Help needed with using jquery to check checkboxes from php array - php

I have a php array which I'm trying to get jQuery to check those checkboxes, but I can't seem to get it working. My php array name is "toCheck" which is:
Array
(
[0] => 0
[1] => 3
[2] => 4
)
0,3,4 are the checkboxes I need checked. Here's my checkboxes:
<input type="checkbox" name="correct[0]" id="correct" value="0" />
<input type="checkbox" name="correct[1]" id="correct" value="1" />
<input type="checkbox" name="correct[2]" id="correct" value="2" />
<input type="checkbox" name="correct[3]" id="correct" value="3" />
<input type="checkbox" name="correct[4]" id="correct" value="4" />
<input type="checkbox" name="correct[5]" id="correct" value="5" />
If someone could point out what jQuery to use to make these checkboxes selected, that would be great!
<?php foreach($toCheck as $checkMe) { ?>
//i'm assuming my jquery goes here but I can't get it working
<?php }; ?>
Thank you in advance :)

Your HTML is invalid. id values must be unique within a document (reference).
That said, ignoring the id values, you could use this (live example):
$(':checkbox[name^=correct]').each(function() {
switch (this.value) {
case "0":
case "3":
case "4":
this.checked = true;
break;
}
});
That uses a CSS3 substring selector (jQuery supports nearly all of CSS3) on the name attribute to select any checkbox with a name starting with correct, and then uses jQuery's each to loop through them. Then we set the checked property on the ones with the desired value.
You could also do it with a longer selector and without the loop (live example):
$(':checkbox[name^=correct][value=0], :checkbox[name^=correct][value=3], :checkbox[name^=correct][value=4]').attr('checked', true);
Update: Re-reading your question, it looks like you might need to do this more dynamically:
<script type='text/javascript'>
(function() {
var boxes = $(); // Assumes jQuery 1.4 or higher
<?php foreach($toCheck as $checkMe) { ?>
echo "boxes.add(':checkbox[name=^=correct][value=" . $toCheck . "]');";
<?php }; ?>
boxes.attr('checked', true);
})();
</script>
...which would generate:
<script type='text/javascript'>
(function() {
var boxes = $(); // Assumes jQuery 1.4 or higher
boxes.add(':checkbox[name=^=correct][value=0]');
boxes.add(':checkbox[name=^=correct][value=3]');
boxes.add(':checkbox[name=^=correct][value=4]');
boxes.attr('checked', true);
})();
</script>
...which would check the relevant boxes. But it wouldn't be very efficient (all of that document traversal), better off using PHP to combine the values into a selector or switch as shown above.

Be aware that browsers don't submit unchecked checkboxes.
See Submit an HTML form with empty checkboxes for more.

Related

how to uncheck checkboxes when another is checked?

im kinda trying to get into programming in general and was wondering how to uncheck / check with updating the array-
like as soon as someone checks a 2nd checkbox it should uncheck the first option and update the search (w the new data)- im a mere beginner and kinda lost rn so would appreciate any form of help
<form action="index.php" id="form1" name="form1" method="get">
<?php $i = 0; foreach ($row_page_nav_kategorie as $row_page_nav_kategorie) { ?>
<label class="checkbox-container">
<input <?php if (strpos($url,$row_page_nav_kategorie['typ']) == true) {echo 'checked="checked"';}?>
type="checkbox"
class="checkmark"
name="hotelKategorie[]"
id="ckb5"
value="<?php echo $row_page_nav_kategorie['typ']; ?>"
onclick="kategorie(<?php echo $i ?>);"
onchange="submit()"/>
<?php echo $row_page_nav_kategorie['typ']; $i++;?>
</label>
<?php } ?>
</form>
You should use radio buttons, but if you want to overwrite checkbox functionality below code will take care of it, I have added a common class on your inputs:
function checkboxClick(obj) {
var cbs = document.getElementsByClassName("checkkbox-option");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo
First of all welcome to the community!
As for your question, there is multiple ways to handle this, one of wich is as followed:
In HTML there's an attribute called radio wich you can add to your input by using type='radio'. In a set of radio buttons, only one can be checked at any time. If you then want to immedietely submit your form, you can use something like onChange='this.form.submit()'. This will submit your form when the value is changed, such as pressing on a different radio button.
Something to keep note of is that the attribute onChange is case sensitive as far as i'm aware. You were heading in the right direction with onchange="submit(), but your code doesn't know what to submit. this.form.submit() will submit the form that the element is in.
Use Radio Buttons or use JavaScript on your page to dynamically uncheck other checkboxes when you click on one.
If you want to dynamically update the page content with the new search results you should also look into AJAX which basically means you will call PHP functions from JavaScript code and those will return JSON arrays that you can exploit to modify your page's DOM.
Try THIS
HTML:
<label><input type="checkbox" name="check1" class="checkbox" /> CheckBox1</label>
<label><input type="checkbox" name="check2" class="checkbox" /> CheckBox2</label>
<label><input type="checkbox" name="check3" class="checkbox" /> CheckBox3</label>
<label><input type="checkbox" name="check4" class="checkbox" /> CheckBox4</label>
jQuery:
$(".checkbox").change(function() {
$(".checkbox").prop('checked', false);
$(this).prop('checked', true);
});
if you want to uncheck the selected checkbox
$(".checkbox").change(function() {
$(".checkbox").not(this).prop('checked', false);
});
hope this helps, thanks !!!

Posting both checked and unchecked checkboxes

I'm trying to make a series of checkboxes in a web form that will post either "true" or "false" to the next php page, depending on whether they are checked. I decided that for each checkbox (value="true"), I would have a hidden checkbox (value="false") that would always be the opposite (when checkbox is checked, hidden checkbox is unchecked etc.) I am using jQuery to do this.
The number of 'td' elements is unknown (the 'td' can be cloned an infinite number of times using a button, to submit multiple values). I added the alerts to the jQuery for testing purposes.
When I added the jQuery code and hidden checkbox into my source code (I made it visible for testing purposes), the code wouldn't work AND all the other jQuery on my web page stopped working!
jQuery code:
$(document).ready(function(){
/***post all 'required' checkboxes instead of just checked ones***/
$(".required").click(function(event){
event.preventDefault();
alert("test");
nextIndex = this.index() + 1;
alert(nextIndex);
$(".required:eq(nextIndex)").attr("checked", !.required:eq(nextIndex).attr("checked"));
});
});
HTML:
<td>
<input type="checkbox" class="required" name="required[]" value="true">
<input type="checkbox" class="required" name="required[]" value="false" style="display: none;" checked>
</td>
You don't have to hide one of the checkboxes. Here is a solution that should accomplish what you want:
<input type="hidden" name="required" value="false" />
<input type="checkbox" name="required" value="true" />
If the checkbox is not checked, then the hidden field will be submitted with the false value. If the checkbox is checked, then the true value from the checkbox will override the false value from the hidden input.
As long as you can name each checkbox something slightly different, it should work.
The following should work as well for an array of values:
<input type="hidden" name="required[0]" value="false" />
<input type="checkbox" name="required[0]" value="true" />
<input type="hidden" name="required[n]" value="false" />
<input type="checkbox" name="required[n]" value="true" />
This way, you don't need any client side javascript to toggle the hidden checkboxes.
This line is probably causing things to break:
$(".required:eq(nextIndex)").attr("checked", !.required:eq(nextIndex).attr("checked"));
You probably meant:
$(".required:eq(" + nextIndex + ")").attr("checked", !$('.required:eq(' + nextIndex + ')').attr("checked"));
Also note that you need to take nextIndex out of the quotes.
My guess is that your javascript console would have thrown some sort of error related to this.
EDIT:
Another error that I noticed was this:
nextIndex = this.index() + 1;
.index() is a jquery function which must be called on a jQuery object. this is the element that was clicked, so you will need to say:
nextIndex = $(this).index() + 1;
BTW, you might want to check out jQuery's .next() function. It would save you from all of this nextIndex mumbo jumbo.
If you are naming your checkboxes like this, you don't necessarily have an index to work with:
<input type="checkbox" name="checkbox_name[]" />
Then this snippet of jQuery should work for you, assuming that you are OK with relying on javascript.
$('form').submit(function(){
$(":checkbox:not(:checked)").each(function(element, index){
$(this).attr({value: 'false', checked:'checked'});
});
return true;
});
This loops through all of the unchecked checkboxes, checks them, and sets their value to false. Here is what you get in PHP:
[checkbox_name] => Array
(
[0] => off
[1] => on
[2] => off
)
Instead of:
[checkbox_name] => Array
(
[0] => on
)

How to create responses depending on which checkboxes are checked?

I need some help.
I'm making a site that has a form, and the response text (is to be displayed immidiately after checking a box) is depending on which checkboxes is checked. Something like this example at the bottom only checkboxes, not radio buttons, and a little more complex than that.
It's three checkboxes, so it's five scenarios;
1 - 2 - 3
---------
O - O - O
X - O - O
X - X - O
X - O - X
X - X - X
I want to have 5 different responses, and was wondering how to do it. I've used AJAX a little bit before, but I don't remember much.. I was thinking that the responses could be parsed from a php-file with get-parameters.. but I don't know. I don't all the responses and conditions to be written in jquery/javascript.
So! Could anyone help me? :) Hopefully I've written good enough for you to understand my problem!
Thanks in advance!
I think the page you linked about the :checked selector is probably the most useful thing in this context.
I'm not really sure if there's a smooth way to determine what combination of them are checked. I suppose you could give each one a different binary value (1, 2, 4), and sum the values of all of the checked boxes?
Then you could associate each possible sum with a different response call.
Of course, if you are dealing with the response on the server side, it could be a bit easier, because the server code should get each of those values as a list.
Not sure if it's helpful, but in Python I could handle something like this on the server this way:
RESPONSES = [
function_1,
...,
function_8]
def handle_checkboxes(request):
response_code = sum(list(request.params["checkboxes"]))
response = RESPONSES[response_code]()
return response
I imagine it would be roughly the same in PHP. Of course, if you are planning to handle this on the client side, the code would be a bit different. But pretty much the same concept.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function(){
$(".checks").click(function(){
one = $("#one").attr("checked");
two = $("#two").attr("checked");
three = $("#three").attr("checked");
if(!one && !two && !three)
{
alert("0-0-0");
}
else if(one && !two && !three)
{
alert("1-0-0");
}
else if(one && two && !three)
{
alert("1-1-0");
}
else if(one && !two && three)
{
alert("1-0-1");
}
else if(one && two && three)
{
alert("1-1-1");
}
});
});
</script>
and html:
<form>
1<input type="checkbox" id="one" class="checks" /><br>
2<input type="checkbox" id="two" class="checks" /><br>
3<input type="checkbox" id="three" class="checks" />
</form>
Here is the Javascript:
function countChecked() {
var str="";
a= $("#a").attr("checked");
b= $("#b").attr("checked");
c= $("#c").attr("checked");
if (a){ str+='X'; } else str+='0';
str+='-';
if (b){ str+='X'; }else str+='0';
str+='-';
if (c){ str+='X'; }else str+='0';
$("div").text(str);
}
countChecked();
$(":checkbox").click(countChecked);
And here is the HTML
<input type="checkbox" id="a" value="1" />
<input type="checkbox" id="b" value="2" />
<input type="checkbox" id="c" value="3" />
<br>
<div></div>
You can also check this JSFiddle
I found an easy way to make this work. You'll have to embed the Jquery Form Plugin. The POST parameters is processed by response.php. The form is submitted every time someone changes the state of one of the checkboxes, and the response is updated in the output-div.
<head>
<script type="text/javascript" src="jquery-1.6.3.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
</head>
<body>
<form id="formId" name="formName" method="post">
<input type="checkbox" name="Check[]" value="1" class="check"/>
<input type="checkbox" name="Check[]" value="2" class="check"/>
<input type="checkbox" name="Check[]" value="3" class="check"/>
</form>
<div id = "output"></div>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output', // target element(s) to be updated with server response
url: 'response.php' // override for form's 'action' attribute
};
$('.check').change(function() {
$('#formId').ajaxSubmit(options);
return false;
});
});
</script>
</body>
</html>

How to toggle a div based upon the radio type selection?

I toggle a div using something like this -
<input type="radio" name="myRadio" value="myDiv_1" />MyDiv
<input type="radio" name="myRadio" value="myDiv_2" />MyDiv2
<input type="radio" name="myRadio" value="myDiv_3" />MyDiv3
<div id="myDiv_1"> 1 Some input fields, text </div>
<div id="myDiv_2"> 2 More input fields, text </div>
<div id="myDiv_3"> 3 More input fields, text </div>
JAVASCRIPT
$('#myDiv_1').hide();
$('#myDiv_2').hide();
$('#myDiv_3').hide();
$('input[name="myRadio"]').change(function() {
var selected_type = $(this).val();
switch(selected_type) {
case "myDiv_1":
$('#myDiv_1').slideDown();
//if others are visible just slideup
$('#myDiv_2').slideUp();
$('#myDiv_3').slideUp();
break;
case "myDiv_2":
$('#myDiv_2').slideDown();
//if others are visible just slideup
$('#myDiv_1').slideUp();
$('#myDiv_3').slideUp();
break;
case "myDiv_3":
$('#myDiv_3').slideDown();
//if others are visible just slideup
$('#myDiv_2').slideUp();
$('#myDiv_1').slideUp();
break;
}
}
);
This works fine. My question is how I can improve it and make it more flexible as if I have to MORE divs I have to modify all cases of switch.
Also should enclose the switch functionality in a function and bind this function to events such as click and change (just to ensure that toggling works)??
Thanks for your help.
This works, I just tested it.
<script type="text/javascript">
$(document).ready(function(){
$('.MyDiv').hide();
$('input[name="myRadio"]').change(function(){
var selected = $(this).val();
$('.MyDiv').slideUp();
$('#'+selected).slideDown();
});
});
</script>
The radio buttons should look like this, where the value is the id of the element that should be shown.
<form action="example.com" method="post">
<input type="radio" name="myRadio" value="myDiv_1" />MyDiv<br />
<input type="radio" name="myRadio" value="myDiv_2" />MyDiv2<br />
<input type="radio" name="myRadio" value="myDiv_3" />MyDiv3<br />
<input type="radio" name="myRadio" value="myDiv_4" />MyDiv4
</form>
And finally, the divs should look like this, all having the class MyDiv:
<div id="myDiv_1" class="MyDiv">Div number 1!</div>
<div id="myDiv_2" class="MyDiv">Div number 2!</div>
<div id="myDiv_3" class="MyDiv">Div number 3!</div>
<div id="myDiv_4" class="myDiv">Div number 4!</div>
The following is based on the code you pasted here - before using, read below:
$("div").hide();
$("input[name='myRadio']").change(function(){
$("div:not(#"+$(this).val()+")").slideUp();
$("div#"+$(this).val()).slideDown();
});
Before Using...
I would suggest you add a class to each of the collapsable panels, maybe .panel. And then update the selectors to modify only div.panel instead of every div on the page.
your solution doesn't work in IE 8-- actually has the opposite behavior. Use the "click" function instead of "change"
$('.myDiv').hide();
$('input[name="myRadio"]').click(function(){
var selected = $(this).val();
$('.myDiv').slideUp();
$('#'+selected).slideDown();
});

Submit an HTML form with empty checkboxes

I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.
However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.
How can I get around this? Thanks.
I've used this technique from time to time:
<input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />
note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.
if (isset($_POST['checkbox'])) {
// checkbox has been checked
}
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:
if (empty($_POST['myCheckbox']))
....
else
....
In PHP empty() and isset() don't generate notices.
Here is a simple workaround using javascript:
before the form containing checkboxes is submitted, set the "off" ones to 0 and check them to make sure they submit. this works for checkbox arrays for example.
///// example //////
given a form with id="formId"
<form id="formId" onSubmit="return formSubmit('formId');" method="POST" action="yourAction.php">
<!-- your checkboxes here . for example: -->
<input type="checkbox" name="cb[]" value="1" >R
<input type="checkbox" name="cb[]" value="1" >G
<input type="checkbox" name="cb[]" value="1" >B
</form>
<?php
if($_POST['cb'][$i] == 0) {
// empty
} elseif ($_POST['cb'][$i] == 1) {
// checked
} else {
// ????
}
?>
<script>
function formSubmit(formId){
var theForm = document.getElementById(formId); // get the form
var cb = theForm.getElementsByTagName('input'); // get the inputs
for(var i=0;i<cb.length;i++){
if(cb[i].type=='checkbox' && !cb[i].checked) // if this is an unchecked checkbox
{
cb[i].value = 0; // set the value to "off"
cb[i].checked = true; // make sure it submits
}
}
return true;
}
</script>
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name
<FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
<input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
<input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
<input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
<input type="checkbox" name="option[]" value="Option1">Option1<br/>
<input type="checkbox" name="option[]" value="Option2">Option2<br/>
<input type="checkbox" name="option[]" value="Option3">Option3<br/>
<input type="submit" value="Ver">
Use this
$myvalue = (isset($_POST['checkbox']) ? $_POST['checkbox'] : 0;
Or substituting whatever your no value is for the 0
We are trouble on detecting which one checked or not.
If you are populating form in a for loop, please use value property as a data holder:
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i ?>"
<?endfor;?>
If submit form you'll get order numbers of checkboxes that checked (in this case I checked 3rd and 4th checkboxes):
array(1) {
["active"]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
When you are processing form data in loop, let's say in post.php, use following code to detect if related row is selected:
if(in_array($_POST['active'] ,$i))
$answer_result = true;
else
$answer_result = false;
Final code for testing:
<?php if (isset($_POST) && !empty($_POST)):
echo '<pre>';
var_dump($_POST);
echo '</pre>';
endif;
?>
<form action="test.php" method="post">
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i; ?>" />
<?php endfor;?>
<button type="submit">Submit</button>
</form>
Although many answers were submitted, I had to improvise for my own solution because I used the customized check-boxes. In other words, none of the answers worked for me.
What I wanted to get is an array of check-boxes, with on and off values. The trick was to submit for each check-box on/off value a separator. Lets say that the separator is ";" so the string you get is
;, on, ;, ;, ;
Then, once you get your post, simply split the data into array using the "," as a character for splitting, and then if the array element contains "on", the check-box is on, otherwise, it is off.
For each check-box, change the ID, everything else is the same... and syntax that repeats is:
<div>
<input type="hidden" name="onoffswitch" class="onoffswitch-checkbox" value=";" />
...some other custom code here...
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch1" checked>
</div>
EDIT: instead of the ";", you can use some KEY string value, and that way you will know that you did not mess up the order, once the POST is obtained on the server-side... that way you can easily create a Map, Hash, or whatever. PS: keep them both within the same div tag.

Categories