Newbie: Need explanation of a Js function - javascript

So I am doing a HTML and JavaScript related assignment which I am not required to have any prior knowledge of these scripting and programming languages. I was required to produce a document explaining how HTML and JavaScript brings about an entry form, and how JavaScript does validation check etc.
<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(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" /> : AS<br />
</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>
There's a task where I need to create 3 additional radio buttons for different level entries and then I was required to create a function which does a confirmation check, to ask the user to either confirm or cancel the choice after they have selected on a specific level entry. As I do not have any prior knowledge of programming(or I have learnt a little during the course of my assignment), I do not know how to create a function. Therefore, I googled it and found this page (It's the same assignment btw) From what I know from this page, I am required to change the radio buttons into:
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
and implement a function as such:
function confirmation() {
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked==null)
{
alert('Please choose an option');
return false;
} else {
return confirm('You have chosen '+checked.value+' is this correct?');
}
And great now I have done what it said, there's now an alert box which pops out and confirms choice of radio button with the user, so clicking on the radio button will trigger an onclick event which returns the function. Now my question is how does this function do the confirmation check?
(I am sorry if I wrote too much, my previous post was put on hold by as too broad by a few of people, because I wasn't being clear enough what I am suppose to say.)

Just add result &= confirmation(); in your validation code. Some where between your two if statements.

You need to watch the click event and determine whether or not you want to permit the action:
$(document).ready(function () {
$('input[type="radio"]').on('click', function () {
var r = confirm("Are you sure?");
if (r == true) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
});
});
http://jsfiddle.net/LTQ9p/1/

Related

Javascript Form Validation, multiple functions on a single button not working correctly

I'm working on a form validation project that requires multiple input fields connected to a single submit button. I more or less figured the button out, but I'm having an issue getting the functions themselves to work properly. I currently only have three of the eleven fields typed up for testing, but what the page should do is let you know which fields are invalid when there is nothing filled out in them (changing text/background colors, message below, etc).
The issue I'm having is that when the requirements for the first field (Gift Card Number) are met, it acts as though there isn't any issues anywhere, regardless of whether or not the other input fields (First name, Last name) have been filled. They all seem to function correctly if none of the fields are filled, but my concern is that the functions seem to be firing in order and first one to work negates all the ones after (for example, Gift Card prevents First and Last, First prevents Last, etc).
Any ideas where I've gone wrong here? I'll include my html and my javascript. (Yes, I know the html is a bit ugly, I plan to move the material over to a div table later, just trying to get it to function for now) Any help appreciated as always!
HTML
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<table>
<tbody>
<tr id="rONE">
<td><h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5></td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
</form>
<tr id="rTWO-1">
<td><h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td><form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4></td>
</form>
</tr>
<tr>
<td><h5 id="recipientMessage"></h5></td></td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>
</body>
<footer>
<script src="Form Validation.js"></script>
</footer>
</html>
Javascript
document.getElementById('btn').addEventListener('click', function(){
validateGiftCard();
validateRecipient();
});
function validateGiftCard() {
valid = true;
if ( document.giftForm.giftInput.value == "" )
{
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if ( document.firstForm.firstInput.value == "" )
{
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor="#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
document.getElementById('btn').addEventListener('click', function(e) {
var v1 = validateGiftCard();
var v2 = validateRecipient();
console.log(v1, v2);
if (!v1 || !v2)
e.preventDefault();
});
function validateGiftCard() {
valid = true;
if (document.giftForm.giftInput.value == "") {
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if (document.firstForm.firstInput.value == "") {
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor = "#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
<table>
<tbody>
<tr id="rONE">
<td>
<h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5>
</form>
</td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
<tr id="rTWO-1">
<td>
<h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td>
<form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4>
</form>
</td>
</tr>
<tr>
<td>
<h5 id="recipientMessage"></h5>
</td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>

JavaScript radio buttons html web form

I am currently using html to code a 'form entry'. I am also using a JavaScript validation, to validate the input in of the form. At the moment, i have 'name', 'subject' and 'examination number', each working and having functional validations. For the 'qualification' fields, I have radio buttons where the user has to click-select their qualification. I have the validation in place, but unfortunately I cant get the field to be highlighted in red and display the error message when the form is submitted and the 'qualification' has been left blank. everything works apart from the qualification field. It would be great if someone could fix the validation of the 'qualification' so that when the field is left emty, the text will be highlighted and the error message will be included. thanks
here is my code:
<html>
<head>
<title>Exam Entry</title>
<script language="javascript" type="text/javascript">
function qualinform(qualname) {
alert(qualname + " was selected as your qualification.");
}
function validateForm(e) {
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.group1.value=="") {
msg+="You must choose a qualification\n";
document.ExamEntry.group1.focus();
document.getElementById('radioqual').style.color="red";
result = false;
}
var regex = /^\d{4}$/;
if (document.ExamEntry.Examination_number.value == "") {
msg+="You must enter your examination number";
document.getElementById('Examination_number').style.color="red";
result = false;
} else if (isNaN(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should only contain digits";
document.getElementById('Examination_number').style.color="red";
result = false;
} else if (!regex.test(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should contain exactly 4 digits";
document.getElementById('Examination_number').style.color="red";
result = false;
}
if (msg != "") {
alert(msg);
}
return result;
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" 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="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<td id="Examination_number">Examination number</td>
<td><input type="text" maxlength="4" name="Examination_number" /></td>
</tr>
<tr>
<td id="qualification">Choose your qualification</td>
<tr>
<td id="radioqual">
<input onclick="qualinform('GCSE');" type="radio" name="group1" value="GCSE">GCSE<br>
<input onclick="qualinform('AS');" type="radio" name="group1" value="AS">AS<br>
<input onclick="qualinform('A2');" type="radio" name="group1" value="A2">A2<br>
</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>
the return value of the group1 radio buttons when none are selected is undefined, not "" as you expected, so you need to change the condition in the if statement
if (document.ExamEntry.group1.value==undefined)

How do I enable cancel button with form validation?

I'm using the frmvalidator javascript found here for my code.
I had to create a custom validation because I'm validating two input fields with the same id (I'm using an array). The validation is working, the problem now though is when I click the cancel button, the validation still takes effect meaning I can't close the dialog box unless I fill in all fields.
Here's my code:
<form name="UpdateIndustry" action="addIndustry.jsp" method="get">
<table align="center">
<c:forEach var="row" items="${paramValues.industries}">
<jsp:setProperty property="tableId" name="bean" value="${row}"/>
<c:set var="ctr" value="${ctr + 1}"/>
<input type="hidden" name="hello" value="${row}"/>
<tr><th>INDUSTRY NAME</th>
<td><div id='UpdateIndustry_industryName_errorloc' style="color:red;"></div>
<input type="text" name="industryName" size=40 value="${bean.thisIndustry.INDUSTRYNAME}"/></td></tr>
</c:forEach>
<input type="hidden" name="finalCount" value="${ctr}"/>
<tr><td style="text-align:center" colspan="3">
<input type=submit name="submit" value="Update Industry" onclick="btnUpdate_click()"/>
<input type=submit name="submit" value="Cancel" onclick="btnCancel_click()"/></td></tr>
</table>
</form>
and the script:
<script language="JavaScript">
var frmvalidator = new Validator("UpdateIndustry");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
function btnUpdate_click(){
frmvalidator.setAddnlValidationFunction(FinalValidator); }
function btnCancel_click(){
frmvalidator.clearAllValidations();
window.close(); }
</script>
and here's the FinalValidator function, where the validation happens.
function FinalValidator()
{
var myForm = document.forms["UpdateIndustry"];
if (myForm.industryName.length > 0) {
for(var i=0; i <= myForm.industryName.length; i++)
{
if(myForm.industryName[i].value.length == 0)
{
sfm_show_error_msg('Please enter industry name.', myForm.industryName[i]);
return false;
}
}
}
return true;
}
How can I get the cancel button to work? Thanks in advance for the help! :)
$(document).ready(function () {
$("#YourButtonID").click(function () {
error = false;
$(".span1").remove();
if ($("#YourTextBoxID").val() == "") {
$("#YourTextBoxID").after("<span class='span1'>Write Your Error</span>");
error = true;
}
});
});
Try this.

JQuery Form Validation

I need to do a form validation with jQuery. But I'm having a problem in this.
I have a HTML form as below:
<FORM id="formID" method="POST" onsubmit="return checkRequiredFields(this)" action="">
<td><input class="required" type="text" id="input1" value="" /></td>
<td><input class="required" type="text" id="input2" value=""/> </td>
<td><input class="required" type="text" id="input3" value=""/> </td>
<td><input type="text" id="input4" value=""/> </td>
<td><input type="submit" id="save" value="Save" /></td>
</FORM>
The first three input text fields are required fields. I tried writing the script like below:
<script type="text/javascript">
function checkRequiredFields(form){
var no_errors = true;
$(form).find(".required").each(function(){
alert("Inside Loop");
var field = $(this);
if (field.val() == ""){
$("#"+field ).css("color","red");
no_errors = false;
} else {
$("#"+field ).css("color","white");
}
});
return no_errors;
}
</script>
But, the above code is not working as I expected. The alert() is never executed, meaning that the control does not find any element with class "required". So, what is the problem in my code?
$("#"+field ).css("color","red"); is not right. field is an object not a string, but since it's already a jQuery object you can just do this: field.css("color","red");. You'll have to do that for the other .css() call too: $("#"+field ).css("color","white"); => field.css("color","white");
Here is a demo: http://jsfiddle.net/eehV6/

Problem in form validation with JavaScript

The editvalidate() function is not getting called at all:
Please suggest why. What's the remedy?
<script type="text/javascript">
function editvalidate() {
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var numericExpression = /^[0-9]+$/;
if(document.editprofile.userid.value == '' || document.editprofile.password.value == ''||document.editprofile.name.value == ''||document.editprofile.age.value == ''||document.editprofile.collegeid.value == ''||document.editprofile.mobile.value == ''||document.editprofile.address.value == ''||document.editprofile.department.value == ''||document.editprofile.email.value == ''||document.editprofile.sec_ques.value == ''||document.editprofile.answer.value == ''){
alert("Hey! you can't left a field blank!");
return false;
}
else if(!document.editprofile.email.value.match(emailExp)){
alert("You need to enter a valid email address to get proper notifications!");
return false;
} else if(!document.editprofile.mobile.value.match(numericExpression)){
alert("Mobile numbers are all numeric digits i think!");
return false;
} else if(document.editprofile.mobile.value.length < 10){
alert("Mobile number must be 10 digit long!");
return false;
}
else{
return true;
}
}
</script>
the form is given below and its used to fetch data from database and itself getfilled with the values.the editable entries are corrected and the form is submitted.its working fine just not getting validated cz the editvalidate() is not getting called at all.why?
<form name="editprofile" action="editprofile.jsp" method="post" onsubmit="return editvalidate();">
<table align="center">
<%
for(int i = 0; i < list.length ; i++){
%>
<tr>
<td>Name:</td>
<td><input type="text" name="name" size="35" style="width: 219px" value="<%=list[i].getName() %>" maxlength="25"></td>
</tr>
<input type="hidden" name="userid" size="20" style="width: 220px"
value="<%=list[i].getUserid() %>" maxlength="10">
<tr>
<td>Address:</td>
<td><input type="text" name="address" size="46"
style="width: 221px" value="<%=list[i].getAddress() %>"
maxlength="50"></td>
</tr>
<tr>
<td>E-mail:</td>
<td><input type="text" name="email" size="20"
style="width: 220px" value="<%=list[i].getEmail() %>" maxlength="40"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="age" size="20" style="width: 219px"
value="<%=list[i].getAge() %>" maxlength="2"></td>
</tr>
<tr>
<td>College ID:</td>
<td><input type="text" name="collegeid" size="20"
style="width: 219px" value="<%=list[i].getCollegeid() %>"
maxlength="10"></td>
</tr>
<tr>
<td>Mobile:</td>
<td><input type="text" name="mobile" size="20"
style="width: 218px" value="<%=list[i].getMobile() %>" maxlength="10"></td>
</tr>
<tr>
<td>Department:</td>
<td><input type="text" name="department" size="20"
style="width: 218px" value="<%=list[i].getDepartment() %>"
maxlength="10"></td>
</tr>
<tr>
<td>Security Question:</td>
<td><input type="text" name="sec_ques" size="20"
style="width: 218px" value="<%=list[i].getSec_ques() %>"
maxlength="50"></td>
</tr>
<tr>
<td>Answer:</td>
<td><input type="text" name="answer" size="20"
style="width: 218px" value="<%=list[i].getAnswer() %>" maxlength="50"></td>
</tr>
<tr>
<td><input type="submit" name="operation" value="editprofile"
style="width: 118px"></td>
<td><input type="reset" value="Reset" name="B2"></td>
</tr>
<%
}
%>
i checked it the way u suggested and found that the function is getting called.but why the rest alerts r nt visible? isnt thatdue to the value attribute in input tags
With the as far given little information, all I can answer is: Just run a Javascript debugger. I can recommend you Firebug for this.
That said, in the future please come up with an SSCCE instead of cutouts of code with unnecessary clutter. This avoids crawling long in the code searching for lines of relevance and at first glance obvious questions as "Are they in the same file?", "Did you add alert('blah') as 1st line of function to see if it actually is invoked?", "Did the browser have JS enables?", "Are you sure that you didn't typo'ed the function name?", "Isn't there more into the code which may have disturbed it?", etcetera.
Here's a basic example of such an SSCCE:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2063598</title>
<script>
function validate(form) {
alert('Validate method invoked!');
return false;
}
</script>
</head>
<body>
<form onsubmit="return validate(this)">
<input type="text" name="foo" class="required">
<input type="submit">
</form>
</body>
</html>
That said, I see that you're still using the legacy scriptlets in your JSP. If you can, I strongly recommend to stop using it and switch to taglibs/EL before it's too late. Raw Java code belongs in Java classes, not in JSP files.
Basic example with JSTL's (just drop jstl-1.2.jar in /WEB-INF) c:forEach:
<table>
<c:forEach items="${users}" var="user">
<tr>
<td><input type="text" name="address" value="${user.address}"></td>
<td><input type="text" name="email" value="${user.email}"></td>
<td><input type="text" name="college" value="${user.college}"></td>
</tr>
</c:forEach>
</table>
And also keep CSS in its own CSS file to separate style from content and to increase webapp performance and maintainability.
you don't call it anywhere from your html, you should probably call it <form onsubmit="return editvalidate();">
Ok now I see he formatted it properly, I don't mind the down votes I give them sometimes as well.
#Robin Agrahari
you probably have somewhere typo in the javascript no one is going to go trought it but you, try to test one by one if by using alert as you do. But don't do it on sumbit, create a mock button that will call(on click) this function editvalidate(); and check your function thoroughly and you will get to the problem eventually
How can you tell it's not being called? I'd put an alert right at the top of the method and see if it hits that. It's possible you're hitting some kind of error somewhere. If an alert at the top of editvalidate doesn't occur, try changing the obsubmit to:
onsubmit="alert('hello!'); return editvalidate();"
then you should at least see "Hello!" when you click the submit button.
looking at the code it should be called
Or Try
onsubmit="editvalidate(); return false;"
Or check where it is not misplaced, I mean the javascript should be in <head> </head>
actually i used a password checking parameter in the first if block document.editprofile.password.value == ''
and i never used an attribute like password in the form.that was my mistake and so it was not working.i found it using the firebug tool.thanks for the help.

Categories