Validate HTML using Javascript - javascript

I have the following code; I want to make sure that submit does not actually post to the page specified by action unless one of the two radio inputs has been selected. I have tried multiple variations of this and other code, and cannot seem to figure out whats wrong. Whether the radio buttons are selected or not it still posts to somepage.py.
<html>
<head>
<title>
Test Page
</title>
<script language="JavaScript">
function validate(formEntry) {
if (formEntry.Q1.q11.checked != true && formEntry.Q1.q12.checked != true)
return false;
return true;
}
</script>
</head>
<body>
<form action="somepage.py" method="POST" onsubmit="return validate(this);">
<input type="radio" name="Q1" id="q11" value="1" />
<input type="radio" name="Q1" id="q12" value="2" />
<input type="submit" name="Submit" />
</form>
</body>
</html>

If you make one button checked by defualt, then one will always be checked:
<input type="radio" name="Q1" id="q11" value="1" checked>
<input type="radio" name="Q1" id="q12" value="2" >
Or the function can be simply:
function validate(formEntry) {
return formEntry.Q1[0].checked || formEntry.Q1[1].checked ;
}
if either is checked it will return true, otherwise false.

if (!formEntry.Q1[0].checked && !formEntry.Q1[1].checked)
Trying to access input by form_name.input_name.input_id is really strange.

Use jquery validation. Checkout this link for details
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Demo page here:
http://jquery.bassistance.de/validate/demo/

It seems to work, look at:
http://jsfiddle.net/EEgea/
Maybe you'd better use a framework like JQuery to prevent javascript flaws between different browsers
Or use a validation framework like JQuery validation, I highly recommend that.

try your function like :-
function validate(formEntry) {
var radiobtn=document.getElementsByName('Q1');
if(!(radiobtn[0].checked || radiobtn[1].checked))
return false;
return true;
}

Related

How to separate HTML from Javascript in this form?

NO, this topic doesn't answer my question at all. Please read the question before doing anything.
I have a form with Javascript, which works as expected:
<script>
function checkForm(form)
{
if(form.cb1.checked) {
window.open('http://google.com/','_blank');
}
if(form.cb2.checked) {
window.open('http://yahoo.com/','_blank');
}
return true;
}
</script>
<form onsubmit="return checkForm(this);">
<label for="cb1">G</label>
<input name="cb1" type="checkbox">
<label for="cb2">Y</label>
<input name="cb2" type="checkbox">
<input type="submit" value="Submit">
</form>
But if i try to separate HTML from JS it stops working.
After clicking on Submit an url changes to checkbox.html?cb1=on, if the first checkbox is checked, or to checkbox.html?cb2=on, if the second checkbox is checked, or to checkbox.html?cb1=on&cb2=on, if checked both. But tabs with urls don't open.
My separation try looks like:
document.getElementById('cbx').addEventListener(
'submit', function checkForm(event) {
if (form.cb1.checked) {
window.open('http://google.com/', '_blank');
}
if (form.cb2.checked) {
window.open('http://yahoo.com/', '_blank');
}
return true;
});
<form id="cbx">
<label for="cb1">G</label>
<input name="cb1" type="checkbox">
<label for="cb2">Y</label>
<input name="cb2" type="checkbox">
<input type="submit" value="Submit">
</form>
<script type="text/javascript" src="form.js"></script>
Use event.preventDefault() to solve the problem. It is essentially the same as doing return true inside an HTML element attribute like onsubmit, it prevents the default behavior that would normally occur. If you want your custom behavior, which is opening some URLs in a new tab, to occur, you must override the default behavior first.
Also, make sure your form variable is defined somewhere, not sure if it is in your code because it isn't in your second example.
document.getElementById('cbx').addEventListener(
'submit', function checkForm(event) {
//Prevents default action that would normally happen onsubmit
event.preventDefault();
//Define the form element
var form = document.getElementById("cbx");
if (form.cb1.checked) {
window.open('http://google.com/', '_blank');
}
if (form.cb2.checked) {
window.open('http://yahoo.com/', '_blank');
}
return true;
});
<form id="cbx">
<label for="cb1">G</label>
<input name="cb1" type="checkbox">
<label for="cb2">Y</label>
<input name="cb2" type="checkbox">
<input type="submit" value="Submit">
</form>
The code is tested and works. (It doesn't work in the snippet due to how snippets react to opening URLs in new tabs, but here's a working JSFiddle.)

jQuery.validator.addMethod is not being executed

This is a simplified version of a page I've been working on; I got some basic validation working here but I want to integrate with the jQuery validator to get inline error messages instead of just alert boxes.
<html>
<head>
<title>pick a box, its contents will help you on your way!</title>
<script src="jQuery-1.4.4-min.js"></script>
<script src="jQuery-validate.js"></script>
</head>
<body>
<form id="fred">
<input class="Notes8" name="Notes8~1" id="Notes8~1" type="checkbox" value="Yes"> Option 1<br>
<input class="Notes8" name="Notes8~2" id="Notes8~2" type="checkbox" value="Yes"> Option 2<br>
<input class="Notes8" name="Notes8~3" id="Notes8~3" type="checkbox" value="Yes"> Option 3<br>
<script type='text/javascript'>
jQuery(function($) {
function validateMultiple (selector, n, isExactlyN) {
const totChecked = $(selector).filter(':checked').length;
return !(isExactlyN ? totChecked == n : totChecked >= n);
}
jQuery.validator.addMethod('.Notes8',
function(value, element) {
return validateMultiple('.Notes8', 1);
},
'Please check at least one check box.');
});
</script>
<button type="submit">SUBMIT!</button>
</form>
</body>
</html>
Problem is, the jQuery.validator.addMethod call doesn't seem to be working; no validation takes place and if I put alert("FRED"); inside the function(value, element) then nothing is displayed, indicating that the validator method never got wired up properly. Why is this? How can I get the validation function to execute when I submit the form? I see no JavaScript errors in the browser console.
You forgot to call validate method: $("#fred").validate();. There was also issue with your validation code - I removed unecessary negation. Also you don't need dot in name paramater in addMethod.
<html>
<head>
<title>pick a box, its contents will help you on your way!</title>
<script src="jQuery-1.4.4-min.js"></script>
<script src="jQuery-validate.js"></script>
</head>
<body>
<form id="fred">
<input class="Notes8" name="Notes8~1" id="Notes8~1" type="checkbox" value="Yes"> Option 1<br>
<input class="Notes8" name="Notes8~2" id="Notes8~2" type="checkbox" value="Yes"> Option 2<br>
<input class="Notes8" name="Notes8~3" id="Notes8~3" type="checkbox" value="Yes"> Option 3<br>
<script type='text/javascript'>
jQuery(function ($) {
function validateMultiple(selector, n, isExactlyN) {
var totChecked = $(selector).filter(':checked').length;
return (isExactlyN ? totChecked == n : totChecked >= n);
}
jQuery.validator.addMethod('Notes8',
function (value, element) {
return validateMultiple('.Notes8', 1);
},
'Please check at least one check box.');
});
$("#fred").validate();
</script>
<button type="submit">SUBMIT!</button>
</form>
</body>
</html>

jQuery validation to ensure that at least one radiobutton value is true

I've a form that has two questions. The first question asks whether the product value is greater than a fixed certain amount and the second question asks if the product value is less than the fixed amount. When the user tries to submit the form, the form should be validated to confirm that at least one question has been answered as yes. If both questions are answered as no, the form valid property $("#form").valid() should be false and a div containing an error message should be displayed on the page. How can I achieve this using jQuery validation?
A simplified version of the form looks something like
<form id="billing" method="POST">
<div>
<label for "billAmountLess">Value is less than 1000</label>
<input id="billAmountLessY" name="billAmountLess" type="radio" required value="True">
<label for "billAmountLessY">Yes</label>
<input id="billAmountLessN" name="billAmountLess" type="radio" required value="False">
<label for "billAmountLessN">No</label>
</div>
<div>
<label for "billAmountMore">Value exceeds 1000</label>
<input id="billAmountMoreY" name="billAmountMore" type="radio" required value="True">
<label for "billAmountMoreY">Yes</label>
<input id="billAmountMoreN" name="billAmountMore" type="radio" required value="False">
<label for "billAmountMoreN">No</label>
</div>
<div id="errorDiv" style="display:none">Error!!!!
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
The jQuery validation that I'm trying is
$('#billing').validate({
rules: {
billAmountMore: {
equalTo: {
param: '#billAmountMoreY',
depends: function(element) {
$("errorDiv").show();
return $("#input[name='billAmountLess']:checked").val() == "false";
}
}
}
}
});
I've created a jsfiddle for this.
You can use this code
function validate(){
console.log($("input[name='billAmountLess']:checked").val());
console.log($("input[name='billAmountMore']:checked").val());
}
to retrieve the radio button value.
In your code this line:
return $("#input[name='billAmountLess']:checked").val() == "false";
should remove the "#" before 'input' as it's indicating the 'id' of an element. Maybe that's why it's not working.
Simple you can do this in custom validation function. Update your form tag -
<form id="billing" onsubmit="return validate();" method="POST">
Then -
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function validate(){
var billLess = $("input[name='billAmountLess']:checked").val();
var billMore = $("input[name='billAmountMore']:checked").val();
if(billLess == "False" && billMore == "False"){
$("#errorDiv").show();
return false;
}
else{
return true;
}
}
</script>

Javascript Checkbox Validation not Checking if Ticked

I've looked through a lot of the questions that people have already asked on this, but I cannot find a solution that has helped me.
I'm a beginner to programming so know little about what to do, I have four check boxes and to submit the form, you have to select at least one of them, but no message comes up and the form is able to be submitted without one of the boxes being ticked.
This is my code below:
<tr>
<td align="right">
<label for="erdbeersocken"><p>Erdbeersocken<sup>*</sup>:</label>
<br>
<label for="armstulpen">Armstulpen<sup>*</sup>:</label>
<br>
<label for="cupcakes">Cupcakes<sup>*</sup>:</label>
<br>
<label for="babykleidung">Babykleidung<sup>*</sup>:</label>
<br>
</td>
<td align="left">
<form action="../" onsubmit="return checkCheckBoxes(this);">
<input type="CHECKBOX" name="CHECKBOX_1" value="Erdbeersocken">
<br>
<input type="CHECKBOX" name="CHECKBOX_2" value="Armstulpen">
<br>
<input type="CHECKBOX" name="CHECKBOX_3" value="Cupcakes">
<br>
<input type="CHECKBOX" name="CHECKBOX_4" value="Babykleidung">
<br>
<input type="SUBMIT" value="Submit!">
</td>
</tr>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.CHECKBOX_1.checked == false or
theForm.CHECKBOX_2.checked == false or
theForm.CHECKBOX_3.checked == false or
theForm.CHECKBOX_4.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
Which looks like: Text here (Checkbox here)
I'm using Notepadd++ more advanced code does not seem to work, so if anyone could help me with simplified JavaScript, I would really appreciate it. :)
function checkCheckBoxes(theForm) {
if ($("input[type='checkbox']:checked").length){
return true;
}else{
alert ('You didn\'t choose any of the checkboxes!');
return false;
}
}
For your form, you should give all the checkboxes the same name but give each checkbox a different value -- this will create an array for your checkboxes (see note at bottom of response if you don't yet know what an array is):
<input type="CHECKBOX" name="CHECKBOX" value="Erdbeersocken">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Armstulpen">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Cupcakes">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Babykleidung">
then in your confirm submit function you want to use a for loop with two nested if statements to check if a checkbox has been checked. I'll give you an example of some code I recently did:
var interestsSelected = false;
for (var i = 0; i < document.forms[0].interests.length; ++i ) {
if (document.forms[0].interests[i].checked == true) {
interestsSelected = true;
break;
//code gives go ahead for submission because at least one checkbox has been checked
}
}
if (interestsSelected !=true) {
window.alert("You must select at least one hobby or interest");
return false;
//code Woot woot woot! It all works!
}
This was my form section for the checkboxes:
<input type="checkbox" name="interests" value="technology" />Technology <br />
<input type="checkbox" name="interests" value="arts" />The Arts <br />
<input type="checkbox" name="interests" value="music" />Music <br />
<input type="checkbox" name="interests" value="film" />Movies <br/>
<input type="checkbox" name="interests" value="shopping" />Shopping <br />
<input type="checkbox" name="interests" value="outdoor" />Camping <br />
<input type="checkbox" name="interests" value="garden" />Gardening <br />
As a fellow beginner :) I often find it useful if everything is spelled out in as simple a language as possible so I'm going to provide some details here that you might or might not already know.
Anytime you create a form, an array for the form is automatically created (you won't see it listed anywhere, the browser will automatically create one when it accesses the form data BUT you can (should) refer to it in your coding). So if you have one form on your page you will have an array forms[0], if you have two different forms on your page then the first form will have an array forms[0] and the second form will have an array forms[1], each containing all of the elements in the respective forms.
If you name all your checkboxes the same name, you are essentially creating an array within an array -- the big Mama Bear array is forms[0] and nestled inside her is the Baby Bear array (your checkbox name[]).
In order to reference the Baby Bear array, you have to acknowledge the Mama Bear array first: that is why in the code example I gave above, you see "document.forms[0]" (the Mama Bear array) followed by ".interests[i]" (the Baby Bear array).
Hope this helps :)
HTML for my example
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>Select a box</p>
<form id="aform">
<input type="checkbox">
<input type="checkbox">
</form>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="test.js"></script>
</body>
</html>
And the javascript in its own file (always seperate code from css and from html)
window.onload=function() {
$("#aform").change(function () {
alert('a box is checked');
})
};

radio buttons and passing values

if(document.getElementById('3w').checked) {
alert('3w');
}else if(document.getElementById('6w').checked) {
alert('6w');
}
<input type="radio" name="pnltype" id="3w" value="3w" /> 3W
<input type="radio" name="pnltype" id="6w" value="6w" checked /> 6W
My problem:
this will run perfectly in firefox. For example, if I tick 3w and than choose "reload", I get alert '3w'
But not in Chrome.
In Chrome although I check 3W, and then manually "reload" the page, 'the alert will be '6w'.
What is the reason?
In previous versions I used the onClick option in the radio buttons and this function:
function radioClick() { window.location.reload(); }
And again - in firefox it behave as expected, not in chrome
Thanks for any help.
remove the checked attribute in the second input.
I feel using jquery will be easy for this kind of things. give it a try
http://code.jquery.com/jquery-1.11.1.min.js
<input type="radio" class="any-name" name="pnltype" id="3w" value="3w" /> 3W
<input type="radio" class="any-name" name="pnltype" id="6w" value="6w"/> 6W
$('.any-name').on('click', function(){
alert($(this).val());
});
http://jsfiddle.net/yasithao3/j1ujhetd/1/
try this without reload it should work:
<script>
function check(){
if(document.getElementById('3w').checked) {
alert('3w');
}else if(document.getElementById('6w').checked) {
alert('6w');
}
}
</script>
<body onload="check()">
<input type="radio" name="pnltype" id="3w" value="3w" onclick="check()"/> 3W
<input type="radio" name="pnltype" id="6w" value="6w" checked onclick="check()"/> 6W
</body>
Please refer following code
<title>Test</title>
<script>
function ClickEvent()
{
if(document.getElementById('3w').checked) {
alert('3w');
}
if(document.getElementById('6w').checked) {
alert('6w');
}
}
</script>
<body>
<input type="radio" name="pnltype" id="3w" value="3w" onclick=" ClickEvent()" /> 3W
<input type="radio" name="pnltype" id="6w" value="6w" checked onclick="ClickEvent()" /> 6W
</body>

Categories

Resources