dimanche 8 février 2015

Validating a html form with javascript

Trying to figure out a javascript exercise that I can't find the answer to.


Here's my base code:



<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple validation</title>
</head>
<body>
<form onsubmit="return validateInput()">
<input type="text" name="txt" id="txt">
<input type="checkbox" name="chk" id ="check_box">
<input type="radio" name="group" value="Radio A" id="radio_a">
<input type="radio" name="group" value="Radio B" id="radio_b">
<input type="submit"/>
</form>

<!-- Display error message in following div -->
<div class="error-message"></div>

<script type="text/javascript">
var form = document.getElementById('frm');
var check_box = document.getElementById('check_box');
var radio_a = document.getElementById('radio_a');
var radio_b = document.getElementById('radio_b');
var text = document.getElementById('text');

function validateInput() {
// function that validates inputs from form and displays the message

//rule 1
if (radio_b.checked === true){
check_box.checked === true;
} else {
document.getElementByClass('error-message').innerHTML = 'RULE 1 FAILED';
}

//rule 2
if (radio_a.checked === true) {
text !== null;
}else{
document.getElementByClass('error-message').innerHTML = 'RULE 2 FAILED';
}
}
</script>
</body>
</html>


What I'm trying to do is write the function that does the following things:


The validation should check the following rules:



  • Rule 1: "chk" may be checked only if "Radio B" is selected.

  • Rule 2: If "Radio A" is selected, the text box must contain a non-empty string.


Depending on failed rules, an appropriate error message should be displayed in the provided div (class “error-message”): - “RULE 1 FAILED”, - “RULE 2 FAILED”, or - “BOTH RULES FAILED”.


I feel like I'm missing something very basic here as I don't have the option to just end it with an else statement that results in 'BOTH RULES FAILED'. Any help would be a lifesaver.





Aucun commentaire:

Enregistrer un commentaire