I am using a checkbox that has the name as "selectedids[]" and I am trying to select all checkboxes with the JavaScript. The code is not working. When I change the name of the checkbox to "selectedids" it works, but I can't do so because I need all the ids that are selected on the POSTED page.
The checkbox is as follows:
foreach($rows as $row)
{
<input type="checkbox" name="selectedids[]" value="<?php echo $row['id']; ?>" class="checkbox" />
........
........
}
And the Java-script function is as follows:
function SetAllCheckBoxes(CheckValue)
{
var CheckValue=true;
if(!document.forms['main'])
return;
var objCheckBoxes = document.forms['main'].elements['selectedids[]'];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
Please help me......
Thanks in advance.......
Do you have the option to use jQuery? If so, then you could do something like:
$(':checkbox').each(function(){
$(this).attr('checked',true);
});
It also might work to try:
$(':checkbox').attr('checked',true);
Or, if you just want to make sure all the boxes are checked only when the page first loads you could have your php that creates the checkboxes include "CHECKED". i.e.
<input type='checkbox' name='selectedids[]' value='value' CHECKED>
Updated to use :checkbox per comment
Why don't you just select them by id?
e.g.
var a=0;
while(document.getElementById('mycheckbox_'+a))document.getElementById('mycheckbox_'+a).checked=true;
If it was me, I would use the class of the checkboxes to identify them, with a bit of jQuery.
This would work:
$('input.checkbox').each(function(){$(this).attr('checked',true); });
It would set all checkboxes with class "checkbox" as true.
Beaten to it!
Related
I have a list of songs. I'm trying to determine whether or not a song on the list has been checked or not. If so I need to know the value of the checkbox.
my html looks like this... the value $song_id is pulled from the list in the database.
<input type='checkbox' name='song[]' value='$song_id' />
There could be 10 songs... there could 100.
I need to know which ones have been checked and how to get the value.
On click save item ID of item to array; (js)
On click search was such ID already checked; (in array)
ADDED
You should use jQuery (or raw javascript) to do logic you want. jQuery is http://jquery.com/ using it you can do you want on front-end. Do this on back-end is bad idea.
Once you submit the form the $_POST['song'] variable will contain an array of all the $song_id's that were selected.
You can do something like this:
<input type='checkbox' name='song[]' class='songItem' value='$song_id' />
<input type='hidden' id='selectSongsHidden' />
In JavaScript,
var selectedSongValues = [];
var selectedSongsString = ""; // for comma-separated values
function GetSelectedSongs()
{
var songs = $('.songItem');
var selectedSongs = [];
for(var i=0; i<songs.length; i++)
{
var checked = $(songs[i]).is(':checked');
if(checked)
{
selectedSongs.push(songs[i]);
}
}
for(var j=0; j<selectedSongs.length; j++)
{
selectedSongValues.push($(selectedSongs[j]).val());
selectedSongsString += $(selectedSongs[j]).val() + ",";
}
$('#selectSongsHidden').val(selectedSongsString);
}
When you press submit, in the onclick event you can call this function and set the value to a hidden field.
You can see this in a working http://jsfiddle.net/A3e3y
foreach ( $_POST['song'] AS $song_id ) {
// do smth with $song_id ...
}
i am new to the jquery, it is quite interesting, but i am having a little problem,
i am populating multiple checkboxes from database using foreach loop like this,
<? foreach($cities as $city) { ?>
<input type="checkbox" name="city[]" value="<?=$city->id?>" id="city[]" />
<? } ?>
i want to restrict user to check atleast one checkbox, i know how to do this with only one checkbox, but got confused with this kind of array in jquery, any help will be greatly appreciated!
Many thanks in advance!
To find how many checkboxes are checked, you can use something like:
var checkedNum = $('input[name="city[]"]:checked').length;
if (!checkedNum) {
// User didn't check any checkboxes
}
Since you're providing the same name attribute to all the checkboxes (from your PHP loop), you can use the selector input[name="city[]"] to target and find them all. But to find out how many specifically are checked, you can add the :checked selector. An alternative to this is using $('input[name="city[]"]').filter(":checked").
Finally, !checkedNum will only pass if checkedNum is 0, since 0 is falsey. Any other number is truthy, and wouldn't satisfy the condition !checkedNum.
References:
jQuery attribute equals selector: http://api.jquery.com/attribute-equals-selector/
:checked selector: http://api.jquery.com/checked-selector/
jQuery .length property: http://api.jquery.com/length/
If you want at least one checkbox checked, you can use this
var somethingChecked = false;
$("input[type=checkbox]").each(function() {
if(this).is(':checked')) {
somethingChecked = true;
}
});
if(!somethingChecked) {
alert("You haven't checked anything yet");
}
What this does is initialize a variable to false. Then the script loops through all inputs of type checkbox. If the item is checked, set the variable to true. Finally, check if the variable is still false. If it is, then show an error.
This code work well for me,here i convert array to string with ~
<input type="checkbox" value="created" name="today_check"><strong>Created</strong>
<input type="checkbox" value="modified" name="today_check><strong>Modified</strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var vals = "";
$.each($("input[name='today_check']:checked"), function(){
vals += "~"+$(this).val();
});
if (vals){
vals = vals.substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>
Assuming you have #my_form as the ID of your form, you could do
$("#my_form input[type=checkbox]:checked"). // ... do something
to select and do something with the checked checkboxes. You can also do
$("#my_form input[type=checkbox]").each(function(idx, elem) {
var is_checked = $(this).prop("checked");
// Do something with is_checked
});
to iterate through all the checkboxes and check whether they are checked or not.
First of all id of the checkboxes should be unique.
Do like this
<?
$checkBoxCount = 0;
foreach($cities as $city) { ?>
<input type="checkbox" name="city[]" value="<?=$city->id?>" id="chkbox-<?=$checkBoxCount?>" />
<? } ?>
Now in jQuery check like this to get all the checkboxes thats checked.
var checkCount = $("input[name='city[]']:checked").length;
if(checkCount == 0)
{
alert("Atleast one checkbox should be checked.");
}
I have the following loop, which shows a checkbox along with an answer (which is grabbed from Wordpress):
$counter = 1;
foreach ($rows as $row){ ?>
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
<?php echo $row['answer'];
} ?>
This is part of a bigger loop that loops through a set of questions and for each question it loops through the answers (code above).
How can I grab the checkboxes that the user has checked and display the values within a div before the form is submitted?
I know I can use the following to check if the checkbox is checked:
$('form #mycheckbox').is(':checked');
I'm not sure where to start with all the looping!
You can use the selector :checked
$.each("#mycheckbox:checked", function() {
$("div").append(this.val());
});
You may do something like below:
var divContent = "";
$("form input[type=checkbox]:checked").each(function() {
divContent += this.value + "<br/>";
});
$("div").html(divContent);
Not completely clear to me when this should be executed. From your question it looks to me like that should happen when user clicks on submit button, in such case you just need to place that code into $("form").submit(function(){...});
var boxes = $('input[type="checkbox"][name^="answer"]');
$('#myDiv').empty();
boxes.on('change', function() {
boxes.filter(':checked').each(function(i, box) {
$('#myDiv').append(box.value);
});
});
Get all the matching checkboxes, and whenever one of the checkboxes changes update a div with the values of the checked boxes.
The loop you provide is happening server side, as it is php code. When you wan't to validate the form before submission you must do it on the client, ie using javascript.
So, you will not use the same loop, but rather create a new one that is run when any checkbox is changed.
I suggest you to add a class name to the checkboxes (like class='cb_answer') in the php loop. This will help you to safely select the specific checkboxes when doing the validation.
Here is a script snippet that will add the value of selected checkboxes to a div each time any checkbox is changed. Add this just before </body>. May need to modify it to fit your needs.
<script>
// make sure jQuery is loaded...
$(documet).ready( {
// when checkboxes are changed...
$('.cb_answer').on('change', function() {
// clear preview div...
$('#answers_preview').html('');
// loop - all checked checkboxes...
$('.cb_answer:checked').each(function() {
// add checkbox value to preview div...
$('#answers_preview').append(this.val());
});
});
});
</script>
assuming id='answers_preview' for the div to preview the answers and class='cb_answer' for the checkboxes.
Trying to make the infamous checkall checkbox for dynamically created rows from a MySQL query. Rows (and therefore checkboxes) could range from 1 row to a metric buttload.
The form (without the checkall) is as follows:
<form name="form" method="post" action = "process.order.php">
<?php
while($fetch = mysql_fetch_array($order_query){
$order_id = $fetch['oid'];
$order_status = $fetch['ostat'];
?>
<input type="checkbox" name="order_row[<?=$order_id?>]" id="1" value="1">
<select name="status[<?=$order_id?>]" id="status[<?=$order_id?>]"
<option value="Ordered">Ordered</option>
<option value="Backordered">Backordered</option>
</select>
<? } ?>
<input type="submit" name="submit" id="submit" value="submit"> </form>
In process.order.php:
<?php
if(is_array($order_row)){
foreach($order_row as $order_id=>$val){
...followed by the rest of the script. I tried using this: How to implement "select all" check box in HTML?
and this:
Select All Checkbox
I'm trying to avoid using jQuery at this moment. Is there a way I can call the checkbox name generated by the PHP script into the javascript code?
Update:
I'd like to use a function that I can call across multiple pages. Thus, calling embedding the form name in the JS won't be practical for me. Also, I'd like it to be a checkbox - the button's worked great, but I'm trying to keep the UI simple and I already have a lot of buttons I'm trying to get rid of...
Working Example
You can do like this:
var frm = document.forms['form'];
for (var i = 0, l = frm.elements.length; i < l; i++) {
if (frm.elements[i].type === 'checkbox') {
frm.elements[i].checked = true;
}
}
Similarly, to uncheck all set:
frm.elements[i].checked = true;
to false.
You can also easily create checkAll and unCheckAll functions using above code.
By the way, an id with only numeric value is invalid, you should use alpha or mix of alpha and numeric characters.
If you don't have to support IE6 or 7, the following will work.
Live Demo
var checkAll = document.getElementById("checkall");
checkAll.onclick = function(){
[].forEach.call(
document.forms['form'].querySelectorAll("input[type='checkbox']"),
function(el){
el.checked=true;
});
}
I'm trying to implement a page with a choice of user's preferences in an HTML form where if the checkbox ALL is selected then all sub-checkbox base1, base2 and base3 are checked automatically, and if any of sub-checkboxes is un-selected then the checkbox ALL must be unchecked. I used a javascript function which works but when I submit the form only the last variable in the array of checkboxes is sent.
<SCRIPT LANGUAGE="JavaScript">
function checkChoice(field, i) {
if (i == 0) { // "All" checkbox selected.
if(field[0].checked==true) {
for (i = 1; i < field.length; i++)
field[i].checked = true;
}
}
else {
if (field[i].checked == false) {
field[0].checked = false;
}
}
}
<form name="form" method = "POST" action="preferences.php">
<input type=checkbox name=classes1 value="allbases" onclick="checkChoice(document.form.classes1, 0)">All bases
</td><td>
<input type=checkbox name=classes1 value="base1" onclick="checkChoice(document.form.classes1, 1)">Base1
<br>
<input type=checkbox name=classes1 value="base2" onclick="checkChoice(document.form.classes1, 2)">Base2
<br>
<input type=checkbox name=classes1 value="base3" onclick="checkChoice(document.form.classes1, 3)">Base3
<input type="submit" value="Set preferences" >
If I call the checkboxes'names in "classes1[]" all the values are submited but the javascript function doesn't work anymore. Is there a way of fixing this?
Thanks for any help.
For an alternative of checkChoice: check this SO question and the jsfiddle I presented there.
[edit] concerning your comment: a bit of extra thinking would have brought you to this solution
All of the values actually ARE submitted but PHP will overwrite $_POST['classes1'] each time until you are just left with the last value. If however you add '[]' to your input names then they are added to an array.
Since the latter causes a problem with javascript, can you not just either
a) iterate all of the form elements from the form.elements array,
or b) give each input a unique id and use document.getElementById() to find it?