Checking a Checkbox through JS in browser - javascript

I'm looking to set multiple values and checkboxes on a webpage using JS.
I'm able to do values using
document.querySelector('input[name="date"]').value = '1/1/2000';
document.querySelector('form').submit();
...that's simple enough. There are multiple checkboxes that may or may not need to be checked. What is the process to check a box through the console? Here is a sample of one of them when it is checked:
input id="FormView1_cb_EXAMPLE" type="checkbox"
name="FormView1$cb_EXAMPLE" checked="checked"

You can do this by targeting the checked attribute of the item after selecting it with either querySelector or getElementByID. Then simply set it to true for checked.
document.querySelector('#steve').checked=true
<input id="steve" type="checkbox">
If you need to do it to multiple and they all have the same class name, you can use querySelectorAll and a forEach/for loop and set each one to true (checked) using that method. (this would only work if your list of which ones need to be checked conditionally is constant)

I hope your job looks
var input = document.querySelector('#FormView1_cb_EXAMPLE').checked;
console.log(input)
<input id="FormView1_cb_EXAMPLE" type="checkbox">

Related

How to collect a string from a radio input and send it to a useState? (React) [duplicate]

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

Javascript if statement using :checked and .bind but only one option works

I am trying to create an Override Button to disable auto-complete for a form I am building and would like to use Javascript to have div "manualOverrideWarning" to display a warning if the button is selected. The problem is that the function only works the first time the user presses the button but then does not remove the warning once the override is turned off. Any and all pointers in how I used Javascript wrong in my code would be greatly appreciated! Thanks!
Html:
Manual Overide:
<label>No <input type="radio"
name="manualOverride" id="manualOverrideNo" value="no" checked /></label>
<label>Yes<input type="radio"
name="manualOverride" id="manualOverrideYes" value="yes" /></label>
<div id="manualOverrideWarning">test</div>
Javascript:
$('#manualOverrideYes, #manualOverrideNo').bind('change', function () {
if($('input[name="manualOverrideYes"]:checked')) {
$('#manualOverrideWarning').text('Autocomplete Disabled!');
} else {
if($$('#manualOverrideWarning').text(''));
}
});
Thanks again y'all! You all are my heroes!
You need to use .is() to test the selected element against a selector
if($('input[name="manualOverrideYes"]').is(':checked')) {
$('input[name="manualOverrideYes"]:checked') returns a jQuery wrapper object which will always be truthy.
If the checkbox is selected then the jQuery wrapper will contain 1 element else 0 element, but still a object will be returned.
Another way to use it is to test the length of the returned object like
if($('input[name="manualOverrideYes"]:checked').length) {
I would do your check with is():
if($('input[name="manualOverrideYes"]').is(':checked')) {
Or if you like your original version then you would need to check the length property to see if any results were actually returned:
if($('input[name="manualOverrideYes"]:checked').length)
Also it looks like you have a typo here:
if($$('#manualOverrideWarning').text(''));
I assume that should be
if($('#manualOverrideWarning').text(''));

Radio button value regardless of selected input

I have this code:
<input type="radio" name="pay" id="payid" value="banktransfer"> Bank Transfer <br/>
<input type="radio" name="pay" id="payid" value="paypal"> PayPal <br/> <br/>
I try:
var sample = $('#payid').val()
alert(sample);
Why I have still banktransfer? (regardless of the selected input)?
The id must be unique. Radios need the same name for their on-off functionality to work, but each must have a unique id. You could, for instance, have "payid1" and "payid2"
The ID attribute must be unique across the page. In your case jQuery is just picking the first element with that ID and returning that value. This code will get you the selected value.
jQuery("input[name=pay]:checked").val();
Try
var sample = $("[name=pay]:checked").val()
You need to specify which one of the radio buttons you want, you can get the correct one (the checked one) by using the :checked selector. You also need to use the name attribute selector, because id needs to be unique and JQuery will only ever return the first match.
This should work for you:
var sample = $('[name="pay"]:checked').val();
alert(sample);
Here is a working example

How to disable enable a checkbox based on another checkbox?

Following code is generated by a for loop.
<form action="saveresponse.php" method="POST" name="mainForm">
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="01.jpg" disabled />Special<br />
<input class="cbox_yes" type="checkbox" name="yes[]" value="02.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="02.jpg" disabled />Special<br />
etc etc upto n times...
Now, what I want is that on page load, all the sp[] checkboxes should be disabled and enabled only if their corrosponding yes[] checkbox is checked by user.
Javascript code I am using: (Just to check if JS is capturing the states of yes[] checkbox?
function spenable(){
var yes = document.mainForm.yes[].value;
if (yes == true)
//alert("true");
document.mainForm.yes[].value = checked;
else
//alert("false");
document.mainForm.yes[].value = checked;
};
};
But I am not getting any alert (Neither Yes, Nor No).
So, is yes[] (Square brackets) in second line is incorrect? Or my if/else condition is wrong in JS?
P.S. All the questions here at SO or on Google deal with only one case/pair.
P.S. If required, I can change yes[] to yes1, yes2, yes3 etc and corresponding sp1, sp2, sp3 where 1,2,3 is $i of For loop, but then how will I capture/refer to it in JS?
_UPDATE:_
The flow/conditions are(Clarification):
Initially Special checkbox will be disabled and OK checkbox will be unchecked.
Then if user checks Ok, Special gets enabled.
If user want, he can tick Special.
If, later, user changes mind and untick the OK, Special should be unticked as well as disabled again.
I used jQuery here for the sake of simplicity.
$("input[name='yes[]']").change(function() { //When checkbox changes
var checked = $(this).attr("checked");
$(this).next().attr("disabled", !checked); //The next checkbox will enable
});​ // or disable based on the
// checkbox before it
Demo: http://jsfiddle.net/DerekL/Zdf9d/
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/1/
Update
It will uncheck the first checkboxes when the Special checkbox is checked.
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/2/
More Updates
Here's the demo:
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/3/
jQuery: http://jsfiddle.net/DerekL/Zdf9d/4/
Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.
You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:
document.mainForm["yes[]"]
This will not return a single element, it will return an array of elements. Use an index to access a specific element:
document.mainForm["yes[]"][0]
The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:
function spenable() {
var yes = document.mainForm["yes[]"][0].checked;
if (yes) {
alert("true");
} else {
alert("false");
};
}
To access the specific checkbox that was clicked, send the index of the checkbox in the event call:
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK
Use the index in the function:
function spenable(idx) {
var yes = document.mainForm["yes[]"][idx].checked;
var sp = document.mainForm["sp[]"][idx];
sp.disabled = !yes;
}
If you are open to using jQuery:
$('input[type="checkbox"]').click(function(){
var obj = $(this);
obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});
This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.
Working Example: http://jsfiddle.net/6YTqC/

Headaches with radios in Jquery

I have 2 radios:
<input id="a_15_0" type="radio" value="abc" name="a_15"/>
<input id="a_15_1" type="radio" value="xyz" name="a_15"/>
Both are unselected. I have only the name of the radio, i.e a_15, but not the IDs.
1) How can I get the value of the selected option of this radio? E.g if the user clicked 'xyz', how can I get it? Right now I'm using:
var val=$('[name="a_15"]').val();
Which always gives abc even when xyz is selected.
2) How can I get xyz to be selected through javascript, without knowing the ID of the radio which says xyz? Doing:
$('[name="a_15"]').val('xyz');
Changes the value of both radios to xyz rather than selecting the one whose value had been xyz.
Do I need to use document.myForm.a_15.value? Would that work consistently?
1)
try
var val = $('input[name=a_15]:checked').val();
jQuery docs on checked pseudo-class
2) the only solution I found is
$('input[name=a_15][value=xyz]').get(0).checked=true
Have you tried using the val() in conjunction with the :checked selector?
$('[name="a_15"]:checked').val();
As for setting the selection based on the value, you may have to perform a multiple attribute tests?
$('[name="a_15"][value="xyz"]').get(0).checked = true;
There are many ways of selectors in jQuery; id, class, etc..I believe this will do the job, not tested:
var val= $("input[name=a_15]:checked").val();
if you know the name of the form then this will definitely do it
var val= jQuery('#radio_form input:radio:checked').val();
you have the correct code here:
to run
to edit
the correct form is:
$("input[name='a_15']:checked").val();
as you can test using the links above

Categories

Resources