简体   繁体   中英

Change the value of input fields, according to what is selected from the Dropdown box

I want my form input values to change automatically according to what is selected from the drop down box. So I basically have a form with three fields, and a <select> tag which has two <option> tags, all of this on the same page, so I want the values of those fields inside the form to update dynamically as different option is selected on the select box.

<select>
  <option>Cake</option>
  <option>Brownie</option>
</select>

<form>
  <input type="text" name="one"></input>
  <input type="text" name="two"></input>
  <input type="text" name="three"></input>
</form>

Basically all the textboxes shoul have the same words of selected option, for example if 'Cake' is selected I want all the textBoxes to display the word Cake, and then if 'Brownie' is selected then all the textBoxes to display Brownie and so forth. Thanks

Simple javascript solution for the html you've provided:

 var select = document.getElementsByTagName('select')[0]; select.addEventListener('change', function () { var texts = document.getElementsByTagName('input'); for (var i = 0; i < texts.length; i++) texts[i].value = select.value; }); 
 <select> <option>Cake</option> <option>Brownie</option> </select> <form> <input type="text" name="one"/> <input type="text" name="two"/> <input type="text" name="three"/> </form> 

Jquery Solution - Change :

<script>
 $(document).ready(function(){
   $("select#YourSelectId").change(function(){
      var b = $("select#YourSelectId :selected").text();
      $("input.TheInputsYouWantToChange").val(b);
   });
});
</script>

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