Как отключить / включить кнопку отправки в зависимости от состояния флажка? - PullRequest
0 голосов
/ 08 января 2019

Есть форма с двумя текстовыми полями и одним флажком, все они обязательны и имеют обязательный атрибут.

Кнопка отправки должна быть активирована только в том случае, если необходимые данные заполнены и проверены.

С текущим кодом проверка текстового поля, кажется, работает нормально, но не влияет на флажок.

Jsfiddle

<form action="#otherForm">
   Name * <input name="otherForm-name1" placeholder="required" required> <br />
   Tel * <input name="otherForm-surname" placeholder="required" required> <br />
   <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>

<script>
    const inputSelector = ':input[required]:visible';

    function checkForm() {
        // here, "this" is an input element
        var isValidForm = true;
        $(this.form).find(inputSelector).each(function() {
            if (!this.value.trim()) {
                isValidForm = false;
            }
        });
        $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
        return isValidForm;
    }
    $('.monitored-btn').closest('form')
        // in a user hacked to remove "disabled" attribute, also monitor the submit event
        .submit(function() {
            // launch checkForm for the first encountered input,
            // use its return value to prevent default if form is not valid
            return checkForm.apply($(this).find(':input')[0]);
        })
        .find(inputSelector).keyup(checkForm).keyup();
</script>

Ответы [ 5 ]

0 голосов
/ 08 января 2019

Вам необходимо проверять это условие при каждом типе пользователя или устанавливать флажки и отключать его с помощью removeAttr и attr ..

$("form input").keyup(check);
$("form input:checkbox").on("click", check);

function check() {  
 if($("input[name='otherForm-name1']").val() != "" &&
   $("input[name='otherForm-surname']").val() != "" &&
   $("input[name='otherForm-chcekbox']").prop("checked") == true) {
     $("#otherForm-submitBtn").removeAttr("disabled");
     return;
   }
   $("#otherForm-submitBtn").attr("disabled",true);
   
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#otherForm">
   Name * <input name="otherForm-name1" placeholder="required" required> <br />
   Tel * <input name="otherForm-surname" placeholder="required" required> <br />
   <input type="checkbox" name="otherForm-chcekbox" id="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form>
0 голосов
/ 08 января 2019

Я бы сделал это очень похоже на ответ Кубвиманы Адриена с первоначальным отображением отключенной кнопки.

Кроме того, как правило, не считается безопасным устанавливать начальное состояние логических значений проверки на ИСТИНА. Таким образом, немного изменив код.

    const inputSelector = ':input[required]:visible';

    function checkForm() {
        // here, "this" is an input element
        var isValidForm = false;
        $(this.form).find(inputSelector).each(function() {
            if (((this.type != 'checkbox') && (this.value.trim() != "")) || (this.type == 'checkbox' && this.checked)) {
                isValidForm = true;
            }
            else{
            	isValidForm = false
                return false //break out of each loop
            }
        });
        $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
        return isValidForm;
    }
    $('.monitored-btn').closest('form')
        // in a user hacked to remove "disabled" attribute, also monitor the submit event
        .submit(function() {
            // launch checkForm for the first encountered input,
            // use its return value to prevent default if form is not valid
            return checkForm.apply($(this).find(':input')[0]);
        })
        .find(inputSelector).on("keyup change", checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <form action="#otherForm">
         Name * <input name="otherForm-name1" placeholder="required" required> <br />
         Tel * <input name="otherForm-surname" placeholder="required" required> <br />
         <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
         <button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
  </form></body>
0 голосов
/ 08 января 2019

Требуется только CSS

#otherForm-submitBtn {
  enabled: false;
  color: grey;
}

input[type='checkbox']:checked ~ #otherForm-submitBtn {
  enabled: true;
  color: black;
}
<form action="#otherForm">
   Name * <input name="otherForm-name1" placeholder="required" required> <br />
   Tel * <input name="otherForm-surname" placeholder="required" required> <br />
   <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>
0 голосов
/ 08 января 2019

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

const inputSelector = ':input[required]:visible';
function checkForm() {
  // here, "this" is an input element
  var isValidForm = true; 
  $(this.form).find(inputSelector).each(function() {
    if (!this.value.trim() || (this.type == 'checkbox' && !this.checked)) {
      isValidForm = false;
    }
  });
  $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
  return isValidForm;
}
$('.monitored-btn').closest('form')
  // in a user hacked to remove "disabled" attribute, also monitor the submit event
  .submit(function() {
    // launch checkForm for the first encountered input,
    // use its return value to prevent default if form is not valid
    return checkForm.apply($(this).find(':input')[0]);
  })
  .find(inputSelector).on("keyup change", checkForm);
0 голосов
/ 08 января 2019

Отключить кнопку с атрибутом отключения. Затем прослушайте событие изменения флажка и либо удалите атрибут, либо добавьте его.

<form action="#otherForm">
    <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form>



$(".otherForm-chcekbox").change(function() {
    if(this.checked) {
      if (checkForm()) {
        $("otherForm-submitBtn").removeAttr("disabled");   
      }
    } else {
      $("otherForm-submitBtn").attr("disabled", "disabled");   
    }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...