I am trying to create a simple way to force a single checkbox to display "No" in a form submission if left unchecked, or clicked off. I've tried a number of ways and this is the closest I can get, but it still isn't working properly.
Any help is much appreciated.
Matt
$(function opt() {
if ($("#optIn").is(":checked")) {
$("#optIn").value="Yes"
$("#optIn").click(function() { this.value="No" })
} else {
$("#optIn").value="No"
$("#optIn").click(function() { this.value="Yes" })
}
return false
});
opt();
An unchecked checked box is not a successful control and is therefore not POSTed with the rest of the form data.
The easiest solution for this is to create a hidden input with the same name as your checkbox that will contain the "unchecked" value:
<input type="hidden" name="myCheckbox" value="No" />
<input type="checkbox" name="myCheckbox" value="Yes" />
This will cause the form to POST myCheckbox=No if the checkbox is left unchecked.
So to start out quite frankly, I'm not sure where you saw that sort of function setup before. You're code, as-is, could be reduced to this:
$(function() { // on DOM ready (when the DOM is finished loading)
$('#optIn').click(function() { // when the checkbox is clicked
var checked = $('#optIn').is(':checked'); // check the state
$('#optIn').val(checked ? "Yes" : "No"); // set the value
});
$('#optIn').triggerHandler("click"); // initialize the value
});
The value of the checkbox, however, is never displayed on the screen. You may need to update a separate field with the values "Yes" or "No", such as:
<input type="checkbox" id="optIn" />
<span id="optInLabel"/>No</span>
And the script:
$(function() { // on DOM ready (when the DOM is finished loading)
$('#optIn').click(function() {
optIn(this);
});
optIn($('#optIn')[0]);
});
function optIn(el) {
var checked = $(el).is(':checked'); // check the state
$('#optInLabel').html(checked ? "Yes" : "No"); // set the value
}
EDIT: Working jsFiddle
If you need to check whether the box is checked on the server-side post-form-submission, then you could also update a hidden input field with the value "Yes" or "No" and ignore the submitted checkbox element value (as jaredhoyt mentioned in his answer).
Use radio buttons:
<span>Opt in?</span>
<br>
<input type="radio" name="optIn" value="no" checked>No
<input type="radio" name="optIn" value="yes">Yes
No javascript required, works in every browser, no shims, no libraries, nothing.
Related
This is my first time posting so I apologize if I've missed something or if I get something wrong. I've also looked at other posts and although some are very similar, I don't think it's quite getting to the answer I'm seeking. I am also very new to AJAX (although this code doesn't really utilize a lot of AJAX I think) so any helpful insight into this problem would be greatly appreciated.
I'm trying to create a quiz template that calls on the data from a PHP file using AJAX after selecting a radio button and clicking the "Answer" button.
The general idea is that after the user reads the question, they select a radio button and clicks on the "Answer" button, the bottom part of the page gets populated with either the correct or incorrect string. It's easy to populate it with text and css, but my issue lies in pulling the right text.
Here is the HTML code block that sets up the form submission:
<form action="data.php" method="post" id="q1">
<input type="radio" name="answer1" value="1a" id="1q"> A.
<br>
<input type="radio" name="answer1" value="1b" id="1q"> B.
<br>
<input type="radio" name="answer1" value="1c" id="1q"> C.
<br>
<input type="radio" name="answer1" value="1d" id="1q"> D.
<br>
<input name="submit1" id="answer" type="button" title="abutton" value="ANSWER">
</form>
Here I've set up four radio buttons that each correspond to a letter and the form is linked to data.php, the file I'm pulling the correct/incorrect text from in this case.
I had an earlier version of the code that would follow the logic I had set out to do but would populate the correct text in another page. My goal is populate the a grey "Answer" box in the same page that appears after clicking the "Answer" button with text. The appended text is defined as a variable in the code as $correct or $incorrect, based on the user's selection.
The JS code block that calls the PHP file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#answer").click(function()
{
var test1 = $.post("data.php",
{answer1:'1d'},
function(data)
{
$("#text1").empty();
$("#text1").append(data);
$("#panel").fadeDown("slow");
});
});
});
</script>
I had help constructing this JS code but I understand enough of it. The goal here is that the "Answer" button, after being clicked, appends the text below the form element. This shows up as a small, grey "Answer" box from where users can read whether they got the right answer or not.
This particular line of code is what's bugging me:
{answer1:'1d'},
1d contains the right answer and when you pick any radio button and press "Answer", it still shows the correct text.
But when I try to do something like this:
{answer1:'1d',answer1:'1a',answer1:'1b',answer1'1c'},
The incorrect text, which is supposed to populate after choosing the radio buttons 1a, 1b, or 1c, overrides the text that's supposed to populate, even if the radio button 1d is chosen.
The PHP code that the JS code is calling from:
<?php
$correct = "Correct";
$incorrect = "Incorrect";
if (isset($_POST['answer1']))
{
if ($_POST['answer1'] === '1d')
{
print $correct1;
}
elseif ($_POST['answer1'] === '1b')
{
print $incorrect1;
}
elseif ($_POST['answer1'] ==='1c')
{
print $incorrect1;
}
elseif ($_POST['answer1'] === '1a')
{
print $incorrect1;
}
};
?>
Again, any insight on this problem would be greatly appreciated! Let me know if I need to clarify anything. Thanks!
First, id should always be unique. So remove or change the id of your inputs radio.
Then, you need to change your ajax request to send the selected input radio like this :
$(document).ready(function() {
$("#answer").click(function() {
var answer = $("input[name=answer1]:checked").val();
$.post("data.php", {answer1: answer}, function(data){
$("#text1").empty();
$("#text1").append(data);
$("#panel").fadeIn("slow");
});
});
});
Because in your code you never send the selected radio to your php page. And if you only send "1d" in this line {answer1:'1d'} your php page will always return the "correct" text even if you check another radio button.
I don't know the jQuery fadeDown() method. Only fadeIn() or fadeOut().
Also, in your data.php $correct1 and $incorrect1 are undefined. So echo $correct or $incorrect.
I have a form, and when a user uploads a training document it will check the checkbox
$('#training_code_'+trainingCode).attr('checked','checked');
If the user deletes the training it will run this :
$('#training_code_'+trainingCode).removeAttr('checked');
HTML:
<input type="checkbox" value="1" name="training_code_1" id="training_code_1"
<? if(mysql_num_rows($result_waperd)>0) echo"checked"; ?> disabled="disabled"/>
I tried to:
upload a file and it's checked.
delete the file and it's unchecked.
upload a file again and it still unchecked.
Does anyone know why that happens?
For DOM properties like checked, disabled and readonly, the proper way to do this (as of JQuery 1.6) is to use prop.
$('#someid').prop('disabled', true);
so try (to check):
$('#training_code_'+trainingCode).prop('checked',true);
uncheck:
$('#training_code_'+trainingCode).prop('checked',false);
I'm using the following code to test for "if" a checkbox is checked on page load.
If it is, then a certain additional field will be shown (called myfield):
<style>
#myfield {
display: none;
}
</style>
<input type="checkbox" id="mycheckbox" name="mycheckbox" />
<input type='text' id='myfield' name='myfield' />
<script>
if ($("#mycheckbox").is(":checked")) {
document.getElementById("id").style.display="block";
}
</script>
However, this only works when the page loads and the checkbox is already checked. It doesn't work live when the box isn't checked on page load, and you go to click the box. I want the hidden field to show up right away when the box is "checked" without the page having to reload. I then want myfield to hide right away when the box is unchecked.
Can any anyone point out the better/proper way to do this?
Additionally:
Of note: I do know how to do this in CSS using labels, but I need to use javascript other times.
Here's what works fine in modern browsers using just CSS: http://jsfiddle.net/3KTC3/
Here's that CSS only jsfiddle code:
<style type="text/css">
.label-for-check {
display:none;
}
.check-with-label:checked + .label-for-check {
display:block;
}
</style>
<div>
<input type="checkbox" id="check" class="check-with-label" />
<label for="check" class="label-for-check">
<br /><br />MyField<br />
<input type='text' id='myfield' name='myfield' size='10' />
</label>
<div>
You need to attach a change event handler. Your posted code only executes when page is loaded, it doesn't watch over your element's state.
Here's a jQuery equivalent to your CSS version with classes and adjacent selector:
$('.check-with-label').change(function() {
$(this).next().toggle(this.checked);
}).change();
Fiddle
Explanation: this references the checkbox being clicked, get the next element (equivalent to your CSS + selector) and toggle its display based on the checked state of the checkbox.
Another version that works only with your 2 given IDs:
$('#mycheckbox').change(function() {
$('#myfield').toggle(this.checked);
}).change();
Fiddle
Note that your CSS version is compatible with all desktop browsers including IE7 and above. Consider whether it is necessary to use JS for this.
edit: You have to trigger the change handler after attaching it, so if the checkbox is already checked when the page is loaded, the triggered handler will display the field.
Your problem is that jQuery will only check one time (when you load the site) if your checkbox is checked.
The change handler will fire every time the user changes the checkbox, if it is cheked it will show #myfield
Do something like this:
$('#mycheckbox').change(function() {
if ($(this).is(":checked")) {
$('#myfield').show()
}
});
$(document).ready(function(){
if($("#mycheckbox").is(":checked")) $('#myfield').show();
$('#mycheckbox').on('change', function(){
if($(this).is(":checked")) {
$('#myfield').show();
} else {
$('#myfield').hide();
}
})
});
right now when it first loads the html page, my checkbox was created in this way:
<input type="checkbox" id="CBOX1" name="CBOX1" onclick="onCBOX(this)" disabled/>
in a function in on the same html:
boolean checked = true;
document.theForm.elements['CBOX1'].checked = true;
For some reason, the checked box value is not checked when the function is called later on the page. Is it because when i first created the checkbox, i created it without a 'checked' attribute? And then when i assign it a value, the element doesnt seem to include the checked attribute anymore as when i check on the source of the page. its still the same...
<input type="checkbox" id="CBOX1" name="CBOX1" onclick="onCBOX(this)" disabled/>
For simplicity sake, i know for sure that there were changes made to other attributes of this element using AJAX, but i am at a loss to WHY the checked attribute is not carried over... What's the alternative?
Check the checkbox:
document.theForm.elements['CBOX1'].checked = true;
document.theForm.elements['CBOX1'].checked = "checked";
Uncheck the checkbox:
document.theForm.elements['CBOX1'].checked = false;
If you want it unchecked on load then don't touch it, by default it is unchecked.
Moreover, no click events will be registered if you use the disabled attribute on your input field.
See this jsfiddle for an example.
EDIT
If clickability is not the issue then just do what I already pointed out. Here is a full working example.
<html>
<head>
</head>
<body>
<input id="tar" type="checkbox" disabled />
<input type="checkbox" onclick="callFunc(this)" />
<script type="text/javascript">
function callFunc(elem){
document.getElementById("tar").checked = elem.checked;
}
</script>
</body>
</html>
Try setting it to true instead:
document.theForm.elements['CBOX1'].checked = true;
Try this, not tested anyway.
document.theForm.elements['CBOX1'].checked = true;
I am using the following code to make a custom checkbox with my own images and it works but it's using a Checkbox and I need to use Radio buttons.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#moreinfo").change(function() {
if(this.checked) {
$(this).prev().attr("src", "checkbox_unchecked.gif");
} else {
$(this).prev().attr("src", "checkbox_checked.gif");
}
});
});
</script>
Next...here's the HTML:
<label for="moreinfo">
<img src="checkbox_unchecked.gif"/>
<input name="moreinfo" type="checkbox" id="moreinfo" style="display:none">
</label>
If it a question of changing from checkbox to radio type or does the jquery need changing too?
How do I go about this?
Change the type="checkbox" to type="radio" (and add some more radio buttons for testing, grouping them via the name attribute, they may not have the same id as IDs are unique!). Then, you also need to handle the click event of the replacement images.
But actually, that's going beyond your original question, which you could have solved by simply trying it out. ;)
A Radio Button uses also the attribute checked. So you can switch the element without changing the script (perhaps the gifs).
But your script will never run, because your checkbox/radio button is not displayed.
So you need some functionality to change the status when clicking the image.