How to create responses depending on which checkboxes are checked? - php

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>

Related

Multiple Forms, check input from all with one submit button

I've got multiple forms like this on one page:
<form method="post" action="#">
<input type="hidden" name="product_id" value="'.$item['articlenumber'].'" />
<input type="text" name="update_quantity" value="'.$pg->quantity.'" />
<input type="hidden" name="packing" value="'.$item['packing'].'" />
<input type="hidden" name="unit" value="'.$item['unit'].'" />
<input type="submit" name="addtocart" value="Update" />
</form>
And I've got one submit button at the bottom:
<input name='placeorder' type='submit' value='Place order' />
How can I check all forms when I press the submit button? I need to validate that the input that was given is the correct quantity.
UPDATE
I now got all the values from the forms in JavaScript and the validation is correct. Now I want to store the variables into PHP SESSIONS. I saw the answer from Ben and that would work if the values where in PHP, they are now in JavaScript. I need them on other pages so I thought Sessions would be the best thing here (if not, other suggestions are welcome).
I saw this answer and there they say it is not possible on one page. I understand that because PHP is server side and Javascript client side. Is this the only possible way to send Javascript variables to PHP?
Alright, first you should remove the type='submit' on the input. So change it to :
<input name='placeorder' value='Place order' />
Then you just need to add a javascript function to validate.
$(document).ready(function() {
$("input [name='placeorder']").click(function() {
var formOK = true;
$("form input").each(function(index, element) {
var value = $(element).val();
if (value != "OK") {
formOK = false;
}
});
if (formOK) {
submitForms();
} else {
alert("Form Input Inccorect");
}
});
});
function submitForms() {
$("#form1").add("#form2").submit();
}
With regards to your question about storing form data in a session variable Try something along these lines:
session_start();
if (isset($_POST['placeorder'])) {
$_session['ProductID'] = $_POST['product_id'];
$_session['UpdateQuantity'] = $_POST['update_quantity'];
$_session['Packing'] = $_POST['packing'];
$_session['Unit'] = $_POST['unit'];
}
Hope that helps
Both answers helped me a little bit but I needed to combine them so I ended up with a solution like the following. I got the values from the inputs by their unique name like this:
var sizeS25 = parseInt($("input[name='size-s25']").val(), 10) || 0;
var sizeM25 = parseInt($("input[name='size-m25']").val(), 10) || 0;
Then I send the variables to a PHP file:
window.location.href = "phpsessions.php?sizeS25=" + sizeS25 + "&sizeM25=" + sizeM25;
In the PHP file I set the variables as sessions:
$_SESSION['sizeS25'] = $_GET['sizeS25'];
$_SESSION['sizeM25'] = $_GET['sizeM25'];

keeping checked checkbox state unless unchecked

I had asked this question but did not get a solution. By short explanation I would like the checked checkboxes to stay checked unless unchecked by the user: on page refresh.
I am able to keep the boxes checked on page refresh but when the page id changes(I have pagination) like index.php?page=2 the boxes get unchecked so is there a way that I can get the boxes to stay checked unless unchecked even if the page id changes?
I am displaying results from database and the user can filter results. If the user clicks on the next page for more results I would like to keep the checked boxes stay checked so that I can show filtered results from page 2. I really need help. Thanks
<form id="form" method="post" action="">
<input type="checkbox" name="sa" class="checkbox" <?=(isset($_POST['sa'])?' checked':'')?>/>Samsung<br>
</form>
<script>
$(document).ready(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
I have tried this jquery function along with the above one but it doesn't work.
$("input.checkbox").each(function() {
var mycookie = $.cookie($(this).attr('name'));
if (mycookie && mycookie == "true") {
$(this).prop('checked', mycookie);
}
});
$("input.checkbox").change(function() {
$.cookie($(this).attr("name"), $(this).prop('checked'), {
path: '/',
expires: 365
});
});
I think this is what you need:
<input type="checkbox" name="sa" class="checkbox" value="yes"
<?php echo ($_POST['sa'] == 'yes')? ' checked="checked"':'' ?>/>Samsung<br>
The proper mark-up being
checked="checked"
to get that to stay active based on your condition.
This only occurs if you are continuing through other pages WITH the form being used to get to them. If you only expect people to use the form once, you should set a SESSION or GET variable to carry that value through other pages without the use of the form.
So, for example, keep the form almost the same, except change your condition and include this in your header, before you spit out the form -
<?php
session_start();
if(isset($_POST['changeit'])) {
if( $_POST['sa'] == 'yes') {
$_SESSION['checked'] = true;
} else {
$_SESSION['checked'] = false;
}
}
?>
then make you're condition for spitting out checked:
<input type="checkbox" name="sa" class="checkbox" value="yes"
<?php echo ($_SESSION['checked'] == true)? ' checked="checked"':'' ?>/>Samsung<br>
and include a hidden input to only check if the checkbox has changed.
<input type="hidden" name="changeit" />
that way, the condition for setting the session is only checked if the form checkbox was checked or unchecked... so your whole structure should look something like this -
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</HEAD>
<BODY>
<?php
if(isset($_POST['changeit'])) {
if( $_POST['sa'] == 'yes') {
$_SESSION['checked'] = true;
} else {
$_SESSION['checked'] = false;
}
}
?>
<form id="form" method="post" action="">
<input type="checkbox" name="sa" class="checkbox" value="yes"
<?php echo ($_SESSION['checked'] == true)? ' checked="checked"':'' ?>/>Samsung<br>
<input type="hidden" name="changeit" />
</form>
<script>
$(document).ready(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
</BODY>
</HTML>
The fundamental note is that POST variables will not transfer over from page to page if the form isn't being used. The "action" is not called, thus the post is not sent. You have to use either COOKIES or SESSIONS or GET variables to have this cross over pages without the use of the form every time.
RCNeil's answer is correct, in that if the post key 'sa' is set, the checkbox will be checked="checked".
To expand on his answer, It doesn't have to be from a post value, it can be pulled from the database, or anywhere really. It just needs to return a boolean (True/False). The following would also work:
//Some logic
$YourVariable = true; //for example
//Then the checkbox conditional
<input type="checkbox" name="sa" class="checkbox"
<?=($YourVariable)?' checked="checked"':'')?>/>Samsung<br>
Will return as the checked="checked" and the checkbox marked by default. (Unless, bool false)
<input type="checkbox" name="sa" class="checkbox" checked="checked" value="forever"
<?=(isset($_POST['sa'])?:'')?>/>Samsung<br>
I guess this should work

Help needed with using jquery to check checkboxes from php array

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.

How to gray out HTML form inputs?

What is the best way to gray out text inputs on an HTML form? I need the inputs to be grayed out when a user checks a check box. Do I have to use JavaScript for this (not very familiar with JavaScript) or can I use PHP (which I am more familiar with)?
EDIT:
After some reading I have got a little bit of code, but it is giving me problems. For some reason I cannot get my script to work based on the state of the form input (enabled or disabled) or the state of my checkbox (checked or unchecked), but my script works fine when I base it on the values of the form inputs. I have written my code exactly like several examples online (mainly this one) but to no avail. None of the stuff that is commented out will work. What am I doing wrong here?
<label>Mailing address same as residental address</label>
<input name="checkbox" onclick="disable_enable()" type="checkbox" style="width:15px"/><br/><br/>
<script type="text/javascript">
function disable_enable(){
if (document.form.mail_street_address.value==1)
document.form.mail_street_address.value=0;
//document.form.mail_street_address.disabled=true;
//document.form.mail_city.disabled=true;
//document.form.mail_state.disabled=true;
//document.form.mail_zip.disabled=true;
else
document.form.mail_street_address.value=1;
//document.form.mail_street.disabled=false;
//document.form.mail_city.disabled=false;
//document.form.mail_state.disabled=false;
//document.form.mail_zip.disabled=false;
}
</script>
EDIT:
Here is some updated code based upon what #Chief17 suggested. Best I can tell none of this is working. I am using value as a test because it works for some reason
<label>Mailing address same as residental address</label>
<input name="checkbox" onclick="disable_enable()" type="checkbox" style="width:15px"/><br/><br/>
<script type="text/javascript">
function disable_enable(){
if (document.getElementById("mail_street_address").getAttribute("disabled")=="disabled")
document.form.mail_street_address.value=0;
//document.getElementById("mail_street_address").removeAttribute("disabled");
//document.getElementById("mail_city").removeAttribute("disabled");
//document.getElementById("mail_state").removeAttribute("disabled");
//document.getElementById("mail_zip").removeAttribute("disabled");
else
document.form.mail_street_address.value=1;
//document.getElementById("mail_street_address").setAttribute("disabled","disabled");
//document.getElementById("mail_city").setAttribute("disabled","disabled");
//document.getElementById("mail_state").setAttribute("disabled","disabled");
//document.getElementById("mail_zip").setAttribute("disabled","disabled");
}
</script>
Unfortunately, since you're doing it in response to user input without a form being sent back to the server, you have to do it through JavaScript.
input elements in JavaScript have both readonly and disabled attributes. If you want them completely disabled, you need to use JavaScript (or a library like jQuery) to change the disabled attribute's value to "disabled".
Note that the disabled inputs will not have their values sent to the server when the form is submitted.
Deleted my other post entirely and replaced with all the code you should need:
<script type="text/javascript">
function disable_enable()
{
if(document.getElementById("checkbox").checked != 1)
{
document.getElementById("input1").removeAttribute("disabled");
document.getElementById("input2").removeAttribute("disabled");
document.getElementById("input3").removeAttribute("disabled");
document.getElementById("input4").removeAttribute("disabled");
}
else
{
document.getElementById("input1").setAttribute("disabled","disabled");
document.getElementById("input2").setAttribute("disabled","disabled");
document.getElementById("input3").setAttribute("disabled","disabled");
document.getElementById("input4").setAttribute("disabled","disabled");
}
}
</script>
and
<label>Mailing address same as residental address</label>
<input id="checkbox" onClick="disable_enable()" type="checkbox" style="width:15px"/><br/><br/>
<input type="text" id="input1" />
<input type="text" id="input2" />
<input type="text" id="input3" />
<input type="text" id="input4" />
Basically, loop through inputs, check if they're checkboxes, add event handlers...
Working sample in plain old javascript:
http://www.theredhead.nl/~kris/stackoverflow/enable-or-disable-input-based-on-checkbox.html
the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Enable/disable input based on checkbox</title>
<script type="text/javascript">
// setup a bit of code to run after the document has loaded. (note that its set on window)
window.addEventListener('load', function(){
potential_checkboxes = document.getElementsByTagName('input');
for(i = 0; i < potential_checkboxes.length; i ++) {
element = potential_checkboxes[i];
// see if we have a checkbox
if (element.getAttribute('type') == 'checkbox') {
// initial setup
textbox = document.getElementById(element.getAttribute('rel'));
textbox.disabled = ! element.checked;
// add event handler to checkbox
element.addEventListener('change', function() {
// inside here, this refers to the checkbox that just got changed
textbox = document.getElementById(this.getAttribute('rel'));
// set disabled property of textbox to not checked property of this checkbox
textbox.disabled = ! this.checked;
}, false);
}
}
}, false);
</script>
</head>
<body>
<h1>Enable/disable input based on checkbox.</h1>
<form>
<label for="textbox_1">
Textbox 1:
<input id="textbox_1" type="text" value="some value" />
</label>
<br />
<input id=="checkbox_1" type="checkbox" rel="textbox_1" />
<label for="checkbox_1">Enable textbox 1?</label>
<hr />
<form>
</body>
</html>
The easiest way is to use JavaScript to enable or disable the form elements when the checkbox's checked status is changed.
That said, you will still need to filter for that checkbox when handling the post on the server, as some browsers will have JS turned off and thus the change will not happen

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();
});

Categories