简体   繁体   中英

JQuery to change value based on selection in a drop down menu

Using JQuery I'm trying to create a drop-down menu and then change a certain value on a search input element based on what people select in the menu.

So far I've figured out how to target the value I need to change. I've also gotten as far as having it so that if someone makes any selection from the menu, it changes the search input value to one specific value:

<div> 
 <form action="setColor" method="post">
   <fieldset>
     <label for="color">Select A Color</label>
       <select name="color" id="color">
           <option>Blue</option>
           <option selected="selected">Red</option>
           <option>Yellow</option>
      </select>
   </fieldset>
  </form>
</div>


<script> 

  $(function() { 
   $('select[name="color"]').change(function() {
     $('input[name="ancestorId"]').val("9999");
   });
 });

</script> 

What I need now is something that sets the value according to the menu selection, matched up something like this:

Blue = 9999
Red =  8888
Yellow = 7777 

I'm still looking at examples and will keep trying, but kind of stuck. Any advice appreciated.

You should put the value assignment in the option elements, as they were designed for just that:

<select name="color" id="color">
    <option value="9999">Blue</option>
    <option value="8888" selected="selected">Red</option>
    <option value="7777">Yellow</option>
</select>

And the script nearly stays the same, except I've used the elements IDs instead of their names in the selectors (assuming here your ancestor element has such an ID):

$(function() { 
    $('#color').change(function() {
         $('#ancestor').val($(this).val());
    }).change(); // Trigger the event
});

Note that the chained .change() call will trigger the change event that was just assigned, so that the pre-selected item's value will be populated into the text field when the page loads.

See it in action:

 $(function() { $('#color').change(function() { $('#ancestor').val($(this).val()); }).change(); // Trigger the event }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select name="color" id="color"> <option value="9999">Blue</option> <option value="8888" selected="selected">Red</option> <option value="7777">Yellow</option> </select> <input id="ancestor" type="text" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM