How do I make sure that at least one checkbox is checked? - javascript

I am using checkboxes whose values is coming from database. Its name is same but name is fetching like:
<input type="checkbox" id="chkBankServices" name="<%=bs.getServiceID()%>">
<%=bs.getServiceDesc()%>
through this i am getting the values from the database.
Now i have to validate that at least one checkbox should be selected..
If any one can help me i shall be thankful to u.
If i am giving like this the javascript code:
var services = document.getElementsById( 'chkBankServices' );
if(!(services[0].checked) &&
!(services[1].checked) &&
!(services[2].checked) &&
!(services[3].checked) &&
!(services[4].checked) &&
!(services[5].checked) &&
!(services[6].checked) &&
!(services[7].checked) &&
!(services[8].checked))
{
alert( "Please select at least one service to submit." );
return false;
}
It's not giving any alert message.
Is anything wrong in that.
Plz help me...
Thanks in advance

in jQuery :
alert( $("#chkBankServices input[type=checkbox]:checked").length > 0 );

Try this:
var services = document.getElementById( 'chkBankServices' );
var checkboxes = services.getElementsByTagName('input');
var checked = false;
for (var i=0,i0=checkboxes.length;i<i0;i++)
if (checkboxes[i].type.toLowerCase()=="checkbox")
{
if (checkboxes[i].checked) checked = true;
}
and then:
if (!checked)
{
alert('Not checked');
return false;
}

There is no getElementsById method, since there should only be one element with a given id. Perhaps you meant to use getElementsByName? This allows multiple elements to be returned.
As this is really a client side issue, it would help if you could post a sample of the generated HTML, and we can guide you further.

Have you checked the rendered source to make sure your checkboxes are being given the expected names?

I don't know if this will help you with your specific problem, but your code would be easier to read if you avoided the massive if block and used a loop instead:
var checked = false;
for(var i=0;i<services.length;i++){
if(services[i].checked){
checked = true;
}
}
if(!checked){
alert( "Please select at least one service to submit." );
return false;
}

Looking at your code, I'm betting you have that checkbox in a repeater of some sort and are creating multiple checkboxes with the same ID which is invalid html. I would wrap it in a div/span or something with an id like below:
if (!isSomethingChecked()) {
alert( "Please select at least one service to submit." );
return false;
}
function isSomethingChecked() {
var parent = document.getElementById("chkBankServices");
for (var child in parent.childNodes) {
var node = parent.childNodes[child];
if (node && node.tagName === "INPUT" && node.checked) {
return true;
}
}
return false;
}
I assumed the HTML looks like :
<div id="chkBankServices">
<input type="checkbox" id="Checkbox1" />
<input type="checkbox" id="Checkbox2" checked="checked"/>
<input type="checkbox" id="Checkbox3" checked="checked"/>
<input type="checkbox" id="Checkbox4" />
<input type="checkbox" id="Checkbox5" />
<input type="checkbox" id="Checkbox6" />
<input type="checkbox" id="Checkbox7" />
</div>

Related

checkbox onclick wont change checked via jscript

I have 3 checkboxes, i wish to be able to click the box and it tick on/off and via jscript change the value of the input for posting to state weather item is accepted or not on another page. However i have logical script but it wont work, theres no errors but the checkboxes wont click on/off they just click on and thats it.. and the value wont change either i dont understand why.
Could somebody look at this short code and tell me why.
Thank you.
<input type="checkbox" id="paypal" name="paypal1" value=" " onclick='chbxpp();' >
</input>
<label for="paypal" class="checkboxes" >Show PayPal Accepted</label>
<br>
<input type="checkbox" id="facebook" name="facebook" value=" " onclick='chbxfb(this);' >
</input>
<label for="facebook" class="checkboxes" >Show FaceBook Contact Details</label>
<br>
<input type="checkbox" id="twitter" name="twitter" value=" " onclick='chbxtw(this);' >
</input>
<label for="twitter" class="checkboxes" >Show Twitter Contact Details</label>
function chbxpp()
{
if(document.getElementById('paypal').checked === true) {
document.getElementById('paypal').checked = false;
document.getElementById('paypal').value='no';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
if (document.getElementById('paypal').checked === false) {
document.getElementById('paypal').checked = true;
document.getElementById('paypal').value='yes';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
}
function chbxfb(objfb)
{
var that = objfb;
(objfb);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
function chbxtw(objtw)
{
var that = objtw;
(objtw);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
The objpp was my attempt at another method but just does the same thing...
p.s if i just didnt use jscript and just had the html, would the value not be valid if the checkbox was not clicked or would the value still be sent...
iv just fond this..
How to change the value of a check box onClick using JQuery?
states that the value wont be sent if the box is unchecked... But then how do i know after post what has been clicked.... will i receieve a not isset($_POST['paypal']) or an empty($_POST['paypal'])
I imagine your checkboxes begin with no check inside them or .checked === false, but when you call your function chbxpp(), it looks to see if your .checked property === true and if so it sets it back to false. The click event already changes the checkbox's .checked property for you, no need to do it in your code.
//If the checkbox is checked, set it to not checked...???
//But the problem is, the click event just set the .checked property to true
//so setting it back to false makes it like it never happened.
if(document.getElementById('paypal').checked === true) {
//document.getElementById('paypal').checked = false; //This part is a no-no
document.getElementById('paypal').value='yes';
}else{
document.getElementById('paypal').value='no';
}
Adding to Ryan Wilson's answer, set your cbx's initial value to false. (Also check the format of the cbx - the closing tag.)
<input type="checkbox" id="paypal" name="paypal1" value="false" onchange="chbxpp();" />
function chbxpp() {
// the cbx starts false. when it is clicked for the first time it
// becomes true.
if (document.getElementById('paypal').checked) {
// you don't need this.
//document.getElementById('paypal').checked = true;
document.getElementById('paypal').value = 'yes';
var vv = document.getElementById('paypal').value;
console.log(vv);
} else {
// you also don't need this.
//document.getElementById('paypal').checked = false;
document.getElementById('paypal').value = 'no';
var vv = document.getElementById('paypal').value;
console.log(vv);
}
}

How to use if condition in document.getelementbyname in javascript

Here I am facing problem in if condition it validates for subject and not validate for medium field. Here checkbox is coming from mysql. But it gives source like this only. Here Know the problem is with if conditional only how to overcome this?can any figure out what is the problem in my code?what I have to do here.I hope everyone understand the question.I don't understand why the second if conditional statement is not working.
function check() {
//alert('done')
var chk = document.getElementsByName('subject[]');
var reg = document.getElementsByName('regional[]');
var len = chk.length;
var regl = reg.length;
//alert(len);
if (len) {
for (i = 0; i < len; i++) {
if (chk[i].checked) {
return true;
} else {
alert('please select the subject');
return false;
}
}
}
if (regl) {
for (i = 0; i < regl; i++) {
if (reg[i].checked) {
return true;
} else {
alert('please select the regional');
return false;
}
}
}
}
<form name="f1" action="" method="post">
Subject
<input type='checkbox' name='subject[]' value='science'>science<br/>
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi<br/>
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT" onClick="return check();">
</form>
Because if the first condition is getting false then it will stop executing the code because you have "return".
At a time both will not be validate as per you code.
First make all the subject checked and then try, you will get the second if will be working.
function check() {
var subjects = document.getElementsByName("subject[]"),
regionals = document.getElementsByName('regional[]'),
subjectSelected = false,
regionalSelected = false;
// check subject
for(var i=0;i<subjects.length;i++){
if(subjects[i].checked){subjectSelected = true;}
}
// check medium
for(var i=0;i<regionals.length;i++){
if(regionals[i].checked){regionalSelected = true;}
}
if(!subjectSelected || !regionalSelected){
if(!subjectSelected){ // subject not selected
alert("Please select a subject.");
}else{ // medium not selected
alert("Please select a regional.");
}
}
}
<form name="f1" action="" method="post">
Subject
<input type='checkbox' name='subject[]' value='science'>science<br/>
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi<br/>
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT" onClick="return check();">
</form>
the mistake you did very silly. whenever you will use the return key it will exit the function and won't process below or next codes. Moreover, I think you are trying to validate the form like if at least one subject and medium is selected the form is valid. Either you want to alert the user. The easy way to do that is first take two variable inside the function, one for subject another one for medium and set both of them to false, that means nothing is selected. Now run a loop and set the related variable true if the checkbox is checked, that means at least one is checked what you want. After two loops now write a if-else-then condition for below three states:
Both true -> at least one subject and medium is checked
one true, one false -> either subject or medium is not selected.
both false -> nothing selected.
if you are trying something else leave a comment and I will post the solution. besides, feel free to ask if you have further questions.

Prevent checking a checkbox after onclick

How can I prevent that a checkbox gets checked (without the use of disable)?
I tried
function nocheck() {
if(somevar.value>3){
alert("Not allowed");
document.getElementById('mybox').checked = false;
}
};
with
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="nocheck();" />
But this way the checkbox still gets checked after the alert message pops up.
EDIT:
Thanks to the comments/answers, I was able to come closer to a solution but not yet solved the problem - what's wrong with this code? http://jsfiddle.net/9kS8E/1/
HTML
<div class="ez-checkbox">
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="nocheck();" class="ez-hide">
</div>
JS
var user = { premium : false };
function nocheck() {
if(!user.premium){
return false;
} else {
return true;
};
};
i think i not understand your question but i think you are searching this,
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="return false;" />
OR
html
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="nocheck()" />
js
function nocheck() {
if(somevar.value>3){
alert("Not allowed");
return false;
}else
return true;
};
(1) save value of check box in a variable [ while "click" value of checkbox will get changed ]
(2) check user type,
if not a premium user, toggle value of check box.
else no need to change value of checkbox
(*) by using toggle : checkbox is already checked or not, we are not allowing a normal user to check it.
Fiddle : http://jsfiddle.net/aslancods/rQG3r/
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="noCheck(event)" />
var user = { premium : true };
function nocheck(elem) {
var newValue = elem.checked;
if(!user.premium) {
alert("not allowed");
elem.checked = !newValue;// toggle value
} else {
alert(" allowed ");
}
};
Your code should also work.
It's getting unchecked after alert.
You can say alert after unchecking like this.
if(somevar.value>3){
document.getElementById('mybox').checked = false;
alert("Not allowed");
}

jQuery check if checkbox is checked and update the value of the texbox with the checkbox's value and uncheck if it's empty

Here what I am trying to do is, if I check the checkbox the value of the respective checkbox should be appended to the textbox by using "," as delimiter between the values. And If the value of the checked respective checkbox is empty it should alert that email ID is invalid and uncheck that checkbox whose value is empty.
What's Working :
- If I check the checkbox the value is appending to the textbox.
- If I check the checkbox whose value is empty I'm getting alert.
- If I uncheck the values are automatically removed from the textbox.
What's Not working:
- Email ID validation isn't working. Function is written but it's not working. (No Errors in console)
- If I have selected few options by checking the boxes which has value and then if I select the checkbox whose value is empty I am not getting the invalid email ID alert.
Here is the code below.
HTML:
<label>Recipients : </label>
<input style="width:450px;" type="text" id="toaddress" name="toaddress"></input>
<br>
<div class="plist" style="padding:20px;">
<input type="checkbox" value="abcp#gmail.com">Pradeep</input><br>
<input type="checkbox" value="cd#gmail.com">Karthik</input><br>
<input type="checkbox" value="abcn#p.com">akfkl</input><br>
<input type="checkbox" value="ksake#po.com">afljs</input><br>
<input type="checkbox" value="">abc</input><br>
<input type="checkbox" value="">xyzop</input><br>
<input type="checkbox" value="abc#cto.com">jay</input><br>
<input type="checkbox" value="">raj</input><br>
</div>
JavaScript:
function updateTextArea() {
var allVals = [];
$('.plist :checked').each(function (i) {
if ($.trim($('.plist :checked').val()) === '' && validateEmail($('.plist :checked').val())) {
$(this)
alert("Email ID is invalid for the selected patient ! \n Example: abc#xyz.com");
} else {
allVals.push((i !== 0 ? "\r\n" : "") + $(this).val());
}
$('#toaddress').val(allVals).attr('rows', allVals.length);
});
}
$(function () {
$('.plist input').click(updateTextArea);
updateTextArea();
});
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($email)) {
return false;
} else {
return true;
}
}
Link to JSFiddle is here
http://jsfiddle.net/RhjjA/
Check http://jsfiddle.net/RhjjA/3/
I changed the validateEmail
Changed the checked when you loop through it to $(this).
I was thinking about checking if the value is empty or not valid, because neither of those conditions are allowed to pass the check. So added ! infron of the validateEmail.
I added an $(this).attr('checked', false);
This should help you get on your way.
if ($.trim($(this).val()) === '' && validateEmail($(this).val())) {
$(this).attr('checked',false);
alert("Email ID is invalid for the selected patient ! \n Example: abc#xyz.com");
Your code works fine except for one tiny detail, after your if condition, you have added $(this). This isn't terminated with a semi-colon, nor is it required. Comment this line and try.
http://jsfiddle.net/RhjjA/5/
I did that from your first question : jsfiddle.net/hBGD6/4/
The 2 main problems were
if ("string is empty" AND "validateEmail" ) couldn't work (so all string were ok). should be if ("string is empty" OR "NOT validateEmail" )
the param used by validateEmail() was the return of a function which is null (or something undefined) which was invalid for emailReg.test()

Using Javascript form validation in WordPress - Firefox issues

I have been struggling for a while to get javascript to validate a WordPress based HTML form which uses radio buttons. I finally came up with a solution with was a bit long-winded but worked - at least in IE and Chrome - however, it doesn't work in Firefox (which suggests my code is a bit sloppy). I think my radio button reference is the issue. Can anyone help with what I have done wrong - apart from use an inefficient approach for validation :-)?
A simplified version of my form:
<script>
function validateForm()
{
var aa=document.forms["personalise"]["motivation"]["1a"];
var ab=document.forms["personalise"]["motivation"]["1b"];
var ac=document.forms["personalise"]["motivation"]["1c"];
var ad=document.forms["personalise"]["motivation"]["1d"];
var ae=document.forms["personalise"]["motivation"]["1e"];
if (!(aa.checked == true || ab.checked == true || ac.checked == true || ad.checked == true || ae.checked == true))
{
alert("Question 1 must be completed");
return false;
}
}
</script>
<form name="personalise" action="insertdatatest.php" onsubmit="return validateForm()" method="post">
1. Are you seriously planning to quit </b>:
<input id="1a" type="Radio" title="" name="motivation" value="1" /> Within the next 2 weeks
<input id="1b" type="Radio" title="" name="motivation" value="2" /> Within the next 30 days
<input id="1c" type="Radio" title="" name="motivation" value="3" /> Within the next 3 months
<input id="1d" type="Radio" title="" name="motivation" value="4" /> No, I am not currently planning to quit
<input id="1e" type="Radio" title="" name="motivation" value="5" /> I have already quit
<input type="submit" value = "Submit">
</form>
I am a real newbie at web development, so any help would be much appreciated.
Thanks again TheDeadMedic for your help. Actually I found a slightly different way of doing it which worked in all three browsers which was set up for multiple radio button questions (hence the blOK entries). In case it is useful to any others, the code is below. Flix.
<script>
function validateForm() {
var inputs;
var i;
var blOK;
blOK = false;
inputs = document.getElementsByName( "motivation" );
for (i=0;i<inputs.length;i++)
{
if ( inputs[i].checked ) {
blOK = true ;
break ;
}
}
if (!blOK)
{
alert( "Question 1 must be completed" );
return false;
}
</script>
Here's a cleaner way of doing things:
function validateForm() {
var inputs = document.getElementsByName( "motivation" );
for ( var i = 0; i < inputs.length; i++ ) {
if ( inputs[i].checked ) return true;
}
alert( "Question 1 must be completed" );
return false;
}

Categories

Resources