changing ''checked' attribute of a checkbox using javascript - javascript

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;

Related

onclick function on a radio or checkbox input?

Is it possible to have a function execute when a radio or checkbox is clicked?
I tried this:
<input name="email_notification" id="email_not1" type="radio" class="form_radio" onclick="select_on()" value=1 <?PHP echo $on;?>>
It doesn't work. I could wrap it in a label and put the onclick function on that, but I need it only on the radio button and not the label. Is this possible?
UPDATE:
Thanks for your answers! I tried it with another function and it worked fine. Part of the original function was to set the checkbox to "checked" and apparently that was conflicting with it. I made a duplicate function with that part removed and it works fine. :)
Basically, and normally yes. If the Javascript function is declared properly and/or file containing the function is included properly on the page. See example:
<input name="email_notification" id="email_not1" type="radio" class="form_radio" onclick="select_on()">
<script>
function select_on() {
alert('Hello');
// do whatever you want here.
}
</script>
Your snippet works for me. You might have a trigger attached to this element, and that can eat up your default event handling.
It works just fine, you have errors elsewhere or there's an element on top of your checkbox and you're not really clicking on it.
See it here:
function select_on() {
alert('it works!');
}
<input name="email_notification" id="email_not1" type="radio" class="form_radio" onclick="select_on()" value=1 />
<input name="email_notification" id="email_not1" type="radio" class="form_radio" onclick="select_on(this)">
<script>
function select_on(node) {
if(node.checked) {
alert('checked true');
} else {
alert('checked false');
}
}
</script>
You can use jquery change function here.
Sample code:
$('input:radio[name="email_notification"]').change(function() {
//do whatever you need here
});
Or if you want to trigger a function for every clicks you can simply use:
$('input:radio[name="email_notification"]').click(function() {
//do whatever you need here
});

How do I make this Javascript checkbox trigger action work like my CSS only example

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

Opt-in / Opt-out Checkbox

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.

JQuery Custom Image From Checkbox to Radio

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.

Automatically making a div appear based on status of radio button with JavaScript

I have a form which posts data to the same page. Based on the user's radio button selection I am inserting checked="checked" into the radio button form element to redisplay the correct selection. This works fine, however when the form is redisplayed (in case of bad input etc), I need a div to be revealed (containing the relevant fields from the form).
I have an onclick event that reveals the div in the first place (before the user has posted the form), and this works fine, but when I redisplay the form I don't want the user to have to manually reveal the form again by clicking.
Therefore I've been trying something along the following lines (heavily cut down for the purposes of this post)...
<link href="styles/style1.css" rel="stylesheet" type="text/css" />
<script language="JavaScript">
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
</script>
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes
<input id="complete_no" type="radio" name="complete" value="false"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
... but it returns an Object Required javascript error (as it does in the 'real' page):
Message: Object required
Line: 3
Char: 1
Code: 0
URI: http://localhost/repair_system/javascript_test.php
Why is this? Am I not correctly referencing the form element? Apologies if I'm being a "div" (deliberate bad pun intended!), I'm yet to learn about the fun and games of javascript!
Because your javascript is not wrapped inside a function, the browser is executing it as soon as it "gets to it". In this case, the JS is being executed before the browser has reached the html declaring your form.
The simplest fix therefore is to move the Javascript to after your form. A more robust solution would be to wrap you code in a function, and have that triggered somehow - from what you appear to be trying to do, in this case it'll be the onLoad event of the body tag:
<head>
<script language="JavaScript">
function showHelpDiv() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
</script>
</head>
<body onload="showHelpDiv()">
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes
<input id="complete_no" type="radio" name="complete" value="false"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
Your code is being executed as the document is being loaded, and the DOM tree isn't ready yet. So it is trying to access an element that doesn't exist yet.
You probably want to instead write an event handler that toggles the div whenever the checkbox is checked.
I prefer jQuery, which abstracts away things like cross-browser event handling, provides lots of nice helpers and generally makes code look cleaner (when written properly). Something like this should work:
$(document).ready(function() {
$('#repair_complete').toggle($('#complete_yes').is(':checked'));
}
The above can be roughly translated as:
When the document loads, perform the following:
Add an event handler for the 'change' event to any elements of type 'input' with a name of 'complete'
When the event handler fires, toggle the visibility of the element with ID 'repair_complete' where it should be visible if the element with ID 'complete_yes' is checked
Update: The JS above now actually does what you want, originally I had it written as an onclick
This is because Javascript is executed just before rest of the objects are created.
Place your javascript code into the function body, and add this function into onclick event for whatever you need.
<link href="styles/style1.css" rel="stylesheet" type="text/css" />
<script language="JavaScript">
function test() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
</script>
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true" onClick="javascript: test();"/>Yes
<input id="complete_no" type="radio" name="complete" value="false" onClick="javascript: test();"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
</form>
It looks to me as though your script is firing before the form is drawn, you may want to move your script block to after the form element. Basically I think that the document.getElementById('complete_yes').checked is looking at null.checked, which would trigger the object required error.
You should make the action of the radio button be to change the visibility of the div (that is, "push" the status to it), rather than to "pull" the div status via the radio button status at render time (which as Andrejs said, will be unset).
Sounds like the problem is in your initialization code. The javascript is being called before the page is finished rendering. It's one annoying aspect of the "onload" event that in my opinion simply doesn't work as it should in every browser.
There's a cross-browser technique to call initialization code once and only once after the DOM is fully loaded.
Try this code in the HEAD of your HTML:
function showHelpDiv() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
function InitOnce()
{
if (arguments.callee.done) return;
arguments.callee.done = true;
showHelpDiv();
}
/* for Mozilla */
if (document.addEventListener)
{
document.addEventListener("DOMContentLoaded", InitOnce, null);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script defer src=ie_onload.js><"+"/script>");
/*#end #*/
/* for other browsers */
window.onload = InitOnce;
And then you need to create an ie_onload.js file that contains this line for IE compatibility:
InitOnce();
I've tried other techniques but none work as perfectly as this. I believe I originally found this solution here:
http://dean.edwards.name/weblog/2005/09/busted/
I use it in an online application that receives 500 unique visits a day or so and this has been reliable for us.

Categories

Resources