skip to Main Content

Need help with jquery script to auto select one of two drop down select box based on manual selection or manual change in either one dropdown.

Form has two drop down selection box, REGNUM and FNAME , Selecting from any one dropdown should auto select another,in both dropdown value in both dropdown is ID number in database.

DB Table:

UID    REGNUM  FNAME     EMAIL
 1      007    James     jbond@
 2      005    Jane      janedoe@
 3      003    John      johndoe@ 
<select id="regnum">
    <option value="1">007</option>
    <option value="2">005</option>
    <option value="3">003</option>
</select>

<select id="fname">
    <option value="1">James</option>
    <option value="2">Jane</option>
    <option value="3">John</option>
</select>

Tried tho check how to do, print Value of selected value from regnum and pass value to fname select .

    $('#regnum').click(function () {
    $('#regnum option:selected').each(function () {
    console.log($(this).val());    
    var vregnum = $(this).val();
    $("#fname option[$vregnum]").attr('selected', true); 
});

});

2

Answers


  1. your are close. u simply made the mistake to add an $ to the var name. By removing it your logging works and this will also work for your goal to select the dropdown from both

    enter image description here

    With this u can select the dropdown from each other:

    $('#regnum').change(function() {
            var selectedValue = $(this).val();
            $('#fname').val(selectedValue);
        });
    Login or Signup to reply.
  2. You could do it like this:

    $("#regnum, #fname").change(function() {
      var v = $(this).val();
      $("#regnum, #fname").not(this).val(v)
    })
    

    This code works for both dropdowns, and then you change 1, then the other will change to match the value.

    Demo

    $("#regnum, #fname").change(function() {
      var v = $(this).val();
      $("#regnum, #fname").not(this).val(v)
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="regnum">
        <option value="1">007</option>
        <option value="2">005</option>
        <option value="3">003</option>
    </select>
    
    <select id="fname">
        <option value="1">James</option>
        <option value="2">Jane</option>
        <option value="3">John</option>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search