2 回答
TA贡献1784条经验 获得超7个赞
这里有很多问题:
1-form.option1
不是访问带有 id 的复选框的有效方式option1
。使用document.getElementById("option1")
来代替。同样适用于optionin
和optionout
2- 您的按钮类型为“提交”,它将重新加载页面并重置您的变量laptop
(除非您使用 cookie 或 localStorage 保存它)。防止按钮刷新页面的一种简单方法是将其类型更改为“按钮”。
3- 正如@obscure 的回答所指出的,您应该laptop
在updateCount
函数之外声明您的变量。
4- 我相信您不希望用户同时选择“签入”和“签出”。为此,请使用单选按钮而不是复选框(请注意,两个单选按钮具有相同的name
属性,因此您不能同时选择两者)。
var laptop=1; //will not reset as long as the page is not refreshed
//a way of preventing the from from refreshing the page is to change the button type to "button"
function updateCount (form) {
var laptop = document.getElementById("option1");
var option_in = document.getElementById("checkIn");
var option_out = document.getElementById("checkOut");
if (laptop.checked && option_in.checked) {
laptop++;
alert ("Your response has been recorded - Check In");
}
if (laptop.checked && option_out.checked) {
laptop--;
alert ("Your response has been recorded - Check Out");
}
if (laptop.checked && option_out.checked && laptop===0) {
alert ("Item currently unavailable, choose another item");
}
}
<!DOCTYPE html>
<html>
<h1>CS Equipment Renatal Form</h1>
<form>
<!--top of form with name and line break for text, don't need
anything with the Name: -->
Name:<br>
<!--creating the variable type for textfield and the name of it which
is fullname-->
<input type="text" name="fullname"><br>
<br>
<!--email textfield with line break after meaning new line-->
OU Email:<br>
<input type="email" name="ouemail"><br>
<br>
<!--doing the checkboxes for rental types with id since the id is
used in the script -->
Equipment Rental Type<br>
Laptop <input type="checkbox" name="option1" value="laptop"
id="option1"><br>
Tablet <input type="checkbox" name="option2" value="tablet"
id="option2"><br>
Monitor <input type="checkbox" name="option3" value="monitor"
id="option3"><br>
Camera <input type="checkbox" name="option4" value="camera"
id="option4"><br>
<br>
<!--doing checkboxes for checkout and check with id because its used
in script-->
Select One<br>
Check In <input type="radio" name="changeQty" value="checkIn"
id="checkIn"><br>
Check Out <input type="radio" name="changeQty" value="checkOut"
id="checkOut"><br>
<br>
<!--adding submit button and associating it with script function-->
<input type="button" name="submit" value="submit"
onClick="updateCount(this.form)">
</form>
</html>
为了laptop
在页面刷新时保存变量,请考虑使用 cookie、localStorage 或某些服务器端脚本。
添加回答
举报