3

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.

3
  • Where is the code where you are getting the value? Please include the $.get function code as well. Commented Jul 20, 2016 at 1:40
  • What is _currentValues ? Commented Jul 20, 2016 at 1:45
  • uhm... $('#mValue' + i) has no value, isn't it? If you write some text or set text on $('#mValue' + i), you can get value with $('#mValue'+i).val() or $(".form-control").eq(i).val() Commented Jul 20, 2016 at 1:49

1 Answer 1

2

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');
Sign up to request clarification or add additional context in comments.

3 Comments

if I try currentVal = currentVal + $('#mValue' + i).val(); console.log(currentVal) I get [object Object] in my console
am I doing something wrong? my currentVal is set var currentVal = {}
Enjoy Elegant Code here= > Just ONE line :jsfiddle.net/abdennour/qjs7hj2r/2 . .. hhh :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.