Bruce O. Bruce O. - 4 months ago 24
HTML Question

Having trouble passing a value from one input to another with jquery

I'm doing a little noob project and making a simple "to-do list" and I'm stuck on something that seems so simple! I'm trying to pass the main up top from #myInput and pass it to the next down and so on. Right now, if you enter something then click add, it creates a blank new line at first for some reason then if you type something else and click add, what you typed before shows up on the next line. It will keep doing that for as long as you type something different in the input, but if you keep hitting add a couple times with the same thing in the input, nothing shows up. Then change the input again to something different and click add and all that will show up lol, but still no current line outputs from what you typed...going nuts. Any suggestions on the proper way to do this? I left a JSfiddle link to see exactly what is happening down below.

<div>
<form id="addThings" type="text">
<input type="text" id="myInput" placeholder="add to your to-do list" size="50" maxlength="40" autocomplete="off" autofocus>
<input type="button" id="addButton" value="add">
</form>
</div>


Also, when you click the button and it creates a new line down below it shifts everything around a bit..ideas on what needs to be changed in the css? Trying to get it a little smoother. Thanks!

$(function() {
var i = 2;
$('#addButton').click(function(e) {
var input = $('#myInput').val();
console.log(input);
var id = "newLine" + i;
var line = '<input type=\"text\" id=\"' + id + '\" size=\"50\" disabled><input type=\"checkbox\" >';
$('form').append(line);
var newId = "#" + id;
$('#myInput').change(function() {
$(newId).val(input);
});
i += 1;
});
});


JSFiddle

Answer

Try this. Providing a value to the input field before you append it works well.In your case there is an issue with javascript closure. To solve it just define the input variable outside of the click function

$(function() {
  var i = 2;
  $('#addButton').click(function(e) {
    var input = $('#myInput').val();
    console.log(input);
    var id = "newLine" + i;
    var line = '<input type=\"text\" id=\"' + id + '\" value=\"'+input+'\" size=\"50\" disabled><input type=\"checkbox\" >';
    console.log(line);
    $('form').append(line);

    i += 1;
  });
});

JSFIDDLE