Jquery simple example change () function
I'm just learning jQuery, I'm so noob.
see, we have 2 divs:
<div id="div1">
<ul>
<li> This is Line 1</li>
<li> This is Line 2</li>
<li> This is Line 3</li>
<li> This is Line 4</li>
<li> This is Line 5</li>
</ul>
</div>
<div id="div2">
<ul>
<li> <input type="text" /></li>
<li> <input type="text" /></li>
<li> <input type="text" /></li>
<li> <input type="text" /></li>
<li> <input type="text" /></li>
</ul>
</div>
since I'm just learning the change () function, this is what I want to do: When each value of the input fields in div2 changes, div1 li of the same number should be changed to the entered value, for example, if we start typing in the second input field in div2 , the second text li should go, what we entered in the second input block.
here is what i have tried so far but not working:
<script type="text/javascript">
$(document).ready(function(){
$('#div2 :input').change(function(i){
var str = $(this).text;
$('#div1 li').eq(i).text(str);
});
});
</script>
What happened to this? thanks in advance
+3
4 answers
The parameter passed to the function change()is not an index. This is eventan object . You need to get the index yourself using index().
$('#div2 :input').change(function() {
var str = $(this).val(), // You need to use `val` to get the value (also, note the "()" here)
index = $(this).parent().index(); // this gets the index of the input
$('#div1 li').eq(index).text(str);
});
+6