After form submit show / hide div +input field based on checkbox? - php

Apparently I am doing something wrong. I have a simple form which reload the page with a bunch of chosen variables (input field values). Now one of my input fields I like to hide and show based on a checkbox. This input field is within a span element, so I just hide/show the span element
I have this part working by
// Show/Hide div span
$('#showDiv').click(function () {
$("#element_span_with_input_field").toggle(this.checked);
if (!$('#element_span_with_input_field').is(":visible")) {
alert("empty input field");
$('#inputfield').val('');
}
});
Now with a simple php $_REQUEST I can check if the checkbox is checked=checked
<input <?php if (isset($_REQUEST['showDiv']) && ($_REQUEST['showDiv'] == '1')) echo 'checked="checked"'; ?> type="checkbox" value="1" name="showDiv" id="showDiv" />Show Div
and the checkbox works.
Now I thought this should do the trick to set show/hide the div on ready
if ($("#showDiv").val() == '1') {
$('#element_span_with_input_field').show();
//$('#element_span_with_input_field').css({ visibility: "visible"});//also tried
} else {
$('#element_span_with_input_field').hide();
}
My Problem: When I uncheck the showDiv checkbox the div becomes visible when I submit the form (and the showDiv variable isn't even set??)

To check during DOM ready if a checkbox is pre-checked or not (based on your PHP setting of the checked="checked" attribute), you would look for the is checked setting:
$(document).ready(function() {
if ($("#showDiv").is(':checked')) {
$('#element_span_with_input_field').show();
} else {
$('#element_span_with_input_field').hide();
}
});
The rest of your code should work out, as you said. Just keep in mind that when a checkbox is not checked, there will not be a variable by its name in $_POST or $_REQUEST. So indeed, if it does not exist (or is empty), consider it false.
As a side note, you may want to tweak the other block a little as such:
$(document).ready(function() {
$('#showDiv').click(function () {
$("#element_span_with_input_field").toggle($(this).is(":checked")); // use jquery
if (!$(this).is(":checked")) { // eval the checkbox state instead
$('#inputfield').val('');
}
});
});

Related

Dynamic list of radio buttons - how do I retrieve value instead of retrieve BY VALUE

I have a list of radio buttons that gets loaded from a database. $missing below is a mysql query result in which I retrieve labels for my radio buttons. That part works a-okay:
<div id="container">
<div id="col1">
<div>
<div id="dam_return">
<form method="post" action="#" >';
foreach ($missing as &$path) {
$prov = $path['template_name'];
$return .= '<input type="radio" name="radio_group1" value="$prov" class="radios">'.$prov."</option>";
$return .= '<br>';
}
$return .= '</form>';
I inject this return value from the above into my HTML elsewhere in my PHP code (and yes I properly close the divs after, etc.). This part works fine so far.
So then, I have a listener for my class of radio buttons:
$(".radios").click(function () {
$('[id$=mytextbox]').val("asdadasd");
$.get('?page=EntitlementTemplates&action=dothething&var1=somestuff', function() {
$(node).removeClass('selected');
$(node).addClass('delete');
});
//location.reload();
});
Now here is me reading my get:
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'dothething' :
//I want to manipulate/identify the selected radio button
break;
In this get code, I want to get the value of the radio button that is pressed. There are many examples online using a switch statement for a discrete list of values... but I want to retrieve the radio button BY value. I will use this radio button value to then load some new data to the page... but right now I don't know how to get what radio button was selected? I can't seem to find anything for this scenario.
In order to pass the clicked element value to your server in your click event hanler, you have to pass it as a parameter in your GET-request query.
In your click handler:
$(".radios").click(
$('[id$=mytextbox]').val("asdadasd");
var radioValue = $(this).val();
$.get('?page=EntitlementTemplates&action=dothething&var1=somestuff&clickedRadioValue='+radioValue , function() {
$(node).removeClass('selected');
$(node).addClass('delete');
});
//location.reload();
});
In your php script:
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'dothething' :
$clickedRadioValue = $_GET['clickedRadioValue'];
//further manipulations
break;
//other cases
}
}
The selected value will be delivered under the name of the radio group; in this case: $_POST['radio_group1'] ... it is under $_POST instead of $_GET because of the method specified on your form.

How to check multiple checkboxes checked using jquery?

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.");
}

Grab checkbox values before form submission

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.

Javascript function only outputs value of first check box from a PHP for loop

I have a for loop that forms a list of check boxes based on information received from a mySQL database. Below is the for loop that forms the check boxes (unnecessary code removed).
for ($i = 1; $i <= count($descriptionIDsArray); $i++) {
$statuses = mysql_fetch_assoc(mysql_query(sprintf("SELECT status, description FROM status_descriptions WHERE description_id='$i'")));
$status = $statuses["status"]; ?>
<input type="checkbox" value="<?php echo $status ?>" <?php if ($check == 1) {echo "checked='checked'";} ?> onchange="checkBox()" /><?php echo $description ?><br />
<?php } ?>
Checking or unchecking a box calls the following function:
<script type="text/javascript">
function checkBox() {
var status = $("input:checkbox").val();
document.getElementById("test").innerHTML = status;
}
</script>
The only value that I can get to appear in "test" is the value of the first check box. If I echo $status throughout the initial for loop all the values appear correctly so the problem seems to arise when the Javascript code is retrieving the corresponding value.
If you still want to keep the inline event handlers, change it to:
onclick="checkBox(this);"
And change the function to:
function checkBox(chk) {
var status = chk.value;
document.getElementById("test").innerHTML = status;
}
Note that onclick is better supported with checkboxes and radio buttons than is onchange. Also, the reason for this change I provided is because passing this to the checkBox function references the element that the click was applied to. That way, you know that inside of checkBox, the parameter chk will be the specific checkbox that just changed. Then just get the value with .value because it's a simple DOM node.
Anyways, I'd suggest using jQuery to bind the click event. Something like:
$(document).ready(function () {
$("input:checkbox").on("click", function () {
var status = this.value;
document.getElementById("test").innerHTML = status;
});
});
But you can obviously use $(this).val() instead of this.value, but why bother? If you use jQuery to bind the events, just make sure you take out the onchange/onclick inline event handler in the HTML.
You can look at why to use input:checkbox and not just :checkbox as the jQuery selector here: http://api.jquery.com/checkbox-selector/
When you do
$('input:checkbox').val();
it is returning the first input of type checkbox on your form, not necessarily the one that is clicked.
To return the one that was actually clicked, you need to do something like this:
$(document).ready(function() {
$('input:checkbox').bind('click', function() {
clickBox($(this));
});
});
function clickBox(field) {
$('#test').html(field.val());
}
if you use a jquery, why bother with inline events?
You could write that like:
$(':checkbox').change( function(){
$('#test').html( $(this).val() );
//`this` is the checkbox was changed
//for check if item is checked try:
$(this).is(':checked') // boolean
});
If you pass that code before your checkboxes are placed make sure you invoke that code when document is loaded;
$( function(){
//code from above here
});
jQuery is well documented with lots of samples.
I think you'll like it docs.jquery.com

Select only one checkbox (and deselect rest) and show input field if checkbox selected

I have a form with "Yes" and "No" as two checkboxes. These come in unselected at first. I'd like the user to only select one of these with the option to deselect their choice if they don't want to make a decision (which is why I didn't use radio buttons). Selecting Yes should deselect No and vice versa. I'm not sure how to do this. I'm using PHP (codeigniter), Javascript and JQuery.
Secondly, after either Yes or No is selected, an input field needs to be displayed. I've got this setup but it toggles on the "onclick" action, which means selecting Yes twice shows and hides the input field! I want the input field to show if Yes or No are selected and disappear if the both Yes and No are unselected.
$do_toggle = "onClick=\"javascript:toggle('togglenote');\"";
echo form_radio('decision'.$key,'y',FALSE,$do_toggle)."Yes ";
echo form_radio('decision'.$key,'n',FALSE,$do_toggle)."No";
echo form_input($mytext);
// I put a div tag around the form_input above
// but it's not showing in the StackOverflow question...
// but it's there for the toggle to work.
Assuming your html is like this (i think it is):
<input type="checkbox" name="decisionY" value="y" /> Yes
<input type="checkbox" name="decisionN" value="N" /> Yes
<input type="text" id="togglenote" name="togglenote" />
Your js would be:
$(document).ready(function(){
$(":checkbox[name^='decision']").change(function(){
if($(this).is(":checked")){
$(":checkbox[name[^='decision']").attr("checked", false); //Uncheck the other
$(this).attr("checked", true);
$("#togglenote").show();
}
if($(":checkbox[name^='decision']:checked").size() == 0){
$("#togglenote").hide();
}
});
});
Hope this helps. Cheers.
This should do what you want:
$("#checkbox1").change(function() {
if ($(this).attr("checked") && $("#checkbox2").attr("checked")) {
$("checkbox2").removeAttr("checked");
} else if ($(this).attr("checked")) {
$("#inputfield").show();
} else {
$("#inputfield").hide();
}
});
$("#checkbox2").change(function() {
if ($(this).attr("checked") && $("#checkbox1").attr("checked")) {
$("checkbox1").removeAttr("checked");
} else if ($(this).attr("checked")) {
$("#inputfield").show();
} else {
$("#inputfield").hide();
}
});
select one of them as jQuery or javascript
Dont think that this is 100% garantee that some hacker can't set up both and post :)
Analise $_REQUEST array against setted up both yes/no values
Make decision.
PS. JQuery works not at my nokia 6303c :) device, hard coded - will work ... so application must have 2 parts.

Categories