Issue
I'm a little confused about why my code doesn't work. I'm very new and am extremely interested to know where I went wrong!
I want to times whichever option I choose by var z
but can't get it to work.
This is my code so far:
<td><select>
<option id="VAS" value="70">VAS</option>
<option id="VTS" value="80">VTS</option>
<option id="VAF" value="60">VAF</option>
<option id="VGS" value="40">VGS</option>
</select></td>
<td>
<input type="number" id="number" name="number">
</td>
<td>
<button onclick="myFunction()"> Total Value</button>
<br/>
<br/>
<p id="value"></p>
<script>
function myFunction() {
var y = document.getElementById("VAS").value;
var z = document.getElementById("number").value;
var a = document.getElementById("VGS").value;
var c = document.getElementById("VAF").value;
var d = document.getElementById("VTS").value;
if (value == VGS) {
var x = a * z;
document.getElementById("value").innerHTML = x;
}
else if (value == VAS) {
var x = y * z;
document.getElementById("value").innerHTML = x;
}
}
</script>
Solution
You need to compare the value of the select, not the values of the options. Here's how I fixed your JavaScript code:
function myFunction() {
var a = parseInt(document.getElementById("VAS").parentNode.value);
var z = parseInt(document.getElementById("number").value);
var x = a * z;
document.getElementById("value").innerHTML = x;
}
Fully working demo:
function myFunction() {
var a = parseInt(document.getElementById("VAS").parentNode.value);
var z = parseInt(document.getElementById("number").value);
var x = a * z;
document.getElementById("value").innerHTML = x;
}
<td>
<select>
<option id="VAS" value="70">VAS</option>
<option id="VTS" value="80">VTS</option>
<option id="VAF" value="60">VAF</option>
<option id="VGS" value="40">VGS</option>
</select>
</td>
<td>
<input type="number" id="number" name="number">
</td>
<td>
<button onclick="myFunction()"> Total Value</button>
<br/>
<br/>
<p id="value"></p>
EDIT:
To do this automatically, use oninput
in the number field like so:
<input type="number" id="number" name="number" oninput="myFunction()" />
Demo:
function myFunction() {
var a = parseInt(document.getElementById("VAS").parentNode.value);
var z = parseInt(document.getElementById("number").value);
var x = a * z;
document.getElementById("value").innerHTML = x;
}
<td>
<select>
<option id="VAS" value="70">VAS</option>
<option id="VTS" value="80">VTS</option>
<option id="VAF" value="60">VAF</option>
<option id="VGS" value="40">VGS</option>
</select>
</td>
<td>
<input type="number" id="number" name="number" oninput="myFunction()">
</td>
<td>
<br/>
<br/>
<p id="value"></p>
Answered By - Jack Bashford
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.