Здесь много вопросов:
1- form.option1
не является допустимым способом доступа к флажку с идентификатором option1
. Вместо этого используйте document.getElementById("option1")
. То же самое касается optionin
и optionout
2- Ваша кнопка имеет тип «отправить», который перезагрузит страницу и сбросит переменную laptop
(если вы не сохраните ее с помощью файла cookie или localStorage). Простой способ предотвратить обновление страницы кнопкой - изменить ее тип на «кнопка».
3 - Как указано в ответе @ obscure, вы должны объявить свою переменную laptop
вне функции updateCount
.
4- Я полагаю, что вы не хотите, чтобы пользователи одновременно выбирали "Check in" и "Check out". Для этого используйте переключатели вместо флажка (обратите внимание, что оба переключателя имеют одинаковый атрибут 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 или некоторых серверных сценариев.