Как я могу проверить флажок с JavaScript? - PullRequest
0 голосов
/ 07 июня 2018

Я новичок в Java-скрипте.Я хочу проверить ввод с типом флажка.Я использовал приведенный ниже код для проверки.

<form onsubmit="return checkForm(this);">
    
    <input type="checkbox" name="terms" value="accept" id="accept" />
    
</form>

    
            function checkForm(form) {
                alert('hello');
                if (form.terms!=check) {
                    alert("Please indicate that you accept the Terms and Conditions");
                    form.terms.focus();
                    return false;
                }
                return true;
            }
    
 <form name="form1" id="form1" runat="server" onsubmit="return checkForm(this);">
 
<input class="farsi-font" type="checkbox" name="terms" value="accept" id="accept" style="color: #000" runat="server" />

 </form>

однако я получаю оповещение («Пожалуйста, укажите, что вы принимаете Положения и условия»); «Форма будет опубликована в базе данных. А проверка просто предупредит пользователяи не помешала форма post.any тело может мне помочь? спасибо

Ответы [ 2 ]

0 голосов
/ 07 июня 2018

Попробуйте:

HTML

<form onsubmit="return checkForm(event, this);">
  <input type="checkbox" name="terms" id="accept" />
</form>

JS

function checkForm(event, form) {
  event.preventDefault();
  if (!form.terms.checked) {
    alert("Please indicate that you accept the Terms and Conditions");
    return false;
  }
  return true;
}

РЕДАКТИРОВАТЬ:

Чтобы отправить формуиспользуя только html, вы можете использовать следующие подходы:

Со входом внутри формы

<form onsubmit="return checkForm(event, this);">
  <input type="checkbox" name="terms" id="accept" />
  <input type="submit" value="Submit the form" />
</form>

С кнопкой снаружи.(Теперь форма должна иметь идентификатор)

<form id="myForm" onsubmit="return checkForm(event, this);">
  <input type="checkbox" name="terms" id="accept" />
</form>
<button type="submit" form="myForm">Submit the form</button>
0 голосов
/ 07 июня 2018

Не знаю, откуда этот код, но вот как я это сделаю:

<input type="checkbox" name="terms" value="accept" id="accept" required />

Обратите внимание на добавление обязательного атрибута.

document.querySelector('#accept').setCustomValidity('Please accept the terms and conditions');

Теперь, когда пользовательотправляет форму, она будет отображать ваше сообщение, если флажок не установлен, форма не будет отправлена.Вы можете проверить это, поместив оператор console.log или debugger в ваш обработчик отправки:

// Note that as I said in the comments, attaching the handler
// this way is preferable to using the onsubmit HTML attribute.
document.querySelector('#form1').addEventListener('submit', function(evt) {
  console.log('stop the presses!');
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...