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" class="" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes"><option value="">Choose an option</option><option value="Small" class="attached enabled">Small</option><option value="Medium" class="attached enabled">Medium</option><option value="Large" class="attached enabled">Large</option><option value="Extra Large" class="attached enabled">Extra Large</option></select>
<input id="count" name="count" value="5" class="thwepo-input-field ">
How could I achieve this using JQuery? I need the value of Field 2 to update every time Field 1 is changed.
>Solution :
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" class="" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes">
<option value="">Choose an option</option>
<option value="1" class="attached enabled">Small</option>
<option value="2" class="attached enabled">Medium</option>
<option value="3" class="attached enabled">Large</option>
<option value="4" class="attached enabled">Extra Large</option>
</select>
<input id="count" name="count" value="5" class="thwepo-input-field ">
But, a couple of things about this:
-
An
inputfield is just that, an element for user input. If you just
need to display information, you should not be using aninput
element, but rather you should just set thetextContentof a normal
element (like aspanordiv). -
If you want the
valueof anoptionto be the same thing as the
text of theoption, you don’t need to specify thevalueattribute
of theoptionat all – – the text will become the value. But, in your case, you’ve said that you want numbers to be the values of the differentoptions, so thevalueattribute 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" class="" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes">
<option value="">Choose an option</option>
<option value="1" class="attached enabled">Small</option>
<option value="2" class="attached enabled">Medium</option>
<option value="3" class="attached enabled">Large</option>
<option value="4" class="attached enabled">Extra Large</option>
</select>
<input id="count" name="count" value="5" class="thwepo-input-field ">