Reputation: 69
I've just started programming and I'm at a very basic level, I've just created a form for my student website and I'm trying to validate the Radio Buttons. I know I can just select "checked" in the HTML code but my tutor stipulates it has to be within the JavaScript code. I have researched on here already but the examples many of you have shown haven't worked for me (my fault!) and it just crashes all my previous validations.
Any guidance from all you ninjas is greatly appreciated. Here is a small sample of my code that does work for me as I have deleted the Radio Button validation in frustration, I just want to know how to adapt this code:
<script>
function validate(){
firstname = document.getElementById("txtFirst").value;
errors = "";
if (firstname == ""){
errors += "Please supply a valid First Name \n";
} else if (!firstname.match(/^[a-zA-Z-\s]*$/)){
errors += "Please use only letters in your First Name \n";
}
}
</script>
<body>
<form method="post" action="" class="booking">
<fieldset>
<div>
<label for="txtFirst" class="fixedwidth">First Name</label>
<input type="text" name="txtFirst" id="txtFirst"/>
</div>
<div class="buttonarea">
<input type="submit" value="submit" onclick="validate()"/>
</div>
</fieldset>
</form>
Upvotes: 1
Views: 105
Reputation: 11320
I recommend jQuery for this as you only would need to check $('element').val()
. In JavaScript you have to check document.getElementById('element').value
. Remember to match both name
and id
properties for this to work as you can only select one value in a set of radioboxes.
Upvotes: 1