checkbox set to checked = false not working - javascript

I'm generating an HTML input with checked="false", however the checkbox is showing up checked.
I did the following in the javascript console and can't quite figure out whats going on. The resulting HTML after using .prop() to set the value to false looks the same except now the checkbox is not checked on the form.
> $(':input[checked]').prop('checked');
< true
> $(':input[checked]')
< [
<input type=​"checkbox" class=​"caseVal" checked=​"false">​
]
> $(':input[checked]').prop('checked',false);
< [
<input type=​"checkbox" class=​"caseVal" checked=​"false">​
]
I'm under the impression that I should just be setting checked="checked" OR not including the checked property at all if its false is that best practice? Either way I'd like to know what's going on in the above code.

Don't put checked="false"
You only put checked="checked" for valid XHTML, otherwise you'd do
<input type="checkbox" checked>
The browser doesn't care what value is assigned to checked attribute, as soon as it sees checked in the checkbox input tag, it's flagged as checked.

$(document).ready(function () { $(e).prop("checked", false);}
// "e" refers to button element

How to Uncheck in this case, example my code is: (see below)
if(previousHighlightedCheckbox!=null) {
console.log(sent.id, previousHighlightedCheckbox); // current checkbox and previous check box values are different.
document.getElementById(previousHighlightedCheckbox).checked = false; // still this does not uncheck previous one
}

Related

Checkbox sends same value, no matter if checked or not - javascript, html

I have a checkbox on my site looking like this:
<input type="checkbox" class="form-control" id="jobfixedstart_cb" onclick="jobfixedstartfunc();" />
In a Javascript .onClick-Event I get the value of the checkbox like this:
var addjobfixedstart = document.forms["add-new-job"].jobfixedstart_cb.value;
Now, no matter if the checkbox is checked or not, the value of "addjobfixedstart" is always "on". If I give the checkbox a value, it always sends the value.
What am i doing wrong?
Edit:
I checked the status of the variable with an "alert" after the variable like that:
alert(addjobfixedstart);
If you want to check checked status you should read checked property. For checkbox value read value property. In addition, listen to onchange event, rather then onclick.
All together it will become:
function jobfixedstartfunc() {
var checkbox = document.forms["add-new-job"].jobfixedstart_cb;
alert('Checked:' + checkbox.checked + ', value:' + checkbox.value)
}
<form name="add-new-job">
<input type="checkbox" class="form-control" id="jobfixedstart_cb" onchange="jobfixedstartfunc();" />
</form>
You can try the following if you are trying to know whether a checkbox is checked or not
document.getElementById('jobfixedstart_cb').checked
This returns boolean. I hope this helps.
I made it work by checking the checkbox like this:
var addjobfixedstart = document.getElementById("jobfixedstart_cb").checked
You get back a "true" of "false" value which you can work with.

Check a radio button with javascript

For some reason, I can't seem to figure this out.
I have some radio buttons in my html which toggles categories:
<input type="radio" name="main-categories" id="_1234" value="1234" /> // All
<input type="radio" name="main-categories" id="_2345" value="2345" /> // Certain category
<input type="radio" name="main-categories" id="_3456" value="3456" /> // Certain category
<input type="radio" name="main-categories" id="_4567" value="4567" /> // Certain category
The user can select whichever he/she wants, but when an certain event triggers, I want to set 1234 to be set checked radio button, because this is the default checked radio button.
I have tried versions of this (with and without jQuery):
document.getElementById('#_1234').checked = true;
But it doesn't seem to update. I need it to visibly update so the user can see it.
Can anybody help?
EDIT: I'm just tired and overlooked the #, thanks for pointing it out, that and $.prop().
Do not mix CSS/JQuery syntax (# for identifier) with native JS.
Native JS solution:
document.getElementById("_1234").checked = true;
JQuery solution:
$("#_1234").prop("checked", true);
If you want to set the "1234" button, you need to use its "id":
document.getElementById("_1234").checked = true;
When you're using the browser API ("getElementById"), you don't use selector syntax; you just pass the actual "id" value you're looking for. You use selector syntax with jQuery or .querySelector() and .querySelectorAll().
Today, in the year 2016, it is safe to use document.querySelector without knowing the ID (especially if you have more than 2 radio buttons):
document.querySelector("input[name=main-categories]:checked").value
Easiest way would probably be with jQuery, as follows:
$(document).ready(function(){
$("#_1234").attr("checked","checked");
})
This adds a new attribute "checked" (which in HTML does not need a value).
Just remember to include the jQuery library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
By using document.getElementById() function you don't have to pass # before element's id.
Code:
document.getElementById('_1234').checked = true;
Demo:
JSFiddle
I was able to select (check) a radio input button by using this Javascript code in Firefox 72, within a Web Extension option page to LOAD the value:
var reloadItem = browser.storage.sync.get('reload_mode');
reloadItem.then((response) => {
if (response["reload_mode"] == "Periodic") {
document.querySelector('input[name=reload_mode][value="Periodic"]').click();
} else if (response["reload_mode"] == "Page Bottom") {
document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
} else {
document.querySelector('input[name=reload_mode][value="Both"]').click();
}
});
Where the associated code to SAVE the value was:
reload_mode: document.querySelector('input[name=reload_mode]:checked').value
Given HTML like the following:
<input type="radio" id="periodic" name="reload_mode" value="Periodic">
<label for="periodic">Periodic</label><br>
<input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
<label for="bottom">Page Bottom</label><br>
<input type="radio" id="both" name="reload_mode" value="Both">
<label for="both">Both</label></br></br>
It seems the item.checked property of a HTML radio button cannot be changed with JavaScript in Internet Explorer, or in some older browsers.
I also tried setting the "checked" attribute, using:
item.setAttribute("checked", ""); I know the property can be set by default,
but I need just to change the checked attribute at runtime.
As a workarround, I found another method, which could be working. I had called the item.click(); method of a radio button. And the control has been selected. But the control must be already added to the HTML document, in order to receive the click event.

Checkbox irregularities with jQuery

Here's some html:
<form>
<input type="checkbox" id="check-123" />
<input type="text" id="text-123" onchange="doSomething('123')" />
</form>
And here's some javascript:
function doSomething(key)
{
var textbox = $('#text-'+key);
var checkbox = $('#check-'+key);
checkbox.attr('checked',(textbox.val()!="") );
}
My goal here is to check the checkbox anytime there's a value in the text box, and uncheck when that value is removed. This appears to work fine in the html (I can see checked="checked" being added to the checkbox), but the checkbox only appears checked the first time something is entered in the textbox.
Why would a checkbox show unchecked even if checked="checked" was added to the html?
Use element properties rather than attributes to change their state via javascript
checkbox.prop('checked',(textbox.val()!="") );
From the jQuery docs on .attr() and .prop():
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
The emphasis is jQuery's own. Only the checked property will reflect and control the checkbox's current state. The checked attribute shouldn't be used to control the checkbox state.
consider something like:
function doSomething(el) {
el.form['check-' + el.name.split('-')[1]].checked = !!el.value;
}
<form>
<input type="checkbox" name="check-123">
<input type="text" name="text-123" onchange="doSomething(this)">
</form>
I've seen some funny things with the checked attribute in IE8 and lower. In some cases I've had to set both the property and the attribute, even though modern browsers seem to be okay with just adjusting the property:
checkbox.prop('checked',textbox.val()!="");//property
Note, the following is only necessary if you come across any browser related inconsistencies.
if(textbox.val()!="")
{
checkbox.attr('checked','checked');
}
else
{
checkbox.removeAttr('checked');
}

JavaScript help needed

hello i'm using this code for publishing important messages on my applications message wall, i'm using a checkbox for publishing important message on message wall. the problem is that after publishing important message it will again publish the important message without clicking on checkbox, means the checkbox remains true after publishing the important message. please help me for this.
and my code is:
<div class="checkbox" id="checkboxShow" name="userCheckList1" style="display:block;" onclick="importantChkBoxChange(userCheckListShow.checked);">
<input type="checkbox" name="userCheckList1" id="userCheckListShow" unchecked="unchecked"
onchange="importantChkBoxChange(userCheckList.checked);"/>
</div>
<div class="checkbox" id="checkboxHide" name="userCheckList1" style="display:none;" onclick="importantChkBoxChange(userCheckListHide.checked);">
<input type="checkbox" name="userCheckList1" id="userCheckListHide" unchecked="unchecked"
onchange="importantChkBoxChange(userCheckListHide.checked);"/>
</div>
<span class="fl" style="margin:3px 0px 0 0;" ><#spring.message "label.employee.home.Important"/></span>
and the script used for this is:
function importantChkBoxChange(chkBoxStatus){
if(chkBoxStatus == true){
document.forms['messageWallForm'].elements['important'].value="checked";
}else if(chkBoxStatus == false){
document.forms['messageWallForm'].elements['important'].value="unchecked";
}
}
Ok, first unchecked is not a property of input. You can have <input type="checkbox" checked="checked" /> if you want to be XML conscious, or you can simply omit the ="checked": <input type="checkbox" checked />, but unchecked is default, so there is no way to us an unchecked attribute.
Second, I noticed that there are variables userCheckListHide and userCheckListShow, but I don't see a declaration of those variables. Are you sure that they exist? Was userCheckListShow = document.getElementById("userCheckListShow") called after the input was created? Otherwise you're dealing with null values.
Third, with checkboxes and radio buttons, you're not interested in the value, so much as you are interested in whether they are checked. You could re-write your function:
// changed the variable name so that it wouldn't scroll. Your var. name was fine.
function importantChkBoxChange(stat){
// since your test is if(checked) set it to checked otherwise set it to
// unchecked, you can simply set the checked property directly.
document.forms['messageWallForm'].elements['important'].checked = stat;
}
As a side note, if you want this to reflect whether either of the cb's in your question are selected, then both onchange handlers should be:
importantChkBoxChange(userCheckList.checked || userCheckListHide.checked);
I dont know where to begin , but here are a few pointers .
A checkbox is not checked/unchecked by changing it's value . It has a checked attribute .Something like document.getElementById('checkBoxId').checked=true
Use DOM ids to refer to your DOM elements .Ideally .
if(chkBoxStatus == true) is redundant
there's no unchecked attribute for checkboxes
if you want to transmit the checked status of a checkbox to a js function on an event (like onchange) , you can do like onchange="foo(this.checked)"

HTML Input Checkbox return 'On' instead of 'True' when submitting form

I have a MVC3 app using Project Awesome (http://awesome.codeplex.com/), but I am getting a weird behaviour on checkboxes. I have the following simple Html within a Modal popup <input type="checkbox" class="check-box" name="IsDeleted">
When I submit the form containing this element, its post value is 'on' instead of the expected 'true' (when element is checked).
Does anybody know why this is? I am assuming there may be some javascript somewhere messing with the form data, but wanted to check whether there isn't some HTML I am missing.
Thanks
Set the checkboxes value attribute to true and you will get true in your post value.
It's browser specific, I suppose, what to send when value is undefined. You need to defined value attribute on your radios/checkboxes to be sure what will be passed back to you. I would suggest value="1"
set data-val="true" and value="true" by deafult...
if checkbox is checked then returns true
Check Checkbox is checked or not if checked set Hidden field true else set hidden field false.
$('#hiddenFieldId').val($('#CheckBoxId').attr('checked')=='checked')
Surely you should just check if it is set - the value that it sends across is irrelevant, if it's not checked, then nothing at all gets sent when you POST.
Nothing worked!
I ended up on a hacky way after seeing the serialised form object just before posting to controller/action. Its not safe in case if anyone would have any textboxes inside that may contain ampersands. In my case, i had an array of checkboxes, so I did this hack after I am very sure, i won't have problems.
var formData = $("#form").serialize();
formData = formData.replaceAll('=on&','=true&');
if (formData.endsWith('=on'))
{
formData = formData.substring(0, formData.length - 3) + "=true";
}
Hope it helps to those 'someone' with my scenario. Happy hacking.
Use jQuery for cross-browser decision. And it will return true or false anyway.
$('#check-box-id').attr('checked' ) == true
if your checkbox has an id check-box-id. For your current version use the next (select by class name):
$('.check-box').attr('checked' ) == true
Use jQuery
var out=$('.check-box').is('checked')
If checkbox is checked out=true
else out=false
In HTML, add a input type="hidden" above checkbox:
<input name="active" id="activeVal" type="hidden">
<input id="active" type="checkbox">
Then, add a script as below:
$('#activeVal').val($('#active').is(':checked'));
$('#active').change(function() {
$('#activeVal').val($('#active').is(':checked'));
});
When you do eg. $('#your-form').serialize() in jQuery, you will get value of checkbox when checked active: true or uncheck active: false

Categories