Louis Louis - 5 months ago 13
jQuery Question

How to use event .change between two input in javascript or jquery

I had two problem.

First: i had input the first, i enter value is number into input first then change input second . But i want it change each row when i enter value

Second : After i press enter then append a row. but why at a row which append is no change. Who can help me?thanks

code html:

<form id="myform" name="data" method="post">
<div>
<input name="salary_one[]" class="a" value="" stt=""/>
<input name="salary_two[]" class="" value=""/>

</div>
<div>
<input name="salary_one[]" class="a" value="" stt=""/>
<input name="salary_two[]" class="" value=""/>


</div>
<div>
<input name="salary_one[]" class="a" value="" stt=""/>
<input name="salary_two[]" class="" value=""/>


</div>
<div id="abc">
<input name="salary_one[]" class="a nhay" value="" stt=""/>
<input name="salary_two[]" class="" value=""/>

</div>

<br>

</form>


code javascript:

$('input[name="salary_one[]"]').change(function(){
//$('input[name="salary_one[]"]').attr('stt',0);
var tien=parseFloat($(this).val())*180;
//$(this).attr('stt',1)
//$('input[stt="1"] + input[name="salary_two[]"]').val(tien);

$('input[name="salary_two[]"]').val(tien);
});


code append :

$(document).on('keyup', '.nhay', function (e) {
if (e.keyCode == 13) {
$('.a').removeClass('nhay');
$('#abc').append('<div><input name="salary_one[]" class="a nhay" value="" stt=""/><input name="salary_two[]" class="" value=""></div>');

}

});

Answer

You need to use relationship between elements. The next() method can be used to get immediately following sibling then set the text.

$('#myform').on('input', 'input[name="salary_one[]"]', function() {
   var tien = parseFloat($(this).val()) * 180;
   $(this).next('input[name="salary_two[]"]').val(tien); //Find sibling textbox and set value
 });


 $(document).on('keyup', '.nhay', function(e) {
   if (e.keyCode == 13) {
     $(this).removeClass('nhay');
     $('#myform').append('<div><input name="salary_one[]" class="a nhay" value="" stt=""/><input name="salary_two[]" class="" value=""></div>');
     e.preventDefault(); //To cancel the default action to submit the form
   }
 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" name="data" method="post">
  <div>
    <input name="salary_one[]" class="a nhay" value="" stt="" />
    <input name="salary_two[]" class="" value="" />
  </div>
</form>