Form validation in JSP using JavaScript - javascript

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style type="text/css">
*{
font-family: cursive;
}
</style>
<script type="text/javascript">
function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if(a.value.length<=0 || b.value.length<=0)
{
alert("Don't leave the field empty!");
valid = false;
}
else{
if(!IsNumeric(a.value) || !IsNumeric(b.value))
alert("Enter a number");
valid = false;
}
return valid;
};
</script>
</head>
<body bgcolor="#CDCDCC" font-family="cursive" font-size="20px;" font-weight="bold">
<h2>Welcome <%=request.getParameter("uname")%>! Enter the numbers and the operation that you want to perform: </h2>
<form font-size="75px;" action ="serv" method="get" onsubmit="return validate();" >
<hr/>
Enter the 1st number: <input type="text" name="a" /><br/>
Enter the 2st number: <input type="text" name="b" /><br/><br/>
<label>Add</label><input type="radio" name="option" value="Add" /><br/>
<label>Subtract</label><input type="radio" name="option" value="Subtract"/><br/>
<label>Multiply</label><input type="radio" name="option" value="Multiply"/><br/>
<label>Divide</label><input type="radio" name="option" value="Divide" /><br/>
<input type="submit" value="Submit" />
</form>
</body>
This is my JSP and I've written a JavaScript function validate() that validates the user input against blank space and String.
My problem is that when i click on the submit button, for correct integer input, it is working. If an invalid input is given, i get a blank page. Can someone help me out with what the problem is and what is that i should modify? Thanks.

In you javascript you are checking via ID but there is no ID for input fields.
<input type="text" name="a" id ="a"/>
<input type="text" name="b" id="b" />
to check if a input is string or not use isNAN() like the following way
if(isNaN(a) || isNaN(b)){
alert("enter a number");}
Following is the complete working example
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style type="text/css">
*{
font-family: cursive;
}
</style>
<script type="text/javascript">
function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var c = document.getElementById("a").value;
var d = document.getElementById("b").value;
var valid = true;
if(a.value.length<=0 || b.value.length<=0)
{
alert("Don't leave the field empty!");
valid = false;
}
else{
if(isNaN(c) || isNaN(d)){
alert("Enter a number");
valid = false;}
}
return valid;
};
</script>
</head>
<body bgcolor="#CDCDCC" font-family="cursive" font-size="20px;" font-weight="bold">
<h2>Welcome <%=request.getParameter("uname")%>! Enter the numbers and the operation that you want to perform: </h2>
<form font-size="75px;" action ="serv" method="get" onsubmit="return validate();" >
<hr/>
Enter the 1st number: <input type="text" name="a" id="a" /><br/>
Enter the 2st number: <input type="text" name="b" id="b" /><br/><br/>
<label>Add</label><input type="radio" name="option" value="Add" /><br/>
<label>Subtract</label><input type="radio" name="option" value="Subtract"/><br/>
<label>Multiply</label><input type="radio" name="option" value="Multiply"/><br/>
<label>Divide</label><input type="radio" name="option" value="Divide" /><br/>
<input type="submit" value="Submit" />
</form>
</body>

Correct me if I'm wrong but your javascript function is looking for 'a' and 'b' IDs
And you don't have such... your input elements got names. add ids attributes...

Related

Radio Button selected value; choice of 3 options

Using HTML and JavaScript only, I am trying to get the first name, surname details and then a choice of favourite colour from three radio buttons. I can get the first name and surname to work, but cannot do the radio buttons?
HTML file:
<html>
<title>Task 3</title>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="formDetails">
First Name:<input type="text" id="firstName"><br>
Last Name:<input type="text" id="lastName"><br>
<p>Favourite Colour:</p>
<input type="radio" name="colour" value="Red">Red<br>
<input type="radio" name="colour" value="Blue">Blue<br>
<input type="radio" name="colour" value="Green">Green<br>
<input type="button" onclick="display()" value="Submit">
</form>
</body>
JavaScript file:
function display(){
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
alert(firstName + " " + lastName);
}
I have no idea how to implement the radio buttons? I have seen some people using jQuery, but I want to stick to just JavaScript here as I am fairly new.
Thanks.
Js:
var colour=document.querySelector('input[name="colour"]:checked').value;
alert(colour);
Steps:
Add a class to all your input tags named check_in.
Use javascript to find all tags with this class
Iterate through each tag to determine which of them is checked. If a tag is checked add it to the variable named results.
Finally get First name and Last name from input box and add these values to your variable named results
function display() {
results = {}
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var all_input = document.getElementsByClassName('check_in');
for (var i = 0; i < all_input.length; ++i) {
if (all_input[i].checked == true) {
results['option'] = all_input[i].value;
}
}
results['firstname'] = firstName;
results['lastname'] = lastName;
console.log(results);
alert('firstname:' + results['firstname'] + ' lastname: ' + results['lastname'] + ' option: ' + results['option']);
}
margin:50px auto auto;
<html>
<title>Task 3</title>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form name="formDetails">
First Name:
<input type="text" id="firstName">
<br>Last Name:
<input type="text" id="lastName">
<br>
<p>Favourite Colour:</p>
<input type="radio" name="colour" value="Red" class="check_in">Red
<br>
<input type="radio" name="colour" value="Blue" class="check_in">Blue
<br>
<input type="radio" name="colour" value="Green" class="check_in">Green
<br>
<input type="button" onclick="display()" value="Submit">
</form>
</body>

How do I use a radio button to send a user to a new website in JavaScript?

What I want the program to do is make a form and have 2 radio buttons and 1 text.
Then I want it to collapse the text and radio value together into one and take me to that page:
If I input text with like "facebook" and the radiobutton value is .com I want it to take facebook + .com and send me to that page.
<!doctype html>
<html>
<head>
<title>A Basic Form</title>
<style type="text/css">
</style>
</head>
<body onunload="Bye()">
<form>
<fieldset>
<legend>Redirection: </legend>
<div>
<label>Where do you want to go?</label>
<input type="text" id="input" name="input" size="7">
<input type="submit" id="submit" name="submit" value="Submit" onclick="go()">
</div>
<div>
<input type="radio" id="no" name="end" value=".no">
<label for=".no">.no</label>
<br />
<input type="radio" id="com" name="end" value=".com">
<label for=".com">.com</label>
</div>
</fieldset>
</form>
<script type="text/javascript">
function go() {
var end = "";
if (document.getElementById("no").checked) {
end = document.getElementById("no").value;
} else {
end = document.getElementById("com").value;
}
var input = document.getElementById("input").value;
var together = input + end;
window.location.replace("http://www." + together);
}
</script>
</body>
</html>
Change type="submit" to type="button".
Change this line:
<input type="submit" id="submit" name="submit" value="Submit" onclick="go()">
to:
<input type="button" id="submit" name="submit" value="Submit" onclick="go()">
In this case you don't need to submit a form. You are just trying to redirect the url. You didn't specify where to submit the form so it is submitting to itself that is your problem.
Alternatively, return false from the onclick handler to prevent the form submit.
Try this code:
<html>
<head>
</head>
<body>
<form>
<fieldset>
<legend>Redirection: </legend>
<div>
<label>Where do you want to go?</label>
<input type="text" id="input" name="input" size="7">
<input type="submit" id="submit" name="submit" value="Submit" onclick="return go()">
</div>
<div>
<input type="radio" id="no" name="end" value=".no">
<label for=".no">.no</label>
<br />
<input type="radio" id="com" name="end" value=".com">
<label for=".com">.com</label>
</div>
</fieldset>
</form>
<script type="text/javascript">
function go() {
var end = "";
if (document.getElementById("no").checked) {
end = document.getElementById("no").value;
} else {
end = document.getElementById("com").value;
}
var input = document.getElementById("input").value;
var together = input + end;
window.location.replace("http://www." + together);
return false;
}
</script>
</body>
</html>
brso05's analysis seems to be spot on... But I can't really explain it. It seems that Chrome is delaying the side effects of the location.href.replace (which should be navigating away from the page) until after the form submit... I have a feeling you have hit a browser bug here. I can't imagine this is spec-compliant.

Change Text of Button on RadioButton Check

I was trying to change text displayed inside button depending on the radio button being checked.
My code is :
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
$("input[type=radio]").click(function(){
if(document.getElementById('segment1').checked) {
alert('Yes');
document.getElementById('sendbutton').value="Proceed";
}
else if(document.getElementById('segment2').checked) {
alert('No');
document.getElementById('sendbutton').value="No";
}
});
</script>
</head>
<body>
<form action="composemail" enctype= "multipart/form-data" method="post" name="f1">
<input type="text" placeholder="Email TO" name="mailreciever">
<input type="text" placeholder="Email SUBJECT" name="mailsubject">
<textarea placeholder="Message" name="messagearea"></textarea>
<input type="file" name="uploadfile" id="uploadfile"/>
<input type="radio" name="radio-view" data-icon="segment-titlestyle-segonly" id="segment1" value="Yes"/>
<label for="segment1" id="controls">
<span class="ui-btn-text-controls">Yes</span>
</label>
<input type="radio" name="radio-view" data-icon="segment-titlestyle-segonly" id="segment2" value="No" checked="checked"/>
<label for="segment2" id="controls">
<span class="ui-btn-text-controls">No</span>
</label>
<input type="submit" value="send" name="sendbutton" id="sendbutton"/>
</form>
</body>
</html>
I eidted my code as per answers But It still not working.Please help
Try .value rather than .text
if(document.getElementById('segment1').checked) {
alert('Yes');
document.getElementById('sendbutton').value="Proceed";
}
else if(document.getElementById('segment2').checked) {
alert('No');
document.getElementById('sendbutton').value="No";
}
If you're going to use jQuery, then use jQuery:
$("input[type=radio]").click(function () {
$('#sendbutton').val(($('input[name="radio-view"]:checked').val() == 'Yes') ? 'Proceed' : 'No');
});
jsFiddle example

javascript radio button multiple value do same validation check

When radio button value is 1 or 2 or 3, I would like to run validation for first and last name.
<form action="index.php" method="post" name="index">
<input type="radio" name="hello" value="abc">
<input type="radio" name="hello" value="def">
<input type="radio" name="hello" value="ghi">
<input type="radio" name="hello" value="jkl">
<input type="radio" name="hello" value="mno">
<input type="text" id="first-name" name="first-name">
<input type="text" id="last-name" name="last-name">
</form>
<script>
if ( $('input:radio[name=hello]:checked').val() == "abc" || $('input:radio[name=hello]:checked').val() == "def" || $('input:radio[name=hello]:checked').val() == "ghi" )
{
if( ($('input[name=first-name]').val().length<1 ))
{
$('#first-name').focus();
return false;
}
if( ($('input[name=last-name]').val().length<1 ))
{
$('#last-name').focus();
return false;
}
}
</script>
I wrote something like this but it doesn't work.
Even I choose value for "mno", the first-name validation work.
Also this function won't validate the last-name.
any idea what i did wrong?
You are using javascript for validation but you should use this javascript in a function and call that function from your form, until it will not work because you are not calling this javascript that mean it is not working.
Here is the simple code for validation by which you can see how to validate a form. hope this code will help you.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>

To show error message without alert box in Java Script

Please correct the below code it is not working as expected i.e, i need a error message to be shown just beside the textfield in the form when user enters an invalid name
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById("fname").innerHTML="this is invalid name ";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
Try this code
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input><div id="errfn"> </div>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
I m agree with #ReNjITh.R answer but If you want to display error message just beside textbox. Just like below
<html>
<head>
<script type="text/javascript">
function validate()
{
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()" /><span id="errfn"></span>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"/><br>
<input type=button value=check />
</form>
</body>
web masters or web programmers, please insert
<!DOCTYPE html>
at the start of your page. Second you should enclose your attributes with quotes like
type="text" id="fname"
input element should not contain end element, just close it like:
/>
input element dont have innerHTML, it has value sor your javascript line should be:
document.getElementById("fname").value = "this is invalid name";
Please write in organized way and make sure it is convenient to standards.
you can try it like this
<html>
<head>
<script type="text/javascript">
function validate()
{
var fnameval=document.getElementById("fname").value;
var fnamelen=Number(fnameval.length);
if(fnamelen==0)
{
document.getElementById("fname_msg").innerHTML="this is invalid name ";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<span id=fname_msg></span>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
You can also try this
<tr>
<th>Name :</th>
<td><input type="text" name="name" id="name" placeholder="Enter Your Name"><div id="name_error"></div></td>
</tr>
function register_validate()
{
var name = document.getElementById('name').value;
submit = true;
if(name == '')
{
document.getElementById('name_error').innerHTML = "Name Is Required";
return false;
}
return submit;
}
document.getElementById('name').onkeyup = removewarning;
function removewarning()
{
document.getElementById(this.id +'_error').innerHTML = "";
}
First you are trying to write to the innerHTML of the input field. This will not work. You need to have a div or span to write to. Try something like:
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<div id="fname_error"></div>
Then change your validate function to read
if(myform.fname.value.length==0)
{
document.getElementById("fname_error").innerHTML="this is invalid name ";
}
Second, I'm always hesitant about using onBlur for this kind of thing. It is possible to submit a form without exiting the field (e.g. return key) in which case your validation code will not be executed. I prefer to run the validation from the button that submits the form and then call the submit() from within the function only if the document has passed validation.
Try like this:
function validate(el, status){
var targetVal = document.getElementById(el).value;
var statusEl = document.getElementById(status);
if(targetVal.length > 0){
statusEl.innerHTML = '';
}
else{
statusEL.innerHTML = "Invalid Name";
}
}
Now HTML:
<!doctype html>
<html lang='en'>
<head>
<title>Derp...</title>
</head>
<body>
<form name="myform">
First_Name
<input type="text" id="fname" name="fname" onblur="validate('fname','fnameStatus')">
<br />
<span id="fnameStatus"></span>
<br />
Last_Name
<input type="text" id="lname" name="lname" onblur="validate('lname','lnameStatus')">
<br />
<span id="lnameStatus"></span>
<br />
<input type=button value=check>
</form>
</body>
</html>
You should use .value and not .innerHTML as it is a input type form element
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById("fname").value="this is invalid name ";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
Setting innerHtml of input value wont do anything good here, try with other element like span, or just display previously made and hidden error message.
You can set value of name field tho.
<head>
<script type="text/javascript">
function validate() {
if (myform.fname.value.length == 0) {
document.getElementById("fname").value = "this is invalid name ";
document.getElementById("errorMessage").style.display = "block";
}
}
</script>
</head>
<body>
<form name="myform">First_Name
<input type="text" id="fname" name="fname" onblur="validate()"></input> <span id="errorMessage" style="display:none;">name field must not be empty</span>
<br>
<br>Last_Name
<input type="text" id="lname" name="lname" onblur="validate()"></input>
<br>
<input type="button" value="check" />
</form>
</body>
FIDDLE
try this
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById("error").innerHTML="this is invalid name ";
document.myform.fname.value="";
document.myform.fname.focus();
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type="text" id="fname" name="fname" onblur="validate()"> </input>
<span style="color:red;" id="error" > </span>
<br> <br>
Last_Name
<input type="text" id="lname" name="lname" onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
You should place your script code after your HTML code and within your body tags. That way it doesn't run before the html code.

Categories

Resources