Если / Остальное с двумя отмеченными флажками - Javascript - PullRequest
0 голосов
/ 23 мая 2018

Очень простая функция javascript, с которой я застреваю ... (Много гуглил и не могу заставить ее работать полностью!).

В принципе, у меня есть два флажка.И я отказался от своего отказа от ответственности, (только когда оба флажка были отмечены. (См. Полный код ниже).

Если только один / ни один флажок не установлен, отказ от ответственности все еще должен появиться. И форма отправляетсяКнопка отключена.

Все работает нормально. Я могу заставить заявление об отказе от ответственности и деактивировать кнопку, если установлен один флажок. Но, похоже, ничего не делает, с моим оператором if / else ниже.

По сути, «если» в моем операторе if / else не проверяет правильность логики.

Я гуглил и перепробовал множество вариантов. Но не могу заставить это работать.
Спасибо!

  var formInput = document.querySelector("input[name=terms]");
  var marketingInput = document.querySelector("input[name=marketing]");
  var cvSubmitButton = document.querySelector("input[type=submit]");
  var checkBoxDiv = document.getElementById("checkboxRow");
  var scfSubmitButtonBorder = document.querySelector(".scfSubmitButtonBorder");

  cvSubmitButton.classList.add('disabled');
  scfSubmitButtonBorder.style.cursor = "not-allowed";

  var legalClause = document.createElement('div');
  legalClause.innerHTML = "<div id='disclaimer'><br /><p>* Your applicaton cannot be submitted, unless you have agreed to read our Terms of Use, Privacy Policy and Cookie Policy.</p></div>";
  checkBoxDiv.appendChild(legalClause);


  // EVENTLISTENER

    var boxes = document.querySelectorAll('input[type=checkbox]:checked').length;

    formInput.addEventListener("change", function(){

     if((formInput.checked) && (marketingInput.checked)) {

      cvSubmitButton.classList.remove('disabled');
      checkBoxDiv.removeChild(legalClause);
      scfSubmitButtonBorder.style.cursor = "pointer";
      console.log('checked');
     } else {

      cvSubmitButton.classList.add('disabled');
      checkBoxDiv.appendChild(legalClause);
      scfSubmitButtonBorder.style.cursor = "not-allowed";
      console.log('not checked');
     }
  });

И ЗДЕСЬ НАКЛОН HTML:

<div id="checkboxRow" class="scfSectionContent">
<input type="checkbox" name="terms" value="terms">  * I have read and agree with the <a href="/terms-of-user" target="_blank">Terms of Use</a>, <a href="/privacy-policy" target="_blank">Privacy Policy</a> and <a href="/cookie-policy" target="_blank">Cookie Policy</a>.
<br>
<input type="checkbox" name="marketing" value="marketing">  I agree that Adecco Group AG can use my details to send me information about their activities. This may be by post, email, SMS, MMS, phone, social media, push notifications in apps and other means. I understand that I may opt out at any time.
<div><div id="disclaimer"><br><p>* Your applicaton cannot be submitted, unless you have agreed to read our Terms of Use, Privacy Policy and Cookie Policy.</p></div></div></div>

Ответы [ 2 ]

0 голосов
/ 23 мая 2018

Спасибо всем вашим советам!Мне удалось заставить его работать, добавив второго слушателя событий в marketinginput.(Хорошее место для плаката!).И бросил вызов && и ||более четко.

Вот код.Спасибо !!!

  var formInput = document.querySelector("input[name=terms]");
  var marketingInput = document.querySelector("input[name=marketing]");
  var cvSubmitButton = document.querySelector("input[type=submit]");
  var checkBoxDiv = document.getElementById("checkboxRow");
  var scfSubmitButtonBorder = document.querySelector(".scfSubmitButtonBorder");

  cvSubmitButton.classList.add('disabled');
  scfSubmitButtonBorder.style.cursor = "not-allowed";

  var legalClause = document.createElement('div');
  legalClause.innerHTML = "<div id='disclaimer'><br /><p>* Your applicaton cannot be submitted, unless you have agreed to read our Terms of Use, Privacy Policy and Cookie Policy.</p></div>";
  checkBoxDiv.appendChild(legalClause);


  // EVENTLISTENER

  formInput.addEventListener("change", function(){

  if(formInput.checked && marketingInput.checked) {

    checkBoxDiv.removeChild(legalClause);
    scfSubmitButtonBorder.style.cursor = "pointer";
    cvSubmitButton.classList.remove('disabled');     
    console.log('forminput - both checked checked');


  } else {
      cvSubmitButton.classList.add('disabled');
      checkBoxDiv.appendChild(legalClause);
      scfSubmitButtonBorder.style.cursor = "not-allowed";
      console.log('not checked');
  }
 });


marketingInput.addEventListener("change", function(){

  if(marketingInput.checked && formInput.checked) {

checkBoxDiv.removeChild(legalClause);
    scfSubmitButtonBorder.style.cursor = "pointer";
    cvSubmitButton.classList.remove('disabled');     
    console.log('marketinginput - both checked checked');


  } else {

      cvSubmitButton.classList.add('disabled');
      checkBoxDiv.appendChild(legalClause);
      scfSubmitButtonBorder.style.cursor = "not-allowed";
      console.log('not checked');
  }
});
0 голосов
/ 23 мая 2018

Ну, у вас, вероятно, есть два флажка ввода с именными терминами:

  var formInput = document.querySelector("input[name=terms]");

Но вы получаете доступ только к одному и добавляете прослушиватель событий только к одному.Вы должны использовать querySelectorAll и добавить eventListener для каждого из этих флажков.

Например:

var a = document.querySelectorAll("input[name=terms]");

Array.from(a).forEach(item => {
  item.addEventListener("change", function() {
    console.log("Here");
  });
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...