输入值未定义

时间:2016-03-23 15:14:14

标签: javascript jquery

SO!

我正在努力学习AJAX。我试图取一个输入框的值,并将其放在屏幕上。但是,当我调用jQuery的.val()函数时,它返回undefined。谁能告诉我为什么会这样?我已经尝试了一切。

<div class="action-center text-center">
    
<div class="input-group input-group-lg">
        
<span class="input-group-addon" id="sizing-addon1"><i class="fa fa-user object"></i></span>
        
<input type="text" class="form-control" id="id1" placeholder="Username" aria-describedby="sizing-addon1">
    
</div>
    
<div class="input-group input-group-lg">
        
<span class="input-group-addon" id="sizing-addon2"><i class="fa fa-coffee object"></i></span>
     
<input type="text" class="form-control object" id="id2" placeholder="Username" aria-describedby="sizing-addon1">
  
</div>
    
<button class="btn btn-success" id="submit">Submit</button>
    
<button class="btn btn-danger remove-action">Remove</button>
</div>

JS:

$(document).ready(function()
{
    $(function()
    {
        var $orders = $('.list-group');
        var $nameFieldGroup = $('#id1');
        var $orderFieldGroup = $('#id2');
        $.ajax({type: 'GET', url: 'test.json', success: function(data)
        {
            $.each(data, function(i, item)
            {
                $orders.append('<li class="list-group-item"><p>Name: '+ item.name + '</p><p>Drink: ' + item.drink +'</p></li>');
            });
        }, error: function()
        {
            alert("AJAX error")
        }});

        $('#submit').on('click', function()
        {
            var order = {name: $nameFieldGroup.val(), drink: $orderFieldGroup.val()};
            $.ajax({type: 'POST', url: 'test.json', data: order, success: function(newOrder)
            {
                $orders.append('<li class="list-group-item"><p>Name: '+ newOrder.name + '</p><p>Drink: ' + newOrder.drink +'</p></li>');
            }});
        });
    });
});

1 个答案:

答案 0 :(得分:-1)

$('#id1')$('#id2')是动态加载控件吗?如果它们是动态控件,请替换

 $nameFieldGroup.val() with $('#id1').val() and $orderFieldGroup.val()  with $('#id2').val()

此外,我同意列出的其他评论意见。问题和代码dees似乎没有关系。