jQuery :checked not working with initial (HTML attribute) radio input - javascript

Please inspect the following Console output, note that the 1st input has checked attribute and is selected:
You can see I have 2 radio inputs, 1 is checked, however neither selector nor prop nor is works for it. The code works correctly if I manually click on one of the radio. Here is my HTML:
<div class="col-sm-6">
Type:
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default active">
<input type="radio" name="generator-type" id="opt-type-passphrase" value="0" autocomplete="off" checked>
Passphrase
</label>
<label class="btn btn-default">
<input type="radio" name="generator-type" id="opt-type-password" value="1" autocomplete="off">
Password
</label>
</div>
</div>
Why is the code not working when the page loads when I haven't clicked any radio? Is there a way to fix it?
EDIT: Found the problem, I have this code in the page load:
$("input[name='generator-type'][value=" + this.Options.Type + "]").prop("checked", "");
The correct solution is using:
.prop("checked", true)
But can anyone please explain how it work? Why is there the checked attribute, but prop function is still false?

Try .is(':checked') instead of .is('checked'). Please check this Fiddle.

You need to check like this
$( ... ).is(':checked')
Why? Because the jquery is method accepts a css selector which it uses to filter the currently matched elements.
Thus temp.is('checked') will only be true if the temp elements have the checked tag. In your case they have the input tag so do not match.
Using :checked matches on the css pseudo selector for whether the current element is checked or not. This is what you want.
Knowing this, you could also use $( ... ).is('[checked]'), which will return true if the matched elements have the checked attribute. That's probably what you were trying to do originally. Though, the conventional way is to use :checked.

You're missing a colon in the is-checked code:
temp.is(":checked")
instead of
temp.is("checked")

Related

jQuery returns UNDEFINED or ON as Input Value

I have problem to get input value with jQuery.
Final Edit:
problem solved.
damnnn, i missed
=
for value attribute in input tag,
i struggled a lot with this silly mistake.. laughing emoji..
If i use
$("input[name=xxx]:checked").attr("value");
it returns UNDEFINED
If i use
$("input[name=xxx]:checked").val();
it returns ON(an error, not value.)
Edit:
Input created dynamically with js.
<div id="ab">
<input type="checkbox" name="aaa" value="apple">apple
<input type="checkbox" name="aaa" value="banana">banana
<input type="checkbox" name="aaa" value="grapes">grapes
<input type="checkbox" name="aaa" value="pista">pista
<input type="checkbox" name="aaa" value="badam">badam
<input type="checkbox" name="aaa" value="fruit">fruit
</div>
<div id="abcd"></div>
and after checked some of above, then below one,
var data="";
$('input[name=aaa]:checked').each(function() {
data += $(this).attr('value')+": <label class=\"badge badge-secondary mx-1\"><input type=\"radio\" name=\"xxx\" value\""+$(this).attr('value')+"\">A</label><label class=\"badge badge-secondary rounded-circle mx-1\"><input type=\"radio\" name=\"yyy\" value\""+$(this).attr('value')+"\">B</label>";
});
$('#abcd').html(data);
that one created content well correctly, but finally have problem in getting value of that checked radios,(user can select only two among different items).
some jQuery functions doesn't work for dynamically generated content like,
$("#xxx").click(function(){});
that one doesn't work for content created with js after page load,
$("body").on("click", "#xxx", function(){});
this one works for content created with js after page load,
maybe, similarly, there will be another one to get Input values that are created with js after page load.
If a value isn't specified in the element, the default values of a checkbox are "on" and "off". If the checkbox is supposed to have some specific meaning, you can specify that in the value attribute.
For example, let's say we want the user to check the box if they're over 18 years old. We could do something like:
<input id="checkbox" type="checkbox" value="over 18"/>
Then, when you query its value, $("#checkbox").attr("value"), you'll get "over 18".
If you don't want to specify a value that way, and you are using a label for the text next to the checkbox, you could do something like this:
HTML:
<input type="checkbox" id="checkbox" name="checkbox"/>
<label for="checkbox">Over 18?</label>
JS:
let text = $("label[for=checkbox]").text();
That will give you the label text, which is "Over 18?".
Update
For OPs updated case, you might be able to use something like $(staticAncestors).on(eventName, dynamicChild, function() {}); via jQuery.
Example:
First, assign a class name to the class attribute when the checkboxes are created dynamically (e.g., class = "your_class_name").
Then, do something like:
$(document).on('click', '.your_class_name', function() {
console.log($(this).is(':checked'));
// Do something with selected element
});
See https://api.jquery.com/on/#on-events-selector-data-handler, especially the section on Direct and delegated event handlers
Hope this helps.
Use
$("input[name=xxx]:checked")[0].value
Because it may return array of inputs so you must select first from array

Having trouble using jQuery change() with checkboxes

I'm trying to add/remove a class and attribute to a few labels and input boxes depending on whether or not a checkbox is checked or not.
By default my check box is set up to be not checked. Here is my existing code...
$("#built").change(function()
{
$("label.readonly").removeClass("readonly");
$("input.readonly").removeAttr("readonly");
}).change();
For some reason the event isn't firing. What am I doing wrong? Thanks!
Update:
Here is my html code
<label for="address1" class="readonly">Address Line 1</label>
<input type="text" name="address1" class="readonly" readonly="readonly" value="" />
Also, upon the check box being unchecked I would like the labels and inputs to revert back to its original state of having the readonly class and attribute respectively.
Remove the .change() after the function and add a ;.
eg:
$("#built").change(function(){
$("label.readonly").removeClass("readonly");
$("input.readonly").removeAttr("readonly");
});
There is no reason your code won't work, maybe just indentation or something like this.
Here is a jsfiddle with your function and it's working.
I just removed the line break like this:
$("#build").change(function() {
$("label.readonly").removeClass("readonly");
$("input.readonly").removeAttr("readonly");
});
Maybe there are other javascript problems somewhere else in the page?

Bootstrap checkbox/radio buttons do not change <input> value

The JavaScript page for Bootstrap shows some nice use of buttons to style checkboxes and radio fields. For example, for a checkbox, I might write
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="checkbox"> Option 1
</label>
</div>
However, the library doesn't actually change the value of the underlying <input> field -- it just changes whether the <label> field has class active. I would have expected it to change the checked attribute on the checkbox. Apparently I don't just have it misconfigured -- this is the way the examples on the Bootstrap site work.
Is this actually expected behavior? If so, it seems fairly useless, as people are going to want to use the checkbox field. If not, how do I properly configure Bootstrap checkboxes/radio buttons?
The checked attribute on the input isn't modified because that isn't what changes when a checkbox input is checked -- the checked DOM property is what changes (true or false), and Bootstrap handles this properly (you can inspect the element in Firebug and see the DOM property change when you toggle them). The checked attribute is only used to determine default value when the DOM is initially rendered.
If you ever happen to be doing any js/jQuery with checkboxes/radios, remember this! If you need to programatically check a checkbox or radio button, $('input').attr('checked', 'checked'); will not get the job done. $('input').prop('checked', true); is what you need.
This isn't special behavior for Bootstrap buttons, this is how all checkbox/radios work.
Edit: Firebug screenshot
Edit 2: Added text from the comments, as it seems to be helpful.
It looks like you are missing a call to "activate" the btn-group (documentation). Here is a demo of this working:
<form id='testForm'>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="checkbox" name='Option' value='1' />Option 1</label>
</div>
</form>
<button class='btn' id='actionSubmit'>Submit</button>
<script>
$('#actionSubmit').on('click', function (e) {
e.preventDefault();
alert($('#testForm').serialize());
});
$('.btn-group').button();
</script>
I am doing it like this for MVC.NET in case anyone needs it:
#{
var removeSelected = Model.Remove == true ? "active" : "";
var buttonText = Model.Remove == true ? "Add" : "Remove";
}
#Html.HiddenFor(model => model.Remove)
<div class="editor-field">
<div class="btn-group" data-toggle="buttons-checkbox">
<button type="button" id="RemoveButton" class="btn btn-primary #removeSelected" onclick="toggle();">#buttonText</button>
</div
</div>
function toggle() {
var value = $("#Remove").val();
if (value == "False") {
$("#Remove").val("True");
$("#RemoveButton").text("Add");
}
else {
$("#Remove").val("False");
$("#RemoveButton").text("Remove");
}
}
And finally don't forget to add the bootstrap js refence.

.checked=true not working with jquery $ function

i want to select a checkbox when a button is clicked.
<form action="" method="post" id="form2">
<input type="checkbox" id="checkone" value="one" name="one" />
<input type="button" value="Click me" id="buttonone"/>
</form>
when i tried the following, the checkbox was not getting selected
$('#buttonone').click(function() {
$('#checkone').checked=true;
});
then i tried:
$('#buttonone').click(function() {
document.getElementById('checkone').checked=true;
});
this time the checkbox got selected. why isn't it getting selected with the jquery $ function?
Try
$('#checkone').attr('checked', true);
or
$('#checkone').get(0).checked = true;
or
$('#checkone')[0].checked = true; // identical to second example
The reason your first code didn't work is because you were trying to set the checked property on a jQuery object which will have no visible effect as it only works on the native DOM object.
By calling get(0) or accessing the first item [0], we retrieve the native DOM element and can use it normally as in your second example. Alternatively, set the checked attribute using jQuery's attr function which should work too.
You need to use .attr() for the jQuery object, like this:
$('#buttonone').click(function() {
$('#checkone').attr('checked', true);
});
But it's better to do it the DOM way, like this:
$('#buttonone').click(function() {
$('#checkone')[0].checked = true; //get the DOM element, .checked is on that
});
Or, completely without jQuery:
document.getElementById('buttonone').onclick = function() {
document.getElementById('checkone').checked = true;
};
None of these answers worked for me because I incorrectly had multiple radios with the same name attributes:
<div id="group-one">
<input type="radio" name="groups" value="1" checked="checked" />
<input type="radio" name="groups" value="2" />
</div>
<div id="group-two">
<input type="radio" name="groups" value="1" checked="checked" />
<input type="radio" name="groups" value="2" />
</div>
Javascript won't recognize the checked attribute (obviously). This was a result of using include to add a similar section of HTML multiple times. Obviously, clicking on a radio button will uncheck the radio toggles with the same name.
Here's a jsfiddle to show that two radio elements can have the attribute checked but only the last one is actually checked:
http://jsfiddle.net/bozdoz/5ecq8/
Again, pretty obvious, but possibly something to watch out for: remove id and name attributes from files that you intend to include into other files multiple times.
Try
$('#checkone').attr('checked', true);
You don't have direct access to DOM object properties because jQuery operates on collections ($(selector) is an array). That's why you have functions defined to manipulate the contents of the returned elements.
try
$('#checkone').attr('checked', true);
cleary googling for "jquery check a checkbox" was the way to go
Or you could simply do
$('#buttonone').click(function() {
$('#checkone')[0].checked=true;
});
It is because ".checked" is not part of jQuery and you are trying to use it on a jQuery object. If you index a jQuery object at [0] you get the raw Javascript object which ".checked" exists on.
More here: http://phrappe.com/javascript/convert-a-jquery-object-to-raw-dom-object/
try this
$('#buttonone').click(function() {
$('#checkone').prop('checked', true);
});

JQuery - Set Attribute value

I have following HTML with two elements having the same name
<input type="hidden" name= "chk0" value="">
<input type="checkbox" name="chk0" value="true" disabled>
Through JQuery, I want to set the enable the checkbox. So, I am using something like this:
$('#chk0').attr("disabled",false);
But this doesn't work. I assume JQuery is getting confused with two elements having the same identical name. Unfortunatel, I cannot avoid using two different names because, when the form is posted, I want all the checkboxes to get posted (not just the ones that are checked). Hence I have to use hidden element with the same name.. So, back to the question, how can I enable the checkbox through JQuery in the above scenario? Is there a "type" parameter for attr which distingues hidden from checkbox?
Thanks
Some things before the actual code..
the hash (#) you use as the selector is for IDs and not for names of elements.
also the disabled attribute is not a true false scenario .. if it has disabled attribute it means that it is true .. you need to remove the attribute and not set it to false.
Also there are the form selectors that identify specific types of items in a form ..
so the code would be
$("input:checkbox[name='chk0']").removeAttr('disabled');
Bringing the answer up-to-date
You should use the .prop() method (added since v1.6)
$("input:checkbox[name='chk0']").prop('disabled', false); // to enable the checkbox
and
$("input:checkbox[name='chk0']").prop('disabled', true); // to disable the checkbox
Seriously, just don't use jQuery for this. disabled is a boolean property of form elements that works perfectly in every major browser since 1997, and there is no possible way it could be simpler or more intuitive to change whether or not a form element is disabled.
The simplest way of getting a reference to the checkbox would be to give it an id. Here's my suggested HTML:
<input type="hidden" name="chk0" value="">
<input type="checkbox" name="chk0" id="chk0_checkbox" value="true" disabled>
And the line of JavaScript to make the check box enabled:
document.getElementById("chk0_checkbox").disabled = false;
If you prefer, you can instead use jQuery to get hold of the checkbox:
$("#chk0_checkbox")[0].disabled = false;
"True" and "False" do not work, to disable, set to value disabled.
$('.someElement').attr('disabled', 'disabled');
To enable, remove.
$('.someElement').removeAttr('disabled');
Also, don't worry about multiple items being selected, jQuery will operate on all of them that match. If you need just one you can use many things :first, :last, nth, etc.
You are using name and not id as other mention -- remember, if you use id valid xhtml requires the ids be unique.
$("#chk0") is refering to an element with the id chk0. You might try adding id's to the elements. Ids are unique even though the names are the same so that in jQuery you can access a single element by it's id.
Use an ID to uniquely identify the checkbox. Your current example is trying to select the checkbox with an id of '#chk0':
<input type="checkbox" id="chk0" name="chk0" value="true" disabled>
$('#chk0').attr("disabled", "disabled");
You'll also need to remove the attribute for disabled to enable the checkbox. Something like:
$('#chk0').removeAttr("disabled");
See the docs for removeAttr
The value XHTML for disabling/enabling an input element is as follows:
<input type="checkbox" id="chk0" name="chk0" value="true" disabled="disabled" />
<input type="checkbox" id="chk0" name="chk0" value="true" />
Note that it's the absence of the disabled attribute that makes the input element enabled.
You can add different classes to select, or select by type like this:
$('input[type="checkbox"]').removeAttr("disabled");

Categories

Resources