Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
Sherly Kim Avatar asked Dec 11 '25 06:12

Sherly Kim


1 Answers

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

Elegant Code

$(data.map((e,i)=>
       `<tr>
            <td>${i}</td>
            <td>${e.name}</td>
            <td>${e.type}</td>
            <td>${e.required}</td>
            <td><input type="text" placeholder="enter number${i}" class="form-control" id="mValue${i}" value="${e.name}"></td></tr>`).join('')).appendTo('#dt_basic');
like image 193
Abdennour TOUMI Avatar answered Dec 12 '25 18:12

Abdennour TOUMI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!