Check if a checkbox is checked in JS - javascript

I am new to js and jquery. Currently, I have a form at form.php which contains a checkbox. When the user clicks submit, the form variables are sent to a form.js file where each value is checked to be null or not.
The form.js file works perfectly, however, for the checkbox nothing seems to happen. I have a feeling this is due to the way I have declared the variable.
The following is the code for the js file:
var email = $('#email').val();
var website = $('#website').val();
var CHECKBOX = $('CHECKBOX').val();
...
...
if (CHECKBOX.checked == FALSE){
var error = true;
$('#notchecked_error').fadeIn(500);
}else{
$('#notchecked_error').fadeOut(500);
}

Try using:
if ( $('#CHECKBOX').prop("checked") )
or:
if ( $('#CHECKBOX').is(":checked") )
Also, be sure your selector for the checkbox is correct.

I see two problems in your code. The first one is that the selector in your CHECKBOX assignation is faulty. It should be
var CHECKBOX = $('#CHECKBOX').val();
or
var CHECKBOX = $('input[type=checkbox]').val();
the second problem is that you are reading CHECKBOX.checked from the val() function, you need to read it from the checkbox itself.
if(CHECKBOX.checked)

$('input[type=checkbox]:checked') // If you have multiple checkboxes you can use this and loop through them to get additional info
$('#checkboxID:checked').length // To get one specific checkbox

`$('CHECKBOX').val();`
Will try to find an element with a tagname of CHECKBOX and return it's value. Presumably you want to reference the checkbox with an ID of CHECKBOX:
var CHECKBOX = $('#CHECKBOX');
To see if it's checked:
if (!CHECKBOX[0].checked) {
// CHECKBOX is not checked
}
You really should learn basic javascript before using jQuery. Usually validation is initiated from a form submit, which can give you are reference to the form. You can then reference all of the form elements as properties of the form, you don't need to create all of those jQuery objects. e.g. if you form is something like:
<form ... onsubmit="validate(this)"... >
<input type="checkbox" name="checkbox">
</form>
Then in your validate function:
function validate(form) {
if (!form.checkbox.checked) {
// the checkbox isn't checked
}
}
You can attach the listener dynamically if you wish.

Related

How to make click button from js script in angularjs?

I want to click checkbox from one of my function of script but i do not know how to do it in angularjs?
I have tried following way but it is not working :
JS
var a = document.getElementById("selectAllElem");
$scope.selectAll = a["onclick"];
if (typeof($scope.selectAll) == "function") {
alert("call click");
$scope.selectAll(a);
}
HTML
<input type="checkbox" ng-click="selectAll($event)" id="selectAllElem" />
Can anyone show me how to make checkbox click from js script in angularjs?
UPDATE
I can not use just single flag variable because above checkbox is placed at header of table and on click of it i need to make all selected check box as deselect and deselected check box as selected.
I need to call button click to achieve target.
how to make checkbox click from js script in angularjs?
you can use this instead of above code :
<input type="checkbox" ng-click="selectAll()" id="selectAllElem" ng-model="allSelected" />
in controller create function selectAll():
$scope.selectAll=function(){
$scope.allSelected=true;
}
UPDATED
You can bind scope variables to all checkboxes and change them in the selectAll() method handling the click.
Also, you could then bind a method to the selectAllElem checkbox, checking if all other checkboxes are selected.
I renamed selectAll() to toggleAll() to show how to select/deselect in one method.
e.g.:
<input ... ng-click="toggleAll()" ng-model="allSelected()" />
and
$scope.allSelected = function(){
return $scope.option1 && $scope.option2;
}
$scope.toggleAll = function(){
var value = !$scope.allSelected();
$scope.option1 = value;
$scope.option2 = value;
}
In case of the checkboxes being generated from an array, you can have scope.options and iterate over it in both methods.
OLD
You could bind the input to a scope variable, e.g.:
<input type="checkbox" ng-click="selectAll($event)" id="selectAllElem" ng-model="allSelected" />
And then set that variable from within the function
$scope.allSelected = true;

jQuery returns checkboxes as all checked even if only one is checked

As per this JSFIDDLE --
I have been going crazy trying to figure this out for last 48 hours. Everything works except for the checkbox. I included the isolated snippet of code that is causing the issue in this.
After I created boxes (pressing checkbox button) and finalize the form, I was successful in seeing code and was able to serialize checkboxes into JSON - but, I ended up getting 'on' for all checkboxes even though if only one of them is checked.
When I checked only one (first box) and other boxes unchecked, and clicked 'save', I get this as result:
{"ck1":"on","ck2":"on","ck3":"on","submit1":"save"}
What was it that threw the result off? Am I doing something wrong in this code?
A help would be appreciated in identifying the issue.
My goal is to see JSON in this format when I have first checkbox checked:
{"ck1":"on","submit1":"save"} or any format that you would suggest.
EDITED:
Find below the function I assinged to submit event:
$('#form'+formnum).submit( function(e) {
e.preventDefault(e);
var data = {};
//Gathering the Data
$.each(this.elements, function(i, v){
var input = $(v);
data[input.attr("id")] = input.val();
//delete data[button.attr("id")]; <-- cant' figure it out
//removeData[submit] <-- cant' figure it out
}); // end of $.each
var output =JSON.stringify(data);
$('#showurl').text(output);
}); //end of 'save' button function
JSFIDDLE: jsfiddle.
You are getting the value from the checkboxes, and the value is always the same regardless of the state of the checkbox.
Check the type of the element to get the state for checkboxes:
if (input.is(':checkbox')) {
if (input.is(':checked')) {
data[input.attr("id")] = input.val();
}
} else {
data[input.attr("id")] = input.val();
}
If you only want data from the checkboxes, you can just filter out the the checked checkboxes from start:
$(':checked', this).each(function(i, v){ data[v.id] = v.value; });
You're arbitrarily assigning the value of all inputs, you're not actually checking the checked state.
Add a conditional line for:
data[input.attr("id")] = input.val();
Something like:
if (/* (input is a checkbox and checkbox is checked) or input is not a checkbox*/) {
data[input.attr("id")] = input.val();
}
You also need an exception for radio buttons.

dynamic javascript when using load->view

I have a form with a « newInput » button, which add dynamically in javascript a new input when I click to it.
When I have an error in my form, I re-load the view with the form. It’s normal, but .. Because I use dynamic javascript for adding new input, all the input added are removed when I reload..
There is something I can do ?
This is an exemple of my view.tpl :
<input
type="text"
placeholder="ex: cerise"
onfocus="javascript:autoComplet('jigd1', '{site_url('recettes/getIngredient')}')"
value="{set_value('igd[]')}" id="jigd1" name="igd[]"
/>
{form_error('igd[]')}
I add a partiel code of my js file
var cpt=1;
function addField(uriIngredient, uriLabel) {
try
{
cpt=cpt+1;
var inputIgd = document.createElement('input'),
button = document.createElement('input'),
div = document.createElement('div'),
inputIgd.setAttribute('type','text');
inputIgd.setAttribute('name','igd[]');
inputIgd.setAttribute('id','jigd'+cpt);
button.setAttribute('type','button');
button.setAttribute('onclick','javascript:supField("igd'+cpt+'")');
button.setAttribute('value','Supprimer');
div.setAttribute('id','igd'+cpt);
div.appendChild(inputIgd);
div.appendChild(button);
document.getElementById("listIgd").appendChild(div);
...
After some research, I tried to look at what someone said me, that's say localStorage, and it is very nice. But I used an exemple for only one input because i wrote it in my html, but I don't know how to do for recreate all inputs .. And particularly because I use javascript to add new inputs, I don't know if I can recreate all inputs .
check the form before submitting, that way you won't have to reload the page, for example using jquery ...
$("#myformid").on("submit", function(){
var goodtogo = true;
// some code here to check the form, if there's an error --> goodtogo = false;
if (!goodtogo) return false; // and some other code to display the errors
});
That way, if there's an error , the form won't submit and won't reload.
If you have to check something in a database (for example) like checking if a username already exists, you'll have to use ajax.

How to disable enable a checkbox based on another checkbox?

Following code is generated by a for loop.
<form action="saveresponse.php" method="POST" name="mainForm">
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="01.jpg" disabled />Special<br />
<input class="cbox_yes" type="checkbox" name="yes[]" value="02.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="02.jpg" disabled />Special<br />
etc etc upto n times...
Now, what I want is that on page load, all the sp[] checkboxes should be disabled and enabled only if their corrosponding yes[] checkbox is checked by user.
Javascript code I am using: (Just to check if JS is capturing the states of yes[] checkbox?
function spenable(){
var yes = document.mainForm.yes[].value;
if (yes == true)
//alert("true");
document.mainForm.yes[].value = checked;
else
//alert("false");
document.mainForm.yes[].value = checked;
};
};
But I am not getting any alert (Neither Yes, Nor No).
So, is yes[] (Square brackets) in second line is incorrect? Or my if/else condition is wrong in JS?
P.S. All the questions here at SO or on Google deal with only one case/pair.
P.S. If required, I can change yes[] to yes1, yes2, yes3 etc and corresponding sp1, sp2, sp3 where 1,2,3 is $i of For loop, but then how will I capture/refer to it in JS?
_UPDATE:_
The flow/conditions are(Clarification):
Initially Special checkbox will be disabled and OK checkbox will be unchecked.
Then if user checks Ok, Special gets enabled.
If user want, he can tick Special.
If, later, user changes mind and untick the OK, Special should be unticked as well as disabled again.
I used jQuery here for the sake of simplicity.
$("input[name='yes[]']").change(function() { //When checkbox changes
var checked = $(this).attr("checked");
$(this).next().attr("disabled", !checked); //The next checkbox will enable
});​ // or disable based on the
// checkbox before it
Demo: http://jsfiddle.net/DerekL/Zdf9d/
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/1/
Update
It will uncheck the first checkboxes when the Special checkbox is checked.
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/2/
More Updates
Here's the demo:
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/3/
jQuery: http://jsfiddle.net/DerekL/Zdf9d/4/
Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.
You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:
document.mainForm["yes[]"]
This will not return a single element, it will return an array of elements. Use an index to access a specific element:
document.mainForm["yes[]"][0]
The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:
function spenable() {
var yes = document.mainForm["yes[]"][0].checked;
if (yes) {
alert("true");
} else {
alert("false");
};
}
To access the specific checkbox that was clicked, send the index of the checkbox in the event call:
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK
Use the index in the function:
function spenable(idx) {
var yes = document.mainForm["yes[]"][idx].checked;
var sp = document.mainForm["sp[]"][idx];
sp.disabled = !yes;
}
If you are open to using jQuery:
$('input[type="checkbox"]').click(function(){
var obj = $(this);
obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});
This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.
Working Example: http://jsfiddle.net/6YTqC/

Changing a checkbox's state programmatically in dashcode

Okay, so I'm trying to change a checkbox's state programmatically in dashcode. I've tried:
var checkbox = document.getElementById("checkbox");
// I have tried all the following methods.
checkbox.checked = false;
checkbox.selected = false;
checkbox.value = false;
Dashboard Widgets just run on WebKit technologies, so code valid for Safari should also be valid in Dashcode. Either of the following should work:
checkbox.checked = true;
checkbox.setAttribute("checked", "true");
The fact that they are not working indicates there is a problem elsewhere in your code. I would check the line
var checkbox = document.getElementById("checkbox");
Correctly assigns an element to the checkbox variable. Also, check the id of your "checkbox" element is valid and correct (not a duplicate, doesn't have a typo, etc).
This question is one month old as I write this answer. It was probably already solved, but in any case I would like to add that if you are using Dashcode, the Checkbox part is a div which contains one label and one input, this one being the "real" checkbox.
If you inspect the html as it is loaded in Safari you will notice that "checkbox" is the type of the element.
Therefore the proper way to change the state of the checkbox would be, assuming "input" is its id (it could have a default number attached though):
document.getElementById("input").checked="true";
or whichever method you want to use.
The main point here is that you were trying to change the state of another div.
Hope it helps!
checkbox.setAttribute("checked", "checked"); // set
checkBox.removeAttribute("checked"); // remove
This question has been around a while. Regardless, the following works for us:
checkbox.childNodes[1].checked = true;
checkBox.childNodes[1].checked = false;
As pointed out in a previous answer, the way Dashcode creates these controls you need to get past the div wrapper, which has the actual ID (checkbox in this example) and set the property for the input, which is child node 1.
Looking for the actual 'id' of the input would be problematic as you have no control over what id's are assigned to the node. For example if you have two checkboxes then the first one would have 'input' as the id for child node 1 and the second one 'input1', unless, of source you have used 'input' or 'input1' as an id somewhere in your design already!
There might be another method but I have not found it yet.
I don't know which browser you used, but when I tested on FF 3.6, it works.
just put like this:
checkbox.checked = false;
while:
checkbox = document.getElementById('blablabla');
or write like that
document.getElementById('idhere').checked = false;
Maybe:
checkbox.checked = "checked";
Then:
checkbox.checked = "unchecked";
cell = row.insertCell(-1);
sel = document.createElement('input');
sel.setAttribute("type", "checkbox")
sel.setAttribute("name", "myCheckBox")
cell.appendChild(sel);
cell.getElementsByTagName('input')[0].checked = true;
I create a table, row then cell and create a checkbox within it.
I can the grab hold of the first input object and set the checked status to true.
var checkbox = document.getElementById("checkbox");
there is a problem with this line, it should be
var checkbox = document.getElementById('#checkbox");

Categories

Resources