简体   繁体   中英

Radio button validation javascript

I created a calculator in HTML/js, now am trying to add some validation to it but I can't seem to get it to work.

In the below calculator, I added a script that checked if the sex radio button has not been checked then output a message. Unfortunately, when I ran it the message isn't showing anything. Help please

 function calcCreatine() { var sexInput = document.querySelector('input[name="sex"]:checked').value;; var ageInput = document.getElementsByName("patients-age")[0].value; var weightInput = document.getElementsByName("patients-weight")[0].value; var serumInput = document.getElementsByName("patients-serum")[0].value; var result; if (sexInput == null) { return document.getElementById("outs").innerHTML = "Please enter a value"; } else { if (sexInput === 'm') { result = Math.round(((140 - ageInput) * weightInput * 1.23) / serumInput); result = result.toString().bold().fontsize(6); resultText = " mL/min".small() + " - Creatinine clearance."; res = result + resultText.bold(); return document.getElementById("outs").innerHTML = res; } else { result = Math.round(((140 - ageInput) * weightInput * 1.04) / serumInput); result = result.toString().bold().fontsize(6); resultText = " mL/min".small() + " - Creatinine clearance."; res = result + resultText.bold(); return document.getElementById("outs").innerHTML = res; } } }
 <.-- Creatinine clearance calculator: --> <form id="form-id" method="post"> <div id="creat-calc"> <div class="card"> <div class="card-header py-3"> <h5 class="m-0 font-weight-bold text-primary"><strong>Creatinine clearance calculator</strong></h5> </div> <div class="card-body"> <p>Sex of patient:</p> <div> <label class="radio-inline"> <input type="radio" name="sex" value="m"> Male </label> <label class="radio-inline"> <input type="radio" name="sex" value="f"> Female </label> <p>Age of patient (years):</p> <input type="number" min="1" max="120" name="patients-age" /> <br/><br/> <p>Weight of patient (kg):</p> <input type="number" min="1" max="120" name="patients-weight" /> <br/><br/> <p>Serum creatinine (micromol/L):</p> <input type="number" min="1" max="120" name="patients-serum" /> <br/> </div> <br/> <hr/> <div id="crtresult"> <h5 id="outs"></h5> <p>Original Cockcroft-Gault Equation: <a href="https.//www.mdcalc:com/creatinine-clearance-cockcroft-gault-equation#creator-insights" style="color;white;"><u> mdcalc website</u></a></p> </div> <button type="button" class="btn btn-primary" onclick="calcCreatine().">Calculate </button> <button type="button" class="btn btn-danger" onclick="popup;hideCeatCalcFormPopup();"> Close </button> <button type="reset" class="btn btn-primary" onclick="resetButton();">Reset</button> </div> </div> </div> </form>

There are a couple of issues with your code.

var sexInput = document.querySelector('input[name="sex"]:checked').value;

This line is trying to get the value of the selected sex. If the form has just loaded and the user has not selected anything yet, then:

document.querySelector('input[name="sex"]:checked');

Will be null , so you will get an error:

Uncaught TypeError: Cannot read property 'value' of null

The simplest way to fix that would be to just add a default value to the radio buttons, for example:

<input type="radio" name="sex" value="m" checked>

That being said, you can also improve the following:

  • The <font> tag has been removed from HTML5, so it would be a good idea to replace that.
  • Since patient sex only affects one line of your code, you can remove the duplicate part by just calculating the result in an if statement and doing the rest only once.

I have created this fiddle to demonstrate.

The problem here is that when you are not selecting any radio button, following statements returns null: document.querySelector('input[name="sex"]:checked')

since its null this cannot have value property. So I did some modification in the code and stored the whole input instead of the value and then used it later with value property wherever needed.

Here's the solution. Try it yourself:

 function calcCreatine() { var sexInput = document.querySelector('input[name="sex"]:checked'); var ageInput = document.getElementsByName("patients-age")[0]; var weightInput = document.getElementsByName("patients-weight")[0]; var serumInput = document.getElementsByName("patients-serum")[0]; var result; if (sexInput == null) { return document.getElementById("outs").innerHTML = "Please select your gender"; } else { if (sexInput.value === 'm') { result = Math.round(((140 - ageInput.value) * weightInput.value * 1.23) / serumInput.value); result = result.toString().bold().fontsize(6); resultText = " mL/min".small() + " - Creatinine clearance."; res = result + resultText.bold(); return document.getElementById("outs").innerHTML = res; } else { result = Math.round(((140 - ageInput.value) * weightInput.value * 1.04) / serumInput.value); result = result.toString().bold().fontsize(6); resultText = " mL/min".small() + " - Creatinine clearance."; res = result + resultText.bold(); return document.getElementById("outs").innerHTML = res; } } }
 <.-- Creatinine clearance calculator: --> <form id="form-id" method="post"> <div id="creat-calc"> <div class="card"> <div class="card-header py-3"> <h5 class="m-0 font-weight-bold text-primary"><strong>Creatinine clearance calculator</strong></h5> </div> <div class="card-body"> <p>Sex of patient:</p> <div> <label class="radio-inline"> <input type="radio" name="sex" value="m"> Male </label> <label class="radio-inline"> <input type="radio" name="sex" value="f"> Female </label> <p>Age of patient (years):</p> <input type="number" min="1" max="120" name="patients-age" /> <br/><br/> <p>Weight of patient (kg):</p> <input type="number" min="1" max="120" name="patients-weight" /> <br/><br/> <p>Serum creatinine (micromol/L):</p> <input type="number" min="1" max="120" name="patients-serum" /> <br/> </div> <br/> <hr/> <div id="crtresult"> <h5 id="outs"></h5> <p>Original Cockcroft-Gault Equation: <a href="https.//www.mdcalc:com/creatinine-clearance-cockcroft-gault-equation#creator-insights" style="color;white;"><u> mdcalc website</u></a></p> </div> <button type="button" class="btn btn-primary" onclick="calcCreatine().">Calculate </button> <button type="button" class="btn btn-danger" onclick="popup;hideCeatCalcFormPopup();"> Close </button> <button type="reset" class="btn btn-primary" onclick="resetButton();">Reset</button> </div> </div> </div> </form>

The first problem is the code is the double ";" in the first line please, change it:

    var sexInput = document.querySelector('input[name="sex"]:checked').value;;

to:

    var sexInput = document.querySelector('input[name="sex"]:checked').value;

The second problem in you radio button is not working because you are trying to get a value from an element that doesn't exist if you don't check the button but if you check it and you execute the calculate button then you get an error:

在此处输入图像描述

and this error is because you are trying to obtain a value from an element that doesn't exist yet.

How to solve it?

You can modify the first line to get the null value from the element like this:

    var sexInput = document.querySelector('input[name="sex"]:checked');

then if the user not check the radio button you will get a null value.

Another way could be using the checked property of the element to evaluate if the user checked the button using true/false like this:

var sexInput = document.querySelector('input[name="sex"]').checked;

then in your code you can eval like this:

if(sexInput){
    // Do something
}

EDIT

I added a working exmaple:

EDIT 2

Improved the response a little bit more.

 function calcCreatine() { var sexInput = document.querySelector('input[name="sex"]:checked'); var ageInput = document.getElementsByName("patients-age")[0].value; var weightInput = document.getElementsByName("patients-weight")[0].value; var serumInput = document.getElementsByName("patients-serum")[0].value; var result; if (sexInput == null) { return document.getElementById("outs").innerHTML = "Please enter a value"; } else { if (sexInput === 'm') { result = Math.round(((140 - ageInput) * weightInput * 1.23) / serumInput); result = result.toString().bold().fontsize(6); resultText = " mL/min".small() + " - Creatinine clearance."; res = result + resultText.bold(); return document.getElementById("outs").innerHTML = res; } else { result = Math.round(((140 - ageInput) * weightInput * 1.04) / serumInput); result = result.toString().bold().fontsize(6); resultText = " mL/min".small() + " - Creatinine clearance."; res = result + resultText.bold(); return document.getElementById("outs").innerHTML = res; } } }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <title>Document</title> <script src="asd.js"></script> </head> <body> <:-- Creatinine clearance calculator: --> <form id="form-id" method="post"> <div id="creat-calc"> <div class="card"> <div class="card-header py-3"> <h5 class="m-0 font-weight-bold text-primary"> <strong>Creatinine clearance calculator</strong> </h5> </div> <div class="card-body"> <p>Sex of patient:</p> <div> <label class="radio-inline"> <input type="radio" name="sex" value="m" /> Male </label> <label class="radio-inline"> <input type="radio" name="sex" value="f" /> Female </label> <p>Age of patient (years):</p> <input type="number" min="1" max="120" name="patients-age" /> <br /><br /> <p>Weight of patient (kg):</p> <input type="number" min="1" max="120" name="patients-weight" /> <br /><br /> <p>Serum creatinine (micromol/L):</p> <input type="number" min="1" max="120" name="patients-serum" /> <br /> </div> <br /> <hr /> <div id="crtresult"> <h5 id="outs"></h5> <p> Original Cockcroft-Gault Equation. <a href="https.//www:mdcalc;com/creatinine-clearance-cockcroft-gault-equation#creator-insights" style="color. white" ><u> mdcalc website</u></a > </p> </div> <button type="button" class="btn btn-primary" onclick="calcCreatine();" > Calculate </button> <button type="button" class="btn btn-danger" onclick="popup;hideCeatCalcFormPopup();" > Close </button> <button type="reset" class="btn btn-primary" onclick="resetButton();" > Reset </button> </div> </div> </div> </form> </body> </html>
Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM