Проверка с использованием Javascript - PullRequest
0 голосов
/ 08 ноября 2018

Я пытаюсь проверить этот простой тест, используя Javascript. Идея состоит в том, чтобы предупредить пользователей, когда они забывают ввод при отправке теста.

Я бы хотел, чтобы появилось предупреждение:

  1. Если текст отсутствует,
  2. Если введенный текст содержит более 3 символов,
  3. Когда текст не является положительным или отрицательным, когда один из предложенных вариантов не был отмечен (как для радио, так и для ввода флажка).

Я включу как форму, так и JavaScript ниже, чтобы согласиться с этим, так как считаю необходимым понять проблему (и).

    <form name="quiz" onsubmit="return validateForm();" >
                <ul>
                    <li><label id="web">Do you ever think about how you would design a web page?</label></li>
                    <li><input type="radio" value="no" name="rad1"/><span>No</span></li>
                    <li><input type="radio" value="yes" name="rad2"/><span>Yes</span></li>
                    <li><label for="check">Which the following are your main priorities? If none, please check N/A</label> </li>
                    <li><input type="checkbox" name="op1" value="op1"/><span>Ease of Use</span></li>
                    <li><input type="checkbox" name="op2" value="op2"/> <span>Graphics & Content</span></li>
                    <li><input type="checkbox" name="op3" value="op3"/><span> The Data Collected</span></li>
                    <li><input type="checkbox" name="op4" value="op4"/><span>Securing the site from possible attacks</span></li>
                    <li><input type="checkbox" name="op2" value="op2"/><span>N/A</span></li>
                    <li><label id="res">Do you enjoy conducting research, asking questions, and building reports?</label></li>
                    <li><input type="radio" value="no" name="rad3"/><span>No</span></li>
                    <li><input type="radio" value="yes" name="rad4"/><span>Yes</span></li>
                    <li><label for="text1">Does hacking a system or stopping a system from being hacked sound interesting to you? Type Yes or No:</label></li>
                    <li><textarea name="text1" id="text1" maxlength="3"></textarea></li>
                    <li><input type="submit" value="Finished!" id="submit"></li>
                    <li><input type="reset" id="reset"></li>
                </ul>
            </form>
<script>
    function validateForm() {
        var radio1 = document.quiz.rad1;
        var radio2 = document.quiz.rad2;
        var ch1 = document.quiz.op1;
        var ch2 = document.quiz.op2;
        var ch3 = document.quiz.op3;
        var ch4 = document.quiz.op4;
        var ch5 = document.quiz.op5;
        var radio3 = document.quiz.rad3;
        var radio4 = document.quiz.rad4;
        var tx1 = document.quiz.text1;
        function vWebRes(radio1, radio2, radio3, radio4){
            x=0;
            if(radio1.checked) || (radio2.checked) || (radio3.checked) || (radio4.checked) {
                x++;
            }
            if (x==0) {
                alert('You forgot a question!')
                radio1.focus();
                return false;
            }
            else {
                alert('Completed!');
                window.location.reload()
                return true;
            }
        }
        function vCheck(ch1, ch2, ch3, ch4, ch5){
            y=0;
            if(ch1.checked) || (ch2.checked) || (ch3.checked) || (ch4.checked) || (ch5.checked){
                y++;
            }
            if (y==0) {
                alert('You forgot a question!')
                radio1.focus();
                return false;
            }
            else {
                alert('Completed!');
                window.location.reload()
                return true;
            }
        }
        function vLenght(tx1) {
            var txLength = tx.value.length;
            if (txLength == 0 || txLength < 3) {
                alert("That is an incorrect entry, try again.")
                txLength.focus();
                return false
            }
            else {
                return true
            }
        }
        function vCheck(tx1) {
            if (tx1 == Yes && tx1 == YES && tx1 == yes) || (tx1 == No && tx1 == NO && tx1 == no) {
                tx1.focus();
                return true
            }
            else {
                return false
            }
        }
    }

</script>

Ответы [ 3 ]

0 голосов
/ 08 ноября 2018
<!DOCTYPE html>
<meta charset="utf-8" />
<form name="quiz" onsubmit="return validateForm();">
    <ul>
        <li><label id="web">Do you ever think about how you would design a web page?</label></li>
        <li><input type="radio" value="no" name="rad1" /><span>No</span></li>
        <li><input type="radio" value="yes" name="rad2" /><span>Yes</span></li>
        <li><label for="check">Which the following are your main priorities? If none, please check N/A</label> </li>
        <li><input type="checkbox" name="op1" value="op1" /><span>Ease of Use</span></li>
        <li><input type="checkbox" name="op2" value="op2" /> <span>Graphics & Content</span></li>
        <li><input type="checkbox" name="op3" value="op3" /><span> The Data Collected</span></li>
        <li><input type="checkbox" name="op4" value="op4" /><span>Securing the site from possible attacks</span></li>
        <li><input type="checkbox" name="op2" value="op2" /><span>N/A</span></li>
        <li><label id="res">Do you enjoy conducting research, asking questions, and building reports?</label></li>
        <li><input type="radio" value="no" name="rad3" /><span>No</span></li>
        <li><input type="radio" value="yes" name="rad4" /><span>Yes</span></li>
        <li><label for="text1">Does hacking a system or stopping a system from being hacked sound interesting to you? Type Yes or No:</label></li>
        <!-- <li><textarea name="text1" id="text1" maxlength="3"></textarea></li> -->
        <!-- maxlength changed to higher value or remove it because it is meant to be a paragraph-->
        <li><textarea name="text1" id="text1"></textarea></li>
        <li><input type="submit" value="Finished!" id="submit"></li>
        <li><input type="reset" id="reset"></li>
    </ul>
</form>
<script>
    function validateForm() {
        var radio1 = document.quiz.rad1;
        var radio2 = document.quiz.rad2;
        var ch1 = document.quiz.op1;
        var ch2 = document.quiz.op2;
        var ch3 = document.quiz.op3;
        var ch4 = document.quiz.op4;
        var ch5 = document.quiz.op5;
        var radio3 = document.quiz.rad3;
        var radio4 = document.quiz.rad4;
        var tx1 = document.quiz.text1;

        //call these functions in order to validate
        vWebRes(radio1, radio2, radio3, radio4);
        vCheck(ch1, ch2, ch3, ch4, ch5);
        //document.getElementById() gets the HTML element object according to id in <textarea ... id="text1" ...></textarea>
        vLength(document.getElementById('text1'));



        function vWebRes(radio1, radio2, radio3, radio4) {
            x = 0;
            //inserted missing braces
            if ((radio1.checked) || (radio2.checked) || (radio3.checked) || (radio4.checked)) {
                x++;
            }
            if (x == 0) {
                alert('You forgot a question!')
                radio1.focus();
                return false;
            } else {
                alert('Completed!');
                window.location.reload()
                return true;
            }
        }

        function vCheck(ch1, ch2, ch3, ch4, ch5) {
            y = 0;
            //inserted missing braces
            if ((ch1.checked) || (ch2.checked) || (ch3.checked) || (ch4.checked) || (ch5.checked)) {
                y++;
            }
            if (y == 0) {
                alert('You forgot a question!')
                radio1.focus();
                return false;
            } else {
                alert('Completed!');
                window.location.reload()
                return true;
            }
        }
        // corrected spelling vLenght to vLength
        function vLength(tx1) {
            // fixed tx to tx1
            // var txLength = tx.value.length;
            var txLength = tx1.value.length;
            if (txLength == 0 || txLength < 3) {
                alert("That is an incorrect entry, try again.")
                    //removed the following function because there is no access to the HTML input field unless you would like to add it
                    //txLength.focus();
                tx1.focus();
                return false
            } else {
                return true
            }
        }


        /*
        renamed second vCheck to vCheck2
        this function is just a confusion that overwrites the first vCheck because this function serves nothing useful but fixed anyway
        */

        function vCheck2(tx1) {
            //inserted missing braces
            //in this case, tx1 compares the value '==' as string 
            if ((tx1 == "Yes" && tx1 == "YES" && tx1 == "yes") || (tx1 == "No" && tx1 == "NO" && tx1 == "no")) {
                tx1.focus();
                return true
            } else {
                return false
            }
        }
    }
//good luck
</script>
0 голосов
/ 08 ноября 2018

Вот значительно упрощенная версия:

function validateForm() {

  //Use query selector all to get the humber of checked check boxes
  var numChChecked = document.querySelectorAll("input[type=checkbox][name=op1]:checked").length;

  var numRad1Checked = document.querySelectorAll("input[type=radio][name=rad1]:checked").length;

  var numRad2Checked = document.querySelectorAll("input[type=radio][name=rad2]:checked").length;

  var text = document.getElementById("text1");

  //Check there is atleast 1 Checkbox checked
  if (numChChecked == 0) {
    alert("You missed a question")
    document.quiz.op1[0].focus();
    return false;
  }


  //Check there is atleast 1 radio button checked
  if (numRad1Checked + numRad2Checked === 0) {
    alert("You missed a question");
    document.quiz.rad1[0].focus();
    return false;
  }

  //Check the text length
  if (text.value.length > 3 || text.value.length === 0) {
    alert("Invalid response length");
    text.focus();
    return false;
  }

  //Nortmalise the case to lower case to simplyfy the check
  //also note the " this denotes a string.
  if (!(text.value.toLowerCase() === "yes" || text.value.toLowerCase() === "no")) {
    alert("Invalid response");
    text.focus();
    return false;
  }

  alert("Success");
  return true;
}
<form name="quiz" onsubmit="return validateForm();">
  <ul>
    <li><label id="web">Do you ever think about how you would design a web page?</label></li>
    <!-- note the radio buttons must have the same name if you want to 
    toggle between them -->
    <li><input type="radio" value="no" name="rad1" /><span>No</span></li>
    <li><input type="radio" value="yes" name="rad1" /><span>Yes</span></li>
    <li><label for="check">Which the following are your main priorities? If none, please check N/A</label> </li>
    <!-- If these are a groupm they probably should have the same name -->
    <li><input type="checkbox" name="op1" value="op1" /><span>Ease of Use</span></li>
    <li><input type="checkbox" name="op1" value="op2" /> <span>Graphics & Content</span></li>
    <li><input type="checkbox" name="op1" value="op3" /><span> The Data Collected</span></li>
    <li><input type="checkbox" name="op1" value="op4" /><span>Securing the site from possible attacks</span></li>
    <li><input type="checkbox" name="op1" value="op2" /><span>N/A</span></li>
    <li><label id="res">Do you enjoy conducting research, asking questions, and building reports?</label></li>
    <!-- note the radio buttons must have the same name if you want to 
    toggle between them -->
    <li><input type="radio" value="no" name="rad3" /><span>No</span></li>
    <li><input type="radio" value="yes" name="rad3" /><span>Yes</span></li>
    <li><label for="text1">Does hacking a system or stopping a system from being hacked sound interesting to you? Type Yes or No:</label></li>
    <li><textarea name="text1" id="text1" maxlength="4"></textarea></li>
    <li><input type="submit" value="Finished!" id="submit"></li>
    <li><input type="reset" id="reset"></li>
  </ul>
</form>

Обратите внимание, у вас есть некоторые проблемы с вашим HTML. Группы радиокнопок или флажков должны иметь одинаковое имя

Для получения дополнительной информации о некоторых методах, которые я использовал выше, смотрите:

  1. querySelectorAll , который имеет важные отличия от querySelector
  2. getElementById
  3. селектор атрибутов
  4. Флажки
  5. Псевдокласс :checked
  6. toLowerCase
0 голосов
/ 08 ноября 2018

Вам не хватает скобок для ваших операторов if и функции внутри не нужны. Ваш код JS должен быть:

function validateForm() {
    var radio1 = document.quiz.rad1;
    var radio2 = document.quiz.rad2;
    var ch1 = document.quiz.op1;
    var ch2 = document.quiz.op2;
    var ch3 = document.quiz.op3;
    var ch4 = document.quiz.op4;
    var ch5 = document.quiz.op5;
    var radio3 = document.quiz.rad3;
    var radio4 = document.quiz.rad4;
    var tx1 = document.quiz.text1;

  x=0;
  if(radio1.checked || radio2.checked || radio3.checked || radio4.checked) {
    x++;
  }
  if (x==0) {
    alert('You forgot a question!')
    radio1.focus();
    return false;
  }
  else {
    alert('Completed!');
    window.location.reload()
    return true;
  }

  y=0;
  if(ch1.checked || ch2.checked || ch3.checked || ch4.checked || ch5.checked){
    y++;
  }
  if (y==0) {
    alert('You forgot a question!')
    radio1.focus();
    return false;
  }
  else {
    alert('Completed!');
    window.location.reload()
    return true;
  }

  var txLength = tx.value.length;
  if (txLength == 0 || txLength < 3) {
    alert("That is an incorrect entry, try again.")
    txLength.focus();
    return false
  }
  else {
    return true
  }

  if ((tx1 == Yes && tx1 == YES && tx1 == yes) || (tx1 == No && tx1 == NO && tx1 == no)) {
    tx1.focus();
    return true
  }
  else {
    return false
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...