How do I validate radiobuttons using a javascript function? - javascript

I have a computing assignment to do.
I've done most I'm just stuck on this task:
"Add a set of radio buttons to the form to accept a level of entry such as
GCSE, AS or A2. Write a function that displays the level of entry to the user
in an alert box so that the level can be confirmed or rejected."
I have done the Radio Buttons I just don't know how to do the second part with the Alertbox and function.
So far my code looks like this:
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value == "") {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color = "red";
result = false;
}
if (msg=="") {
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<! Main HTML content begins >
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr></tr>
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examinationno">Examination Number</td>
<td><input type="text" name="examno" maxlength="4" /></td>
</tr>
<tr>
<td><input type="radio" name="Level" value="GCSE">GCSE</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="AS">AS</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="A2">A2</td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>

All you have to do is add the value of the radio button to the message like this:
msg += "Level of Entry: "+document.ExamEntry.Level.value;
Here is a fiddle demo you can try
EDIT #1: Though it has been said to use an alert box, that wouldn't actually allow the user to confirm or reject, for that, you could use confirm instead:
if (confirm("Click OK to confirm your Level of Entry or Cancel if you would like to correct it"))
return true;
else
return false;
In my example, I added it only in case the rest of the form validation was successful: http://jsfiddle.net/Qd8sk/2/
EDIT #2: Following our conversation, I updated the jsfiddle you created. It is much more simple than what you provided.
Here is yours: http://jsfiddle.net/Kjxmn/
Here is mine: http://jsfiddle.net/Kjxmn/2/
Several things I changed:
-1. Added return in front of the function name in onchange - looks like otherwise it would still submit even on return false.
-2. Corrected the form name that you called radioform this time, not Exam Entry.
-3. Got rid of the slightly cumbersome check of the selected value using if (document.radioform.level.value == '') instead.
-4. Added the confirm check.
EDIT #3: Looks like firefox doesn't like the usage of document.ExamEntry.Level.value for radio buttons, so instead I created a quick workaround that would loop through the elements of document.ExamEntry.Level and find the one that is 'selected' ('checked' actually - even though it's a radio button, the js code is still called 'checked').
Have a look at the updated fiddle: http://jsfiddle.net/Qd8sk/3/

function confirm () {
var alerttxt = "Are you sure you want to choose",
value = document.ExamEntry.name.value;
alerttxt += value;
alert(alerttxt);
}
The value variable holds the value the user chose in the radio button, you just want to append that to a message you make up and display that whole txt in an alert

Related

JavaScript "Live" form validation

I am trying to get an alert whenever a user clicks on the username or password input field and exits it without entering. However, I am able to get this to work after using "onblur" instead of "onfocus" (Thanks to Gurvinder's answer below). Now, the alert seems to work for both the fields when I click outside of the form using "onfocus". However, when I use tab key to get to password field from username field to password field, the "passwordCheck" function keeps running. Please help.
<!DOCTYPE html>
<html>
<head>
<title>Javascript exercises</title>
<meta charset="UTF-8">
</head>
<body>
<form name="myForm" >
<table>
<tr>
<td>Username:</td>
<td><input name="username" id="userName" type="text" onfocus="userNameCheck();"></input></td>
</tr>
<tr>
<td>Password:</td>
<td><input name="password" id ="password" type="password" onfocus="passwordCheck();"></input></td>
</tr>
<tr>
<td></td>
<td><input type="Button" value="Submit"></input></td>
</tr>
</table>
</form>
<script>
//User name field validator - Alert a message for empty input fields
var userNameCheck = function() {
if(document.myForm.username.value == ""){
alert("User Name cannot be blank");
}
else{
return false;
}
}
//password field validator - Alert a message for empty input fields
var passwordCheck = function() {
if(document.myForm.password.value == ""){
alert("Password cannot be blank");
}
else{
return false;
}
}
</script>
</body>
</html>
I want the username input to show an alert if the user clicks on it
and tabs to the next field without entering any data.
If you are using focus event to check for the input validity, then unless value is pre-populated, alert will keep coming.
Use blur event, onblur instead of onfocus.
<td><input name="username" id="userName" type="text" onblur="userNameCheck();"></input></td>
Demo
<body>
<form name="myForm">
<table>
<tr>
<td>Username:</td>
<td><input name="username" id="userName" type="text" onblur="userNameCheck();"></input>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input name="password" id="password" type="password"></input>
</td>
</tr>
<tr>
<td></td>
<td><input type="Button" value="Submit"></input>
</td>
</tr>
</table>
</form>
<script>
//User name field validator - Alert a message for empty input fields
var userNameCheck = function() {
if (document.myForm.username.length >= 1) {
//Nothing happens
} else {
alert("User Name cannot be blank");
return false;
}
}
</script>
</body>
Why not create your own 'alert' div for more control (and better user experience).
$("input").focus(function(){
var x = document.forms["myForm"]["password"].value;
if (x == "") {
/*alert("Password cannot be blank");*/
$('.alert').show();
return false;
}
});
And to specify tab key scenario, try:
function checkTabPress(key_val) {
if (event.keyCode == 9) {
$('.alert').hide();
}
}

Issues testing HTML web form

I'm trying to test a HTML web form, but I'm experiencing some problems.
The form opens a secondary HTML file (showing a success message) if all data is entered correctly. If data is not entered, or if data is entered incorrectly, the field name should turn red and a message is displayed directing the user to re-enter the information.
I opened the file directly from Finder (I'm on Mac) to Google Chrome, where it displays fully. However, regardless of what I put (or don't put) in the input fields, the code directs me to the success message.
The code is as follows:
<head>
<title>Form</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.Entry.name.value=="") {
msg+="You must enter your name \n";
document.Entry.name.focus();
document.getElementById(‘name’).style.color="red";
result = false;
}
if (document.Entry.age.value=="") {
msg+="You must enter your age \n";
document.Entry.age.focus();
document.getElementById(‘age’).style.color="red";
result = false;
}
if (document.Entry.number.value=="") {
msg+="You must enter your number \n";
document.Entry.number.focus();
document.getElementById(‘number’).style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Form</h1>
<form name="Entry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="age">Age</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td id=”number”>Number</td>
<td><input type="text" name="number"/></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return
validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
I have looked over the code and I am sure it is correct, so why doesn't the HTML work as intended?
Your code contains errors including:
Wrong " ' " chars
Wrong ' " ' chars
Using the reserved word 'number'
The following is the fixed working (at least in Firefox) code:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.Entry.name.value=="") {
msg+="You must enter your name \n";
document.Entry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.Entry.age.value=="") {
msg+="You must enter your age \n";
document.Entry.age.focus();
document.getElementById('age').style.color="red";
result = false;
}
if (document.Entry.mumber.value=="") {
msg+="You must enter your number \n";
document.Entry.mumber.focus();
document.getElementById('number').style.color="red";
result = false;
}
if(msg == ""){
return result;
}
else
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Form</h1>
<form name="Entry" id="Entry" method="post" action="success.html" onsubmit="return validateForm()">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="age">Age</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td id="number">Number</td>
<td><input type="text" name="mumber"/></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
It will be wise to initiate the 'result' variable as 'false'. This way you need to update it only once - when 'msg' is empty.
It seems that you should choose some other editor/IDE. Also, try to debug your JS scripts - you have debuggers for all modern browsers. I personally use Firebug addon for Firefox. Many people use Chrome developer tools.
Also, you may find this simple reference handy:
http://www.w3schools.com/js/js_form_validation.asp
Your form action is success.html so your form is submitting to this page regardless of your javascript.
The Javascript function is firing on click but its a submit button so the submit is still firing. The page its submitted to is success.html so this is continually being called regardless because the form is continuously being submitted.
The issue comes from how you are accessing the form inputs. Type this into a console, or at the start of your script block:
console.log(document.Entry);
It'll print out undefined. Your code is throwing an error, failing and never returning a false value to prevent the form from submitting.
I suggest taking a look at this question to see various ways of accessing form inputs using vanilla javascript.
I've rewrite your code. Now it's working. You can check working example JSFiddle - http://jsfiddle.net/uj5xcp26/ or copy&paste example below:
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Form</h1>
<form name="Entry" method="post" action="">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td id="subject">Age</td>
<td><input type="text" name="age" id="age" /></td>
</tr>
<tr>
<td id=”number”>Number</td>
<td><input type="text" name="number" id="number"/></td>
</tr>
<tr>
<td><button onclick="validateForm();" id="submit_btn" type="button" name="Submit" value="Submit">Submit</button></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
<script type="text/javascript">
//Assuring page is loaded
document.onload = function(){
validateForm();
};
var validateForm = function() {
var result = true;
var msg="";
var name,age,number;
name = document.getElementsByName("name")[0];
age = document.getElementsByName("age")[0];
number = document.getElementsByName("number")[0];
//Conditionals
if (name.value =="") {
msg+="You must enter your name \n";
name.focus();
name.style.color="red";
result = false;
}
if (age.value=="") {
msg+="You must enter your age \n";
age.focus();
age.style.color="red";
result = false;
}
if (number.value=="") {
msg+="You must enter your number \n";
number.focus();
number.style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg);
return result;
}
};
</script>
</body>
</html>
Firstly try putting your script after your form in the body.
Secondly I agree with above your form action will fire regardless. Can you not handle message with innerHTML.

Checking that at least one textarea is filled

I need help with adding a controll that checks that atleast one on the textareas is filled so that people wouldnt save blank forms. so it should controll that at least on element is checked and filled, otherwise it should give an error and wouldnt save. If anyone would have an idea how to do so, I would greatly appreciate it. The code that Im working with is down below (actually have more textareas but they are the same only with another names).
<tr>
<td valign="top" style='width: 300px;'>Family members help</td>
<%
elemText = xml.getElementFromXPath("//nursing_care/family_help/tekst");
%>
<td valign="top"><input <%=(elemText==null?"checked=\"checked\"":"") %> value="0" onclick="javascript:showText(this);" name="//nursing_care/family_help" type="radio" checked="checked">Valimata
<input <%=(elemText!=null?"checked=\"checked\"":"") %> value="1" onclick="javascript:showText(this);" name="//nursing_care/family_help" type="radio">Määratud</td>
<td>
<textarea style='width: 350px' style="display:<%=(elemText==null?"none":"block") %>" id="//nursing_care/family_help/tekst" name="//nursing_care/family_help/tekst"><%=(elemText!=null?elemText.getText():"") %></textarea>
</td>
<td><input style="display:<%=(elemText==null?"none":"block") %>" type="text" class="txt_left" id="//nursing_care/family_help/date" name="//nursing_care/family_help/date" value="<%=xml.getText("//nursing_care/family_help/date")%>" maxlength="10" size="10"
onchange="gnlDateValid(this,event); if(event.returnValue != false);" onfocus="gnlGotFocus(getCurrentDate(),this); inputChanged(this);" onkeydown="gnlKeyDown('00.00.0000',this,event);" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3"><input type="submit" class="button_save button" value="Salvesta" />
<input type="button" class="button" value="Sulge" onclick="window.close()" /></td>
</tr>
</tfoot>
And here is the function that shows/hides the textareas (just in case)
function showText(obj){
var elements = document.getElementsByName(obj.name);
var element = getNode(obj.name + "/tekst");
if (elements[0].checked)
element.style.display="none";
else
element.style.display="block";
var element = getNode(obj.name + "/date");
if (elements[0].checked)
element.style.display="none";
else
element.style.display="block";
}
Something like this should work.
Extend the submit button like this.
<input type="submit" class="button_save button" value="Salvesta" onclick="return submitCheck()"/>
and implement this function in your javascript file.
function submitCheck(){
var form = document.forms[0];
var textareas = form.getElementsByTagName("textarea");
for(var textarea in textareas){
if(textarea.value !== ""){
return true;
}
}
return false;
}
BTW i would recommend you to use jQuery when working with the HTML DOM ;-)

Alert Box not showing up in JavaScript

I am new to JavaScript and trying to learn it. I just have a text field and want to check if it is empty. I am doing it successfully but now i want to check that if it contains only asterisk (*) in a new JavaScript function! my code is showing the alert box Please help me if i am doing something wrong my code is:
<html>
<head>
<script>
function Verify(){
if(!isNameEmpty()){
return false;
}
if(isNotValidName()==false){
return false;
}
}
function isNameEmpty(){
var name=document.nicform.name.value;
if(name==""){
alert("Please Enter Your Name!");
return false;
}
}
function isNotValidName(){
var name=document.nicform.name.value;
if(name=="*"){
alert("hello star");
return false;
}
}
</script>
<title>
NIC FORM EXAMPLE
</title>
</head>
<body>
<form name="nicform" onsubmit = "return Verify()">
<table border="1" width="400px">
<th>
FILL IN ALL THE FIELDS!
</th>
<tr>
<td>
Name:
</td>
<td>
<input type="text" id="name" maxlength="10" size="30">
</td>
</tr>
<tr>
<td>
Age:
</td>
<td>
</td>
</tr>
</table>
</form>
</body>
change this:
var name=document.nicform.name.value;
to:
var name = document.getElementById('name');
And submit your form with js\a button\etc..
Your code is a little messed up. I didn't fix it..only made it work.
Check this plnkr:
PLNKR
It is best to target by ID as mentioned by Amiros.
However, if your form was submitting fine before, perhaps try replacing your JavaScript with this:
function Verify(){
var name=document.nicform.name.value;
if(name==""){
alert("Please Enter Your Name!");
} else if(name=="*"){
alert("hello star");
}
return false;
}

javascript checkbox validation checking

I have problem with my checkbox validation on my Tip Area Soccer Game. So if the user likes to tip a game, he must have to use 2 inputs field and the confirmation checkbock. But if the user uses 2 inputs fields and "more than one" confirmation checkbox, then he must get an alert error message. Because the right combination consists from "2 input fields + confimration checkbox" Here, in my screenshot you see the right combination for the green submit button:
And in the second screenshot you see the error combination:
I don't have any idea of how to code the alert for the error message on the display if the user uses the second combination.
Here's my Javascript code:
function chkAddTip(){
var inputs = document.getElementById('AddTip').getElementsByTagName('input');
// boolean flag
var foundValid = false;
// early exit the loop if at least one valid bet has been found
for (var i = 0; i < inputs.length && !foundValid; i += 3){
if (inputs[i].type !== "submit" && (inputs[i].value && inputs[i + 1].value && inputs[i + 2].checked)) {
// set the flag to true when a valid bet is found
foundValid = true;
}
}
// determine the return value depending on the flag
if (foundValid) {
return true;
}
else {
alert("Bitte deinen Tipp und die Bestättigung abgeben.")
inputs[0].focus();
return false;
}
And here my form code:
<form action="Ctipservlet" id="AddTip" onsubmit="return chkAddTip()" method="POST">
<div id="inhalt"><h1>Tip Area</h1>
<table>
<tbody>
<tr>
<th>Playdate</th>
<th>Playtime</th>
<th>Games</th>
<th>Your Tip</th>
<th>Confirmation</th>
</tr>
<tr>
<td>21.07.</td>
<td>19:30 Uhr</td>
<td>Schalke - Bayern</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a0" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b0" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check0"></td>
</tr>
<tr>
<td>22.07.</td>
<td>20:30 Uhr</td>
<td>Dortmund - Leverkusen</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a1" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b1" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check1"></td>
</tr>
<tr>
<td>23.07.</td>
<td>15:30 Uhr</td>
<td>Wolfsburg - Nürnberg</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a2" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b2" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check2"></td>
</tr>
</tbody>
</table>
<input class="button_green" type="submit" name="tip" value="Submit Tip">
<input class="button_blue" onclick="this.form.onsubmit = null" type="submit" name="back" value="Back">
</div>
</form>
I hope someone have idea for this checking
We talked in chat, looked at this. Below is my solution but first... this is badly structured. You are doing validation and form submission in one step. I would break it up in to more then one. It just makes debugging/extension easier in the long run. I would validate inputs first. Save into object. Send to submit function. Then submit to DB. This right now is trying to do all that in one function. Anyway....
The problem is the loop for checking if there are inputs. When it finds the first true result it will call a submit and exit the function.
That's why you can input 2 fields, a checkbox and other checkboxes and foundValid is true.
My fix was to check for invalid input first. Have an outer boolean as an error. If it passes it submits. The only issue with it right now is empty fields will return a true condition and submit. Check the JS Fiddle http://jsfiddle.net/Komsomol/EDdUU/4/
var error = false;
var results = [];
function chkAddTip() {
var inputs = document.getElementById('AddTip').getElementsByTagName('input');
console.log(inputs);
// early exit the loop if at least one valid bet has been found
for (var i = 0; i < inputs.length; i += 3) {
if (!inputs[i].value && !inputs[i + 1].value && inputs[i + 2].checked) {
console.log("inputs inputed wrong!");
error = true;
} else {
results.push(inputs[i].value,inputs[i + 1].value,inputs[i + 2].checked);
}
}
submit();
}
function submit(){
console.log(results, error);
if(error == true){
alert("error in inputs");
} else {
alert("posting to server");
}
}

Categories

Resources