если флажок снят во время отправки формы, он станет красным - PullRequest
0 голосов
/ 26 ноября 2018

У меня есть форма регистрации и там у меня есть два флажка.Если он не отмечен, и клиент нажимает кнопку регистрации, он становится красным.

Ниже приведены мои коды флажков: -

$('#age_confirmation').change(function(){
    var c = this.checked ? '' : 'red';
    $('#age_confirmation').css('color', c);
});
$('#terms_of_service').change(function(){
    var c = this.checked ? '' : 'red';
    $('#terms_of_service').css('color', c);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" accept-charset="utf-8" class="form-signin form-register" role="form" id="register" autocomplete="off">
  <div style="display:none"></div>
  <input type="checkbox" id="age_confirmation" name="age_confirmation" required tabindex="10"/> Age Confirmation
  <input type="checkbox" id="terms_of_service" name="terms_of_service" required tabindex="11"/> Terms of Service
  <input type="submit" class="btn btn-tiffany" value="register" />
</form>

Может кто-нибудь сказать мне, где я не прав.Любая помощь будет оценена.

Ответы [ 6 ]

0 голосов
/ 27 ноября 2018

Другой подход - использовать CSS-селекторы и немного JS.Прежде всего, вам нужно обернуть текст, чтобы повлиять на цвет, как говорили другие пользователи здесь ...

<form action="" method="post" accept-charset="utf-8" class="form-signin form-register" role="form" id="register" autocomplete="off">
   <input type="checkbox" id="age_confirmation" name="age_confirmation" required tabindex="10"/>
   <label for="age_confirmation">Age Confirmation</label>

   <input type="checkbox" id="terms_of_service" name="terms_of_service" required tabindex="11"/>
   <label for="terms_of_service">Terms of Service</label>

   <input type="submit" class="btn btn-tiffany" value="register" />
</form>

Затем вы можете выбрать все label рядом сinvalid input с использованием чистого CSS:

 :invalid + label {
   color: red;
 }

Но при этом метки будут выбраны до того, как вы нажмете кнопку отправки.Итак, мы будем использовать javascript для добавления класса для определения состояния submitting ...

$('input[type=submit]').click(function() {
  $('#register').addClass('submitting');
});

И затем мы можем сопоставить это с помощью CSS ...

.submitting :invalid + label {
  color: red;
}

Вы найдете рабочий пример здесь: https://jsfiddle.net/yL7je0ap/

Преимущества этого решения

  • Сохраняет четкое разделение между CSS и JS
  • Использует встроенныйФункция проверки HTML5
  • Не нужно прослушивать каждое изменение
0 голосов
/ 26 ноября 2018

в вашем коде, были внесены следующие изменения,

  1. Добавлен Span и ID в тексте вашего флажка для окраски текста.
  2. Добавлен атрибут novalidate вотправка формы, так как она препятствовала операции jQuery.

$('#age_confirmation').change(function() {
  var c = this.checked ? '' : 'red';
  $('#age_confirmation_span').css('color', c);
});

$('#terms_of_service').change(function() {
  var c = this.checked ? '' : 'red';
  $('#terms_of_service_span').css('color', c);
});

$("#register").submit(function() {
  var returnStatus = true;
  if ($('#age_confirmation').is(":checked") == true) {
    $('#age_confirmation_span').css('color', '');
  } else {
    $('#age_confirmation_span').css('color', 'red');
    returnStatus = false;
  }
  if ($('#terms_of_service').is(":checked") == true) {
    $('#terms_of_service_span').css('color', '');
  } else {
    $('#terms_of_service_span').css('color', 'red');
    returnStatus = false;
  }
  return returnStatus;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" accept-charset="utf-8" class="form-signin form-register" role="form" id="register" autocomplete="off" novalidate>

  <input type="checkbox" id="age_confirmation" name="age_confirmation" required tabindex="10" /><span id="age_confirmation_span"> Age Confirmation</span>

  <input type="checkbox" id="terms_of_service" name="terms_of_service" required tabindex="11" /><span id="terms_of_service_span"> Terms of Service</span>

  <input type="submit" class="btn btn-tiffany" value="register" />

</form>
0 голосов
/ 26 ноября 2018

Вам необходимо обернуть одноуровневый текст ввода тегом label, а при изменении ввода изменить цвет соответствующей метки.Установка цвета флажка input не влияет на цвет текста рядом с ним.

$('#age_confirmation').change(function(){
  var c = this.checked ? '' : 'red';
  $('#age_confirmation').next().css('color', c);
})
$('#terms_of_service').change(function(){
  var c = this.checked ? '' : 'red';
  $('#terms_of_service').next().css('color', c);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" accept-charset="utf-8" class="form-signin form-register" role="form" id="register" autocomplete="off">
  <input type="checkbox" id="age_confirmation" name="age_confirmation" required tabindex="10"/> 
  <label for="age_confirmation">Age Confirmation</label>
  <input type="checkbox" id="terms_of_service" name="terms_of_service" required tabindex="11"/>
  <label for="terms_of_service">Terms of Service</label>
  <input type="submit" class="btn btn-tiffany" value="register" />
</form>

Также вы можете упростить ваш код

$('#register :checkbox').change(function(){
  $(this).next().css('color', this.checked ? '' : 'red');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" accept-charset="utf-8" class="form-signin form-register" role="form" id="register" autocomplete="off">
  <input type="checkbox" id="age_confirmation" name="age_confirmation" required tabindex="10"/> 
  <label for="age_confirmation">Age Confirmation</label>
  <input type="checkbox" id="terms_of_service" name="terms_of_service" required tabindex="11"/>
  <label for="terms_of_service">Terms of Service</label>
  <input type="submit" class="btn btn-tiffany" value="register" />
</form>
0 голосов
/ 26 ноября 2018

function check(){
if(document.getElementById("age_confirmation").checked ==false){
$("#lbl_age_confirmation").css("color","red");
}else{
$("#lbl_age_confirmation").css("color","black");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" accept-charset="utf-8" class="form-signin form-register" role="form" id="register" autocomplete="off"><div >

<input type="checkbox" id="age_confirmation" name="age_confirmation" required tabindex="10"/> <lable id="lbl_age_confirmation">Age Confirmation</lable>

<input type="checkbox" id="terms_of_service" name="terms_of_service" required tabindex="11"/> Terms of Service

<input onclick="check()" type="submit" class="btn btn-tiffany" value="register" />

</form>
0 голосов
/ 26 ноября 2018

Вы слушаете событие change на каждом флажке.Читая ваш вопрос, я думаю, что вы хотите обработать событие формы submit, а затем предоставить некоторую обратную связь пользователю, что-то вроде ...

РЕДАКТИРОВАТЬ: вам нужно будет обернуть текст флажка в<label> также, чтобы увидеть изменение цвета, как @Juan Mendes заявил в своем ответе

<input id="age_confirmation" ...><label for="age_confirmation">Age</label>

<script>
const age = $('#age_confirmation');
const terms = $('#terms_of_service');
$('#register').submit(function() {
  age.next().css('color', age.checked ? '' : 'red');
  terms.next().css('color', terms.checked ? '' : 'red');
  return age.checked && terms.checked;
})
</script> 
0 голосов
/ 26 ноября 2018

Вы можете сделать это с помощью JavaScript, например:

<script type="text/javascript">
    function validateForm(form){
        if (form.agreement.checked==false){
            alert("Please agree to our Terms and Conditons."); //Here you can do some styling
            //document.getElementById('terms_of_service').classList.add('redColor')
            return false;
        }else{
            //document.getElementById('terms_of_service').classList.add('whiteColor')
        }
    }
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...