简体   繁体   中英

Dynamically created textbox's value doesnt get updated

I am creating dynamic rows with this code, but the textbox's value is not getting updated as i type. That is as i type i can see the text in the text box but when i fetch/inspect the value it is empty.

I have tried exploring on this but i couldnt understand what's happening, any clues?

$('#add_ans').click(function(){
var rowCount = $('table tbody tr').length + 1;
var rowString = '<tr>\
                    <td><div class="span_5"><span class="badge badge-success">'+rowCount+'</span></div></td>\
                    <td><div class="span3"><input type="text" class="input-large" value="" /></div></td>\
                    <td><div class="span2 pull-right"><b>0</b></div></td>\
                    <td><div class="span2"><button class="btn btn-success" id="vote'+rowCount+'"><b>Vote!</b> <i class="icon-thumbs-up"></i></button></div></td>\
                    <td><div class="span2"><button class="btn btn-info" disabled><b>Reviews</b> <i class="icon-ok-circle"></i></button></div></td>\
                </tr>'
$('tbody').append(rowString);
$('tbody').on("click","#vote"+rowCount,voteOption);

});

and the event handler is

function voteOption(){            
    var rowCount = $('tr').index($(this).closest('tr'));
    alert(rowCount);
    var ans = $('tr:eq('+rowCount+') .input-large').attr('value');
    alert(ans);

}

You're not setting the value attribute in your HTML, so it will remain empty. Just use val() instead of attr('value') :

var ans = $('tr:eq('+rowCount+') .input-large').val();

Alternatively, you can set the value attribute in the HTML you're generating, then retrieve it using the approach you are now.

Here's a jsFiddle with it working correctly: http://jsfiddle.net/Rjrpy/

使用.val()代替.attr('value')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM