How to check checkbox array along with text using javascript - javascript

I have HTML page with javascript. In this, I have form which contains text for name and checkboxes. Below is the HTML form:
<form name="drugForm" action="form1.php" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="dname">
<pre>
<input type="checkbox" name="drug" value="id1">ID1 <input type="checkbox" name="drug" value="id2">ID2</br>
<input type="checkbox" name="drug" value="id3">ID3 <input type="checkbox" name="drug" value="id4">ID4</br>
</pre>
<input type="submit" value="Submit">
</form>
Below is the javascript for same:
<script>
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
//var y=document.drugForm.drug[0].value;
var y = new Array();
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
alert("click any checkbox "+ y);
//alert("Working with boolean " + y);
return false;
}
}
</script>
Here, I want to check whether any checkbox is checked also along with name entry. But whenever I am trying to put for loop with y (array) in else if condition or anywhere in function, the code is not working and instead giving action directly.
My question, specifically, is how to check checkboxes, like did in if condition, is checked and how to get those values?

The code below validate when there's at least one checked box:
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
} else if (Boolean(x)) {
for (k=0;k<y.length;k++) {
if(y[k].checked) {
return true;
}
}
alert("Check one option at least");
return false;
}
}
There's another goog option in jquery as shown in another post.

Try this,
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (x)
{
if(!$('input:checkbox:checked').length)//check length of checked checkboxes
{
alert("click any checkbox ");
return false;
}
}
}

Related

html javascript doesn't work or show an alert

i'm using javascript to validate my html (checking if the user input a correct data ) source code and it's more than simple but the problem is that when i press the submit button i can't see any result or alert
<script type= "text/javascript">
function checkname()
{
name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
if ( name.value=="")
{
alert("you kindly forget to put your name here");
return false;
}
return name.value("Welcome" + name + " to valet parking service VPS");
}
</script>
that's all for the first part where the script is written now in the html tag where the button is typed
<input type="submit" value=" submit " >
and that's what written in the form
<form onsubmit = " checkname(); return false; ">
This is the mistake (you always return false to the submit function):
<form onsubmit = " checkname(); return false; ">
Try this:
<form onsubmit="return checkname();">
Then modify your checkname function to something like this:
function checkname()
{
var name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
if ( name.value=="")
{
alert("you kindly forget to put your name here");
return false;
}
name.value("Welcome" + name + " to valet parking service VPS");
return true;
}
Here is the JSFiddle: http://jsfiddle.net/267wL/
HTML
<form action="demo.html" id="myForm" onsubmit = "checkname(); return false; " method="post">
<p>
<label>First name:</label>
<input type="text" id="myname" />
</p>
<input type="submit" value=" submit "/>
</form>
JavaScript
function checkname()
{
var name = document.getElementById("myname");
var reg= /^[A-Z][a-z]+$/;
if (!name.value.match(reg))
{
alert("Please enter your name begin with a CAPITAL letter");
return false;
}
name.value = "Welcome " + name.value + " to valet parking service VPS";
return false;
}
You don't have to check null values. If the name.value is empty, your regex validation failed.
Pay also attention that the welcome message is set in the input text. Weird behaviour...
The return true; will block all following code.
Try This
<script> function checkname() {
var x = document.forms["myForm"]["myname"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}
<form name='myForm' action='action.php' onsubmit='return checkname()' method='post'>
First name: <input type="text" name="myname"><input type="submit" value="Submit"></form>

Form Validation not working on all fields but only the first

When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.

Javascript form validation needs fix

I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}

JavaScript double form validation

I am new to JavaScript and I have been doing a university assignment based around HTML and JavaScript. In this assignment I was asked to create a number of forms to allows a person to register for some form of educational classes. I was asked to create the form using HTML and to validate the entries using only JavaScript.
What I have been struggling to figure out is how to validate more than one form input using one block of validation (if that is possible), I want to validate both the firstname and familyname inputs using only validateForm.
Here is a segment I have been testing out:
<head>
<script>
function validateForm() {
var x = document.forms["nameform"]["firstname"].value;
if (x == null || x == "") {
alert("first name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="nameform" , action="demo_form.asp" , onsubmit="return validateForm()" , method="post">
<b>First name:</b>
<input type="text" name="firstname">
<br>
<b>Family name:</b>
<input type="text" name="familyname">
<br>
<input type="submit" value="Submit">
</form>
</body>
Any help would be greatly appreciated!
<head>
<script>
function validateForm()
{
var firstname=document.getElementById('txtfirstname');
var familyname=document.getElementById('txtfamilyname');
if (firstname.value=="")
{
alert("first name must be filled out");
return false;
}
if (familyname.value=="")
{
alert("familyname must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="nameform", action="demo_form.asp", onsubmit="return validateForm()", method="post">
<b>First name:</b> <input type="text" id="txtfirstname" name="firstname">
<br>
<b>Family name:</b> <input type="text" id="txtfamilyname" name="familyname">
<br>
<input type="submit" value="Submit">
</form>
</body>
You can check all inputs, store error messages (if any) and return false at the end if there is even one failure.
i.e.
function validateForm() {
var x = document.forms["nameform"]["firstname"].value, errors = [];
if (x == null || x == "") {
errors.push("first name must be filled out");
}
x = document.forms["nameform"]["familyname"].value;
if (x == null || x == "") {
errors.push("family name must be filled out");
}
if(errors.length > 0) { // check if there were any errors
alert(errors.join("\n")); // alert all messages together
return false;
}
}
Couple of possibilities...
<script>
function validateForm()
{
var x=document.forms["nameform"]["firstname"].value;
if (x==null || x=="")
{
alert("first name must be filled out");
return false;
}
x=document.forms["nameform"]["lasttname"].value;
if (x==null || x=="")
{
alert("last name must be filled out");
return false;
}
return true;
}
</script>
will present an alert for each field as it fails validation and return true if all fields are OK.
<script>
function validateForm()
{
var errorString="";
var x=document.forms["nameform"]["firstname"].value;
if (x==null || x=="")
{
errorString+="first name must be filled out\n";
}
x=document.forms["nameform"]["lasttname"].value;
if (x==null || x=="")
{
errorString+="last name must be filled out\n";
}
if(errorString=="")
{
return true;
}
else
{
alert(errorString);
return false;
}
}
</script>
will return a single alert listing all of the fields that have failed validation.
In addition, I always like to use the focus() method on the first field that failed validation to put the cursor in the field that needs correcting.
Try this..
function validateForm()
{
var msg='';
var flag=false;
var x = document.forms["nameform"]["firstname"].value;
if (x == null || x == "")
{
flag = true;
msg = ' First Name '
}
x = document.forms["nameform"]["familyname"].value;
if (x == null || x == "")
{
if(flag==true)
msg = msg + 'And Family Name '
else
msg = msg + ' Family Name ';
flag = true;
}
if (flag==true) {
msg = msg + " must be filled out";
alert(msg);
}
return false;
}
simply store it in multiple variables and have multiple if statements:
<script>
function validateForm() {
// name the variables appropriately
var firstname = document.forms["nameform"]["firstname"].value;
var familyname = document.forms["nameform"]["familyname"].value;
// check if either of them are correct, if not alert and return false.
if (firstname == null || firstname == "") {
alert("first name must be filled out");
return false;
} else if (familyname == null || familyname == ""){
alert("family name must be filled out");
return false;
}
return true;
}
</script>

How to validate 3 fields in javascript

I want to validate 3 fileds
First name text box
Last name text box
Middle name text box
here is my code:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["lname"].value;
var z=document.forms["myForm"]["mname"].value;
if(((x!='') && (y=='' && z==''))
|| ((y!='') && (x=='' && z==''))
|| ((z!='') && (x=='' && y=='')))
{
alert("First name must be filled out");
return false;
}
alert("fill input filed");
return false;
}
</script>
My code is executing like this: if i wont enter anything in any field - alerting, this part is fine. Then when i enter one of the field its alerting me the if part same way if i will enter two text box my if part should be executed, but its not happening.
Can you change that condition please so that if I will fill 2 fields it should alert me at least one field can be filled?
Make it simple, your first name is mandatory, so make it first priority
if(x==''){
alert("First name must be filled out");return false;
if(y=='' && z==''){
//alert();// other condtions
}
}else{
alert("fill input filed");return false;
}
I think this is what you are looking for...
Javascript Code
<script type="text/javascript">
function validateForm()
{
var x=document.getElementById("fname").value;
var y=document.getElementById("mname").value;
var z=document.getElementById("lname").value;
if((x==''))
{
alert("First name must be filled out");
return false;
}
else if((y==''))
{
alert("Middle name is empty");
return false;
}
else if((z==''))
{
alert("Last name is empty");
return false;
}
return true;
}
</script>
HTML Code
<form action="#">
<input type ="text" id ="fname"></input>
<input type ="text" id ="mname"></input>
<input type ="text" id ="lname"></input>
<input type="submit" onclick="return validateForm();">
</form>

Categories