Начинающий программист, нуждающийся в помощи - PullRequest
0 голосов
/ 24 апреля 2020

Я новичок в кодировании. Я создал форму с тремя полями - два с типом «число» и одно с выбором переключателя. Я пытаюсь использовать «try catch throw» для проверки этих полей и отображения сообщений об ошибках на экране (не как предупреждение). Я знаю, что здесь много кода, но я действительно потерян с этим. Вот мои HTML и js:

HTML:

<form>
    <fieldset>
        <label for="hshld" class="formhdr">Total number of people in your household:</label>
        <input type="number"  id="hshld" name="hshld" min="1">
    </fieldset>
    <fieldset>
        <label for="hrrisk" class="formhdr">Number of high-risk people in your household:</label>
        <input type="number"  id="hrrisk" name="hrrisk" min="0">
    </fieldset>
    <fieldset>
        <legend class="formhdr">Number of weeks in isolation:</legend>
        <input type="radio" id="countone" name="headcount">
        <label for="countone" class="numweeks">1</label>
        <input type="radio" id="counttwo" name="headcount">
        <label for="counttwo" class="numweeks">2</label>
        <input type="radio" id="countthree" name="headcount">
        <label for="countthree" class="numweeks">3</label>
        <input type="radio" id="countfour" name="headcount">
        <label for="countfour" class="numweeks">4+</label>
    </fieldset>
    <input type="submit" value="Submit" id="submit">
</form> 

и мои. js:

//Global variables
    var hshld = document.getElementById("hshld");
    var mysubmit = document.getElementById("submit");
    var radioError = document.getElementById("radioError");
    var weekCount;

//this function checks to see if the user entered a number into the field
    function validatehshld() {
        try {
            if (hshld.value == "") {
                throw "Enter a number!";
            }
            hshld.style.outline = "none";
            // clear input box
        }
        catch (hshldError) {
            hshld.style.outline = "2.5px dashed red";
            hshld.placeholder = hshldError;
            return false;
        }
    }

// makes sure that the radio button is selected. If not, throws an error message into the "radioError" paragraph at under the form.
    function validatewkCount() {
        try {
            if (weekCount == 0) {
                throw document.getElementById('radioError').innerHTML = "Select a number!";
                    }
// clear input box
                    hshld.style.outline = "none"; 
                    }
                    catch (weekCountError) {
                        radioError.style.outline = "2.5px dashed red";
                        radioError.placeholder = radioError;
                        return false;
                    }
    }

// stop the form from submitting if a field needs attention
    function endEvent() {
        return event.preventDefault();
    }

    function validateSubmit() {
        if(validatehshld() === false && validatewkCount() === false) {
            endEvent();
        }
    }

// EventListeners, includes IE8 compatibility
        if (hshld.addEventListener) {
            hshld.addEventListener("focusout", validatehshld, false);
        } else if (hshld.attachEvent) {
        hshld.attachEvent("onclick", validatehshld);
        }

// runs validateSubmit() function when the user clicks the submit button
        if (mysubmit.addEventListener) {
            mysubmit.addEventListener("click", validateSubmit, false);
        } else if (mysubmit.attachEvent) {
            mysubmit.attachEvent("onclick", validateSubmit);
        }

        if (mysubmit.addEventListener) {
            mysubmit.addEventListener("click", numBottles, false);
        } else if (mysubmit.attachEvent) {
            mysubmit.attachEvent("onclick", numBottles);
        }

// this function gets called via the onclick attribute (line 44)
    function numBottles() {

// takes the current value of the input field from id "hshld"
        var people = document.getElementById("hshld").value;
        var hrrisk = document.getElementById("hrrisk").value;

        // this variable represents the number of gallons a single person should have for one week of isolation- 1 gallon per day
        var weekWater = 7; 

        // this variable will hold the number of weeks selected from the radio buttons
        var weekCount;

// this code determines which radio button is selected and assigns a value to the variable depending on which radio button is selected
        if (document.getElementById('countone').checked) {
            var weekCount = 1; 
        } else if (document.getElementById('counttwo').checked) {
            var weekCount = 2;
        } else if (document.getElementById('countthree').checked) {
            var weekCount = 3;
        } else if (document.getElementById('countfour').checked) {
            var weekCount = 4;
        } else if (isNaN(weekCount) === true) {
            var weekCount = 0; 
        }

// echo out the calculation (people X weekWater) to the span object with id=bottles
                document.getElementById("bottles").innerHTML = (people * weekWater * weekCount) + (hrrisk * weekCount);
                }

1 Ответ

0 голосов
/ 25 апреля 2020

Старайтесь не использовать try, catch или throw здесь, вместо этого создайте сообщение об ошибке в новом элементе и поместите его в html там, где вы считаете, что это выглядит красиво.

Я бы просто использовал:

if (typeof hshld.value !== 'number') { // if a wrong data type was entered

    document.getElementById("error-zone").innerHTML += "<div>Enter a number!</div"

} else {

    // continue calculating answer

}

для быстрого и грязного метода.

...