Jordan
Jordan

Reputation: 327

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

Upvotes: 1

Views: 3225

Answers (2)

T J
T J

Reputation: 43166

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>

Upvotes: 2

Mark
Mark

Reputation: 4883

Jquery Solution - Change :

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

Upvotes: 0

Related Questions