Sherly Kim Sherly Kim - 4 months ago 10
Javascript Question

getting the textbox input from javascript using jquery

I have a jquery $.get function to get the data and for each data, I am making a textbox for the user to enter corresponding text.

for(var i = 0; i <data.length; i++){

var newHtml = '<tr><td>'+ idx + '</td><td>' + data[i].name + '</td><td>' + data[i].type + '</td><td>'
+ data[i].required + '</td><td>'+ '<input type="text" id="mValue'+i+'" class="form-control" placeholder="enter number'+i+'" /></td></tr>';
$(newHtml).appendTo('#dt_basic');
idx++;

_currentValues[data[i].name] = $('#mValue');
}


as shown in the code, I made a
</input>
with id of "mValuei" and
i
could be from 0 to the data.length. How do i get the value of the input box? I tried
$('#mValue'+i).val()
but it doesn't seem to work.

Answer

Use value attribute to fill input

 '<input type="text" id="mValue'+i+'" class="form-control" placeholder="enter number'+i+'"  value="'+i+'"/>'

In jquery :

1. Setter :

  $('#mValue'+i).val('new value of input') ;

2. Getter :

  currentVal=$('#mValue'+i).val() ;

Thus, you use val as getter (val() without argument), however, you should use it as setter (with one argument which is the new value of INPUT)


DEMO