根据表单选择选择新的对象属性和值

时间:2012-05-29 23:33:36

标签: jquery

这段代码是从csv获取数据,将其放入JSON并显示给用户。此外,我正在尝试创建一个对象属性并根据所选值分配其值,但我得到deliveryMethod - undefined

$(document).ready(function() {
$.getJSON('CSV.php', function(data) {

    var prevCardCode = '';
    var newDiv; var NewDiv2;
    var DeliveryMethod;

    $.each(data, function(index, element) {
        var XMLObject = jQuery.extend({}, element);

        if (element['CardCode'] != prevCardCode) {
            newDiv = $('<div/>').addClass('row').appendTo('#showdata');
            $('<div class="sum_field">' + 'Total: ' + element['payment_sum'] + '</div>').appendTo(newDiv);

                $('<div class="options">Delivery Method: <select name="Delivery_Method" id="Delivery_Method"><option value="100" selected="selected">US Mail</option><option value="300">Foreign Mail</option></select></div>').appendTo(newDiv);

                $('select#Delivery_Method').change(function(){
                    DeliveryMethod = $(this).val(); 
                });

                    XMLObject.deliveryMethod = DeliveryMethod;
                    console.log(XMLObject);

        }

        newDiv2 = $('<div/>').addClass('sub_row').appendTo(newDiv);

        prevCardCode = element['CardCode'];

        $.each(element, function(key, value) {

            switch (key) {
                case 'InvKey':
                break;

                default:

                   $('<div class="field">' + value + '</div>').appendTo(newDiv2);
                   break;
            }
          });
      });
   });
});

2 个答案:

答案 0 :(得分:1)

您需要在更改功能之外声明DeliveryMethod:

var XMLObject = {};
var DeliveryMethod;

$('<div class="options">Delivery: <select id="Delivery_Method"><option value="100" selected="selected">US Mail</option><option value="300">Foreign Mail</option><option value="400">UPS Priority - 10am guarantee</option></select></div>').appendTo(newDiv);

 $('#Delivery_Method').change(function(){
   DeliveryMethod = $('select#Delivery_Method').val(); 
   });

    XMLObject.deliveryMethod = DeliveryMethod;
    console.log(XMLObject);

答案 1 :(得分:0)

根据Jquery更改事件,Firefox控制台无法更新。因此,通过打印到html进行测试可以得到我想要的结果。