babi babi - 4 months ago 28
HTML Question

Multiple textboxes fill the dropdown selection having same class in jquery

I have used the concept of multiple textboxes having same class fill with the multiple dropdown option selection which also having same class.I have facing problems in it.when i click the first dropdown option then it change the second textbox value.I want that if i click on first dropdown option it changes the values of first textbox not other or if click the second dropdown option it will change the value of second textbox.

<form action="" method="post">
<select name="drop[]" id="budget" class="drop">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
</select>
<input type="text" name="txt" id="txt" class="txt" value="text1"><br>
<select name="drop[]" id="budget1" class="drop">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
</select>
<input type="text" name="txt" id="txt1" class="txt" value="text2">

</form>


$('input[name="txt"]').each(function () {
$('.drop').on('change', function(){
var total = $(this).val();
$('input[name="txt"]').val($(this).find("option:selected").attr("value"));
});
});

Answer

You need to find out the next input element which should be updated when you change a select element. You can use the below code to achieve this.

    $('.drop').on('change', function(){
        var total = $(this).val();
        $(this).next("input:first").val($(this).find("option:selected").attr("value")); 
    });

Plunker : https://plnkr.co/edit/qFjuFtwhHBvDE9zxAup2?p=preview

Comments