Mirza Adil Ali Baig Mirza Adil Ali Baig - 2 months ago 10
jQuery Question

How to populate dynamic input field with dynamic select option in jquery

I am trying to populate input field with the value of selected option both are dynamically loaded. I am able to load selected option value and can update it when option changed. but if there are 10 input field and 10 select option tags and i select one option from 10 tags than all 10 input fields show same value. Every input field have 10 options. I need to change value individually .

here is function of jquery,

$("#myselect").change(function () {
$( "select option:selected" ).each(function() {
$('.returnValue').val($( this ).text());
});
});


I want to insert individual product quantity in input field.

I am struggling for two days please help.

<select id="myselect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>

<input class="returnValue" type="text" value="">

Answer

You can solve your problem in different ways:

If the select and input fields are one after another you may use:

$(this).next('.returnValue').val($( this ).val());

Another approach can be based on adding for each select a new attribute like:

input-field="newlass1"

And so add a new class to the corresponding input field in a way to link the select and input field.

In this case you can do it:

$('input.' + $(this).attr('input-field')).val($( this ).val());

The snippet:

$("[id^=myselect]").change(function () {
  
  
  //$(this).next('.returnValue').val($( this ).val());
  
  
  $('input.' + $(this).attr('input-field')).val($( this ).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>


<select id="myselect1" input-field="newlass1">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<input class="returnValue newlass1" type="text" value=""><br>
<select id="myselect2" input-field="newlass2">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<input class="returnValue newlass2" type="text" value=""><br>
<select id="myselect3" input-field="newlass3">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<input class="returnValue newlass3" type="text" value=""><br>
<select id="myselect4" input-field="newlass4">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<input class="returnValue newlass4" type="text" value="">

Comments