Reputation: 983
This is what I'm trying to do:
The user selects either option "One" or option "Two".
If the user select "One" the result is 66 + 45
or if the user select "Two" the result is 35 + 45
.
How can I implement this using HTML and JavaScript?
This is what I've done so far:
HTML:
<select id="number">
<option>One</option>
<option>Two</option>
</select>
...
// Result
<div id="result"></div>
JAVASCRIPT:
function test(eventInfo) {
var userSelection = document.getElementById("number").value;
if () {
result = 66 + 45;
} else {
result = 35 + 45;
}
var greetingString = userSelection;
document.getElementById("result").innerText = greetingString;
}
Upvotes: 2
Views: 1470
Reputation: 123739
How about this. Set the values in data-attribute and calculate the sum.
<select id="number">
<option value="1" data-Values="66,45">One</option>
<option value="2" data-Values="35,28">Two</option>
</select>
<div id="result"></div>
var values = this.options[this.selectedIndex].getAttribute('data-Values');
var sum = eval(values.split(',').join('+')); //Use with caution eval.
document.getElementById("result").innerHtml = sum;
Upvotes: 2
Reputation: 1084
You can try this one:
<select id="number" onchange="test(this.value);">
<option value="66+45">One</option>
<option value="35+45">Two</option>
</select>
...
// Result
<div id="result">here</div>
JS
<script>
function test(val) {
document.getElementById("result").innerHtml = val;
}
</script>
Upvotes: 0
Reputation: 4370
Use Switch Statement:
Html:
<select id="number">
<option value="66">One</option>
<option value="35">Two</option>
</select>
Javascript:
var userSelection = document.getElementById("number").value;
switch (userSelection)
{
case 66:
result = 66 + 45;
break;
case 35:
result = 35 + 45;
break;
}
Upvotes: 0
Reputation: 147343
Consider:
<select id="number">
<option value="66">One</option>
<option value="35">Two</option>
</select>
then:
result = 45 + +document.getElementById("number").value;
Upvotes: 3
Reputation: 4343
Why don't you use value
:
<select id="number">
<option value="66+45">One</option>
<option value="35+45">Two</option>
</select>
var greetingString = $("#number option:selected").val();
// or document.getElementById("number").value;
document.getElementById("result").innerText = greetingString;
Upvotes: 0