You seem to have two main problems:
- You combine HTML and JavaScript into a single block
- You fail to ensure that your JavaScript executes when the user changes the quantity
Your first step should be to separate the <input type="hidden" name="discount" />
out from the JavaScript block. It is HTML not JavaScript, so the JavaScript engine won't know what to do with it.
<input type="hidden" name="discount" />
<script type="text/javascript">
if (quantity==3)
{
value="5.00";
}
else if (quantity==2)
{
value="2.00";
}
else
{
value="0.00";
}
</script>
Next up you need to ensure the JavaScript gets executed when the user changes the quantity. To do this, put your code into a named function and wire that up to the onchange
event if the quantity
element:
<script type="text/javascript">
function updateDiscount()
{
var select = document.getElementById("quantity");
var quantity = select.options[select.selectedIndex].value;
if (quantity==3)
{
value="5.00";
}
else if (quantity==2)
{
value="2.00";
}
else
{
value="0.00";
}
}
document.getElementById("quantity").onchange = updateDiscount;
</script>
Note that we now also look up the quantity value in the JavaScript. This is again because you cannot simply mix JavaScript and HTML in the way you did. For the lookup to work, you will need to add id
attributes to your elements with the same value as your current name
attributes (which are needed when you submit the form).
With these changes you are almost there. You're now setting the discount into a variable value
, while you want it to go into the discount
field of your form. To get this, you'll need to look up that element and set its value, like this:
document.getElementById("discount").value = value;
Complete HTML
<select name="quantity" id="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="amount" value="10.00"/>
<input type="hidden" name="discount" id="discount" />
Complete JavaScript
function updateDiscount()
{
var select = document.getElementById("quantity");
var quantity = select.options[select.selectedIndex].value;
if (quantity==3)
{
value="5.00";
}
else if (quantity==2)
{
value="2.00";
}
else
{
value="0.00";
}
document.getElementById("discount").value = value;
}
document.getElementById("quantity").onchange = updateDiscount;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…