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
inputfield is just that, an element for user input. If you just need to display information, you should not be using aninputelement, 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" 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" >
