Мой код JavaScript не увеличивается / не уменьшается в операторе if - PullRequest
0 голосов
/ 13 июня 2019

Я создаю форму, которая будет иметь несколько элементов для выбора и регистрации (добавление / увеличение) и извлечение (минус / уменьшение), и она будет работать только тогда, когда переменная ноутбука равна 1. Я хочу установитьОбщая сумма элемента, а затем любой выбранный параметр будет увеличивать или уменьшать переменную, связанную с этим элементом.Я также не могу найти способ убедиться, что переменная не будет сбрасываться каждый раз, когда форма закрывается и открывается снова.

    function updateCount (form) {
	    //need to figure out way for count to not reset to total when closing 
    form
	    //only works when set to 1
	    var laptop=1;
	    if (form.option1.checked && form.optionin.checked) {
		    laptop++;
		    alert ("Your response has been recorded");
	    }
	    if (form.option1.checked && form.optionout.checked) {
		    laptop--;
		    alert ("Your response has been recorded"); 
	    } 
	    if (form.option1.checked && form.optionout.checked && laptop===0) {
		    alert ("Item currently unavailable, choose another item");
	    }}
    <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="checkbox" name="optionin" value="checkIn" 
    id="checkOut"><br>
	    Check Out <input type="checkbox" name="optionout" value="checkOut" 
    id="checkIn"><br>
	    <br>
	    <!--adding submit button and associating it with script function-->
	    <input type="submit" name="submit" value="submit" 
    onClick="updateCount(this.form)">

    </form>

Ответы [ 2 ]

1 голос
/ 13 июня 2019

Я полагаю, var laptop=1; должно содержать количество доступных ноутбуков.

Проблема здесь в том, что вы объявляете это внутри функции, которая должна фактически управлять им - поэтому вы в основном сбрасываете ее при каждом вызове этой функции.

Чтобы обойти это, вам нужно сделать ее глобальной переменной, которая определяется до и вне function updateCount (form) { }.

Кроме того, вы должны избавиться от события onclick в поле ввода и вместо этого использовать событие onsubmit в самой форме. Таким образом, вы можете проверить форму перед ее отправкой.

Взгляните на этот пример:

var laptop = 1;

function updateCount(form) {

  if (form.option1.checked && form.optionin.checked) {
    laptop++;
    alert("Your response has been recorded");
    return true;
  }
  if (form.option1.checked && form.optionout.checked) {
    laptop--;
    alert("Your response has been recorded");
    return true;
  }
  if (form.option1.checked && form.optionout.checked && laptop === 0) {
    alert("Item currently unavailable, choose another item");
    return false;
  }
  return false;
}
<h1>CS Equipment Renatal Form</h1>
<form onsubmit="return updateCount(this)">
  <!--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="checkbox" name="optionin" value="checkIn" id="checkOut"><br> Check Out <input type="checkbox" name="optionout" value="checkOut" id="checkIn"><br>
  <br>
  <!--adding submit button and associating it with script function-->
  <input type="submit" name="submit" value="submit">
0 голосов
/ 13 июня 2019

Здесь много вопросов:

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 или некоторых серверных сценариев.

...