Home > Mobile >  How to set an input field value based on the value of another field?
How to set an input field value based on the value of another field?

Time:05-17

Field 1 [attribute_size]
Drop down menu Values: Small, Medium, Large, Extra Large

Field 2 [count]
Input text Value: Set value depending on Field 1 input based on the following mappings

Small = 1
Medium = 2
Large = 3
Extra Large = 4

<select id="size"  name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes"><option value="">Choose an option</option><option value="Small" >Small</option><option value="Medium" >Medium</option><option value="Large" >Large</option><option value="Extra Large" >Extra Large</option></select>

<input id="count" name="count" value="5" >

How could I achieve this using JQuery? I need the value of Field 2 to update every time Field 1 is changed.

CodePudding user response:

You would set up a change event handler on the select that sets the value of the input:

const $input = $("#size");
$input.change(function(){
  $("#count").val($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="size"  name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes">
  <option value="">Choose an option</option>
  <option value="1" >Small</option>
  <option value="2" >Medium</option>
  <option value="3" >Large</option>
  <option value="4" >Extra Large</option>
</select>

<input id="count" name="count" value="5" >

But, a couple of things about this:

  • An input field is just that, an element for user input. If you just need to display information, you should not be using an input element, but rather you should just set the textContent of a normal element (like a span or div).

  • If you want the value of an option to be the same thing as the
    text of the option, you don't need to specify the value attribute of the option at all - - the text will become the value. But, in your case, you've said that you want numbers to be the values of the different options, so the value attribute should reflect that.

  • The scenario you've asked about is extremely simple and JQuery is probably overkill to accomplish it. Here's what the code would be with vanilla JavaScript:

const input = document.getElementById("count");
document.getElementById("size").addEventListener("change", function(){
  input.value = this.value;
});
<select id="size"  name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes">
  <option value="">Choose an option</option>
  <option value="1" >Small</option>
  <option value="2" >Medium</option>
  <option value="3" >Large</option>
  <option value="4" >Extra Large</option>
</select>

<input id="count" name="count" value="5" >

  • Related