Onsubmit, check number of checkboxes checked - javascript

I think my brain has already checked out and is in holiday mode. I'm trying to do something extremely simple, and I can not get it to work for the life of me.
I have a form that is dynamically generated via server-side code. It can have one or more questions that have checkboxes as options. I need to check to make sure at least one item is checked in any group, and the validation has to be done in pure JS (no jQuery).
I'm banging my head against the desk trying to get it to work:
HTML:
<form onsubmit="return validateCheckboxes();">
<h4>Which things do you enjoy?</h4>
<input type='checkbox' name='2' value='12' id='2_12'>
<label for='2_12'> Breathing</label><br />
<input type='checkbox' name='2' value='13' id='2_13'>
<label for='2_13'> Watching paint dry</label><br />
<input type='checkbox' name='2' value='14' id='2_14'>
<label for='2_14'> Nothing</label><br />
<br />
<br />
<input type="button" value="Submit">
Javascript:
function validateCheckboxes() {
if (document.querySelector('.2:checked')) {
alert('something is checked');
return true;
} else {
alert('NOTHING is checked');
return false;
}
};
jsFiddle Link: https://jsfiddle.net/r6c4hxhj/

The selector .2:checked is looking for class="2" in the checkboxes. To select checkboxes with name="2" you should use
document.QuerySelector('[name="2"]:checked')
function validateCheckboxes() {
if (document.querySelector('[name="2"]:checked')) {
alert('something is checked');
return true;
} else {
alert('NOTHING is checked');
return false;
}
};
<form onsubmit="return validateCheckboxes();">
<h4>Which things do you enjoy?</h4>
<input type='checkbox' name='2' value='12' id='2_12'>
<label for='2_12'> Breathing</label><br />
<input type='checkbox' name='2' value='13' id='2_13'>
<label for='2_13'> Watching paint dry</label><br />
<input type='checkbox' name='2' value='14' id='2_14'>
<label for='2_14'> Nothing</label><br />
<br />
<br />
<input type="submit" value="Submit">
</form>

With .2:checked you are testing against the class whereas 2 is the name value. Add class=2 to your checkboxes.

The form element needed a closing tag </form>
The button needs to be a submit <input type="submit"/>
In order to get a HTMLCollection, use:
var chkList = document.querySelectorAll('input[type="checkbox"]:checked');
Then use a simple conditional against the collection's length:
if (chkList.length > 0)
http://plnkr.co/edit/PXiQCk0f7Qu3H5EYIgOF?p=preview
function validateCheckboxes() {
var chkList = document.querySelectorAll('input[type="checkbox"]:checked');
if (chkList.length > 0) {
alert('something is checked');
return true;
} else {
alert('NOTHING is checked');
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form onsubmit="return validateCheckboxes();" action="http://examples.funwebdev.com/process.php" method="post">
<fieldset>
<legend>Which things do you enjoy?</legend>
<input type='checkbox' name='2' value='12' id='2_12'>
<label for='2_12'> Breathing</label>
<br />
<input type='checkbox' name='2' value='13' id='2_13'>
<label for='2_13'> Watching paint dry</label>
<br />
<input type='checkbox' name='2' value='14' id='2_14'>
<label for='2_14'> Nothing</label>
<br />
<br />
<br />
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>

you could iterate over each checkbox to see if it is checked on submission.
cool I just learnt something, I didn't realize you could use pseudo selectors with querySelectorAll. I still think this is a valid pattern though, if you want to compare the total checked with the total checkboxes to make it more dynamic. without another expensive querySelector attribute call.
function validateCheckboxes( form ){
var checkboxes = slice( form.querySelectorAll('[type=checkbox]') ),
ret = checkboxes.reduce( function( total, checkbox ){
if( checkbox.checked ){
++total;
}
return total;
}, 0 );
console.log( ret + ' of ' + checkboxes.length + ' checkboxes checked' );
return false; // to cancel submission for stack
}
function slice( arr, start ){
return Array.prototype.slice.call( arr, start || 0 );
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
<form onsubmit="return validateCheckboxes(this);">
<h4>Which things do you enjoy?</h4>
<input type='checkbox' name='2' value='12' id='2_12'>
<label for='2_12'> Breathing</label><br />
<input type='checkbox' name='2' value='13' id='2_13'>
<label for='2_13'> Watching paint dry</label><br />
<input type='checkbox' name='2' value='14' id='2_14'>
<label for='2_14'> Nothing</label><br />
<br />
<br />
<input type="submit" value="Submit">

Related

Validating - at least one checkbox is checked

I have a problem in validating whether at least one checkbox is checked or not.
The same code is being used for a different form and its working perfectly but I can't figure why it doesn't on this form.
Script:
if(jQuery('#MOTForm input[type=checkbox]:checked').length == 0) {
alert("1");
valid = valid && false;
$("#MOTFORMERROR").css('color', 'red');
$("#MOTFORMERROR").html("*Choose at least one");
}else{
$("#MOTFORMERROR").html("");
}
Html:
<td style="width: 10%;" rowspan="3">
<div style="padding-left:5px;">
<form id="MOTForm">
<input name="" type="checkbox" class="form-check-input"/> HEMS<br />
<input name="" type="checkbox" class="form-check-input"/> EMS<br />
<input name="" type="checkbox" class="form-check-input"/> Walk-in<br />
</form>
<p id="MOTFORMERROR"></p>
</div>
</td>
The code in the block of the if statement is being run all the time, instead of the code in the block of the else statement, even if one or all checkboxes are checked!
your code does not show when the javascript is executed, maybe your checkboxes are not yet rendered when you look for them.
In fact if you run your code in the exact order you posted here is perfectly normal that your condition is always true.
If you put your code inside a function to be called after all the HTML is rendered everything works perfectly:
<td style="width: 10%;" rowspan="3">
<div style="padding-left:5px;">
<form id="MOTForm">
<input name="" type="checkbox" class="form-check-input"/> HEMS<br />
<input name="" type="checkbox" class="form-check-input"/> EMS<br />
<input name="" type="checkbox" class="form-check-input"/> Walk-in<br />
</form>
<p id="MOTFORMERROR"></p>
</div>
</td>
<!-- ... -->
<button id="check_btn">Click me</button>
<!-- ... -->
<script>
var valid;
$('#check_btn').click(function() {
if ($('#MOTForm input[type=checkbox]:checked').length == 0) {
valid = false;
$("#MOTFORMERROR").css('color', 'red');
$("#MOTFORMERROR").html("*Choose at least one");
} else {
$("#MOTFORMERROR").html("");
}
});
</script>
Since the variable valid wasn't defined, there was an error in your initial code (see below). This error is visible in the browser console.
Uncaught ReferenceError: valid is not defined
Because of that error, the lines after valid = valid && false; are not being executed.
To fix this, declare that variable before this code is run:
var valid = false;
//...other code to check if form is valid
Then move the original JavaScript code into a function that can be run on submit (e.g. function check() {...}). See this demonstrated below. It uses the jQuery function .click() to bind the event handler to the submit button. You will also notice it uses .ready() to wait until the DOM is ready before binding the event handler to the submit button.
//wait until DOM is ready to bind check function to button click
$(document).ready(function(readyEvent) {
$('#submit').click(check);
})
var valid = false;
function check() {
if (jQuery('#MOTForm input[type=checkbox]:checked').length == 0) {
alert("1");
valid = valid && false;
$("#MOTFORMERROR").css('color', 'red');
$("#MOTFORMERROR").html("*Choose at least one");
} else {
console.log('no error- clearing error html');
$("#MOTFORMERROR").html("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-left:5px;">
<form id="MOTForm">
<input name="" type="checkbox" class="form-check-input" /> HEMS
<br />
<input name="" type="checkbox" class="form-check-input" /> EMS
<br />
<input name="" type="checkbox" class="form-check-input" /> Walk-in
<br />
<button id="submit">
Submit
</button>
</form>
<p id="MOTFORMERROR"></p>
</div>
Update:
You typed a comment on your post (replying to questions in other comments):
valid is declared at the beginning of .click
Now that that information is revealed, it makes me feel like most of what I said above is useless. Moving the declaration of valid into the click handler seems like a trivial change and there isn't much different besides that... See the example below:
//wait until DOM is ready to bind check function to button click
$(document).ready(function(readyEvent) {
$('#submit').click(check);
})
function check() {
var valid = false;
if (jQuery('#MOTForm input[type=checkbox]:checked').length == 0) {
alert("1");
valid = valid && false;
$("#MOTFORMERROR").css('color', 'red');
$("#MOTFORMERROR").html("*Choose at least one");
} else {
console.log('no error- clearing error html');
$("#MOTFORMERROR").html("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-left:5px;">
<form id="MOTForm">
<input name="" type="checkbox" class="form-check-input" /> HEMS
<br />
<input name="" type="checkbox" class="form-check-input" /> EMS
<br />
<input name="" type="checkbox" class="form-check-input" /> Walk-in
<br />
<button id="submit">
Submit
</button>
</form>
<p id="MOTFORMERROR"></p>
</div>
Please have a look at the following snippet. It does that you are looking for. I removed the valid variable, since it isn't apparent, where this parameter is used. Apparently, you can add it and use it as you think.
$(function(){
function checkCheckBoxes(){
if($('#MOTForm input[type=checkbox]:checked').length == 0) {
alert("1");
$("#MOTFORMERROR").css('color', 'red');
$("#MOTFORMERROR").html("*Choose at least one");
} else {
$("#MOTFORMERROR").html("");
}
}
$(".js-check").on("change", checkCheckBoxes);
checkCheckBoxes();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td style="width: 10%;" rowspan="3">
<div style="padding-left:5px;">
<form id="MOTForm">
<input name="" type="checkbox" class="form-check-input js-check"/> HEMS<br />
<input name="" type="checkbox" class="form-check-input js-check"/> EMS<br />
<input name="" type="checkbox" class="form-check-input js-check"/> Walk-in<br />
</form>
<p id="MOTFORMERROR"></p>
</div>
</td>

Javascript/jQuery Submit Form Validation

I am new to web development and I am trying to create a simple form validation using javascript/jquery.
I drafted a simple form very similar to what I have that looks like this:
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
What I want to happen is when the user clicks the submit button, it will check every input box if it contains a valid number (price) before it allows the submit, if one or more of the input box is invalid, it will be highlighted with an alert error "Invalid inputs on highlighted textboxes" or something like that. After couple of searches this is what I have in my script:
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$('.price')[i].focus();
}
errors = 'True';
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
I understand what is wrong with what Ive done but I dont know how to fix it.
I know that we can only focus() 1 element at a time but I wanted to have some effect that it highlights the inputboxes with invalid characters.
Please tell me how to do it or if there's a better approach can you show me some examples. I saw bootstrap has some css effects for this focus but I dont know how to implement it. Thank you!
You can add a class to the inputs with bad values. The class can add a border for example.
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$(inputs[i]).addClass('error');
errors = 'True';
} else {
$(inputs[i]).removeClass('error');
}
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
First, I think you should clean up your HTML. For example, it is always a good idea to give an id attribute to your form tags to reference them. Also, someone correct me if I am wrong, you won't be submitting any values without giving a name attribute to your input fields.
<form id="price-form" action="" method="get">
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<button type="submit">Save</button>
</form>
Now, since you are using jQuery, why not utilize its methods such as on() and .each() ?
$(function() {
$('#price-form').on('submit', function(e) {
// this variable acts as a boolean, so might as well treat it as a boolean
var errors = false;
// remove previous errors
$('.price').removeClass('error');
// check each input for errors
$('.price').each(function() {
if (isNaN(this.value)) {
$(this).addClass('error');
errors = true;
}
});
// alert if there are any errors
if (errors) {
alert('Errors are highlighted!');
e.preventDefault(); // stop submission
}
});
});
In your CSS, you could do
.error {
border: 2px solid #a00;
}

textbox.value not working in javascript

The following is a simple javascript code to set a value into a textbox. But, it doesn't seem to work. I am not able to find the flaw. Also, the javascript is working only in IE and not in Chrome/Firefox. How do I get out of this trouble?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function reportValue()
{
var form = document.getElementById("billgen");
var radioArray = form["time"];
var months;
for(var i=0;i<radioArray.length;i++)
{
if(radioArray[i].checked)
{
months = radioArray[i].value;
break;
}
}
if(months == "1")
{
e=31*100;
form["total"].value = e;
//document.getElementById("total").value = e; => not working as well
return true;
}
else{
alert("Are you sure the instructor is " + months + "?\nYou may be underestimating the instructor!");
return false;
}
}
</script>
</head>
<body bgcolor="white">
<fieldset>
<legend>Bill Generation</legend>
<form id="billgen" method="post">
<label><input type="radio" name="time" value="1" checked /> 1 Month </label>
<label><input type="radio" name="time" value="3" /> 3 Month </label>
<label><input type="radio" name="time" value="6" /> 6 Month </label>
<label><input type="radio" name="time" value="12" /> 1 Year </label>
<input type="submit" value="submit" onclick="reportValue();" />
<p>
<input type="text" id="total" name="total" />
</p>
</form>
</fieldset>
</body>
</html>
Clicing on a <input type="submit"/> causes the page to reload, so instead of "submit", either use the <button> element or use an <input type="button"/>.
Here is your code with getElementById( instead of getElementById[: JSFiddle and it works.
Just move your code to the end of your html, just before the </body> and it should work, I think the problem is that you are asigning the form to a variable before the form even exists.

html page direct

hello i am new at html i am designing a quiz in html. this is example with 2 questions only.when i click a submit button i want to calculate marks show it in a alert box and then go to result.htm page .but when i click submit alert box shows answer but page is not redirected forward to result.htm.
my code is:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
.d1
{
background-color:#FFFFCC;
}
#Submit1
{
width: 67px;
}
</style>
<script language="javascript" type="text/javascript">
function Submit1_onclick() {
var i = 0;
var a = document.getElementById("Radio1");
if (a.checked == true) {
i++;
}
var b = document.getElementById("Radio8");
if (b.checked == true) {
i++;
}
alert(i);
}
</script>
</head>
<body>
<p>
</p>
<form name="f1" method="post" action="d://result.htm">
<div class="d1">
Q1 What is your name ?
<br />
a <input id="Radio1" name="R1" type="radio" value="t" />
b <input id="Radio2" name="R1" type="radio" value="f" />
c <input id="Radio3" name="R1" type="radio" value="f" />
d <input id="Radio4" name="R1" type="radio" value="f" /></div>
<br /> <br /> <br />
<div class="d1">
Q1 What is your Id ?
<br />
1 <input id="Radio5" name="R11" type="radio" value="V1" />
2 <input id="Radio6" name="R11" type="radio" value="r1" />
3 <input id="Radio7" name="R11" type="radio" value="as1" />
4 <input id="Radio8" name="R11" type="radio" value="pop1" /></div>
<br /> <br /> <br />
<div class="d1">
<input id="Submit1" type="submit" value="submit" onClick="return(Submit1_onclick())"/><br />
<br /> <br />
</form>
</body>
</html>
As the last line of your function call
<script language="javascript" type="text/javascript">
function Submit1_onclick() {
var i = 0;
var a = document.getElementById("Radio1");
if (a.checked == true) {
i++;
}
var b = document.getElementById("Radio8");
if (b.checked == true) {
i++;
}
alert(i);
location.href="result.htm";
}
</script>
This will redirect the page
Change your markup to this:
<input id="Submit1" type="submit" value="submit" onclick="Submit1_onclick();"/>
and add this to your javascript:
function Submit1_onclick() {
...
alert(i);
return true;
}
Returning true from an event handler will tell the browser to continue the default behavior (in this case, submit the form).
Sounds like you're trying to submit a POST between two static files in an IIS server, which you can't do. You can change the files to .aspx and it should work as expected.

Get nested element value

i have the html:
<div>
<label>
<input type='radio' name='a'>
<span></span>
<input type='hidden' value='1'>
</label>
<label>...
</div>
I need to get value of hidden input by click event on label.
I have javascript like this:
$('label').live('click', function () {
var value = $(this).children('input:hidden').val();
});
But this is not work. Can anybody help?
Works fine:
<div>
<label>
<input type='radio' name='a'>
<span></span>
<input type='hidden' value='1'>
</label>
</div>
<script type="text/javascript">
$('label').live('click', function () {
var value = $(this).children('input:hidden').val();
console.log(value);
});
</script>
Output: 1
First, unless you absolutely have to, you should avoid live() function. Depending on jQuery version, use bind(), click() or on()
But your code works fine, see this Fiddle.
<form action="form_action.asp" method="get">
Email: <input type="text" name="email" /><br />
<input type="hidden" name="country" value="Norway" />
<input type="submit" value="Submit" />
</form>
$(function() {
$('label').on('click', function () {
var value = $(this).children('input:hidden').val();
});
});

Categories