here is a link to a jsfiddle if you would like to play with it yourself
Using javascript
and html
only. This will update the textbox with the value selected onchange
.
By setting the onchange
attribute on the select tag, you register the updateInput()
function as a listener to the onchange
event.
Then inside the function you can use document.getElementsByName()
to access the elements and manipulate their values. Notice that document.getElementsByName()
returns an array-like collection of elements, therefore requiring us to select the first element like so
document.getElementsByName("elementNameGoesHere")[0]
index of the element we want to select goes here --------^
<select class="select" name="discount" onchange="updateInput()">
<option value="5" selected>5% discount</option>
<option value="10">10% discount</option>
<option value="20">20% discount</option>
</select>
<select class="select" name="cost" onchange="updateInput()">
<option value="500" selected>$500</option>
<option value="100">$100</option>
<option value="20">$20</option>
</select>
<input type="text" name="price" value="">
<script>
function updateInput(){
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
</script>
here is a link to a jsfiddle if you would like to play with it yourself