JQuery - Set Attribute value - javascript

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");

Related

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

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")

jquery mobile: get selected radiobutton

I'm not sure how can I get the selected radio button in jQuery mobile (I'm using version 1.4.3). The checked attribute doesn't change whenever I click one of the radio buttons. Actually, when I inspect the elements I see that only attribute data-cacheval is changing. Is it safe to use this attribute to get the selected radio button? This is the code I'm using for the radio buttons:
<input type="radio" name="chkViewType" id="chkViewType2" data-mini="true">
<label for="chkViewType2" data-mini="true">List</label>
<input type="radio" name="chkViewType" id="chkViewType1" data-mini="true">
<label for="chkViewType1" data-mini="true">Map</label>
You can use the :checked selector:
e.g.
$("[name='chkViewType']:checked")
Also, you should probably read the Attributes vs. Properties paragraph in the documentation.

getting class attribute of radio button in IE

I need to get the class attribute of checked radio button, with name="radio".
Used the code that's working fine in Firefox, but fails in IE.
val = $('input:radio[name=radio]:checked').attr('class');
How can i accomplish this?
There is no psuedo-class :radio. I think you meant [type=radio].
As comments says, I think you should use type instead of name. But i think you have named your input as radio because you can find this specific input. If you just use type selector you will catch every single selected radio input on page.
<input type="radio" name="radio" class="ey" /> Male<br />
So, if your page have more forms, you should specify a parent or form to avoid conflicts. Set a id for your form and try to find it by form id and radio type like this:
<form id="myForm">
<input type="radio" name="radio" class="ey" /> Male<br />
</form>
val = $("#myform input[type='radio']:checked").attr('class');
I hope it can help you :)

Observing change in radio button selection using Prototype JS

I'm relatively new to Prototype JS (v1.7), and I'm stuck on something. I'm trying to detect when a change in the radio button selection occurs. Here's the code:
Radio buttons:
<input class="amounts" type="radio" name="amount" id="amount-1" value="1" />
<input class="amounts" type="radio" name="amount" id="amount-2" value="2" />
<input class="amounts" type="radio" name="amount" id="amount-3" value="3" />
Javascript:
Here's a stab I took at it, which doesn't work:
Event.observe($$('amounts'), 'change', function(event) {
alert('change detected');
});
When the form loads, no radio buttons are checked. I'd like the Javascript to detect these events:
A radio button is selected when none was previously selected
The radio button selection changes
Any help would be greatly appreciated.
It doesn't work because $$ returns an array of elements and Event needs a single element. Also $$('amounts') doesn't match any elements, there are no <amounts> tags.
A better way is to use a single ancestor element which is easy to identify.
<form id="amounts-form">
<input class="amounts" type="radio" name="amount" id="amount-1" value="1" />
<input class="amounts" type="radio" name="amount" id="amount-2" value="2" />
<input class="amounts" type="radio" name="amount" id="amount-3" value="3" />
</form>
Now there is a unique ID to work with we can use Event.on
$('amounts-form').on('change', '.amounts', function(event) {
alert('change detected');
});
Notice the events are being filtered by '.amounts', the period says to use the class name.
If you're using FireBug for FireFox or Chrome's developer tools then you can test parts of your script directly in the console. It really helps to find if a selector is matching the elements you think it is by typing $$('.amounts')
Alternegro's answer attempts to use an iterator to attach the event handler directly to the "amount" radio elements but doesn't work for a few reasons:
The "$" function doesn't take css selectors as parameters, only ids. Use "$$" instead.
The css "id" attribute selector should include square braces "[]". It's also spelled wrong. "amounts-" should be "amount-" to match the ids in the example. Or just use a class selector instead: ".amounts".
There is no "change" method that can be called on enumerables. Use invoke or some other enumerable method instead.
This one should work:
$$("[id^=amount-]").invoke(
'on',
'change',
function(){alert("hello " + this.id)}
)
(YMMV using "this" in the event handler. I only checked the code in Firefox)
Its more efficient to just give those checkboxes the same class but u can also try
$("id^=amounts-").change(function(){alert("blah blah")})

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

Categories

Resources