jquery index() method problem selecting by attribute value - javascript

Could someone please take a look at this?
You'll see the first alert prints -1 whereas I was expecting 1. Anyone know why?
Basic code from the fiddle:
<input type="checkbox" value="0" />0
<input type="checkbox" value="1" />1
<input type="checkbox" value="2" />2
<input type="checkbox" value="3" />3
alert($(':checkbox').index("input[value='1']"));
alert($(':checkbox').index("input[value='0']"));

You have the selectors reversed:
Example: http://jsfiddle.net/RaV35/
// element---v collection----------v
alert($("input[value='0']").index(":checkbox"));
alert($("input[value='1']").index(":checkbox"));
When passing the index()[docs] method a selector, the individual element for which you want the index is the element against which .index() is invoked.
The selector you pass to .index() represents the collection against which the element in the original jQuery object is tested.
When the original jQuery object (on the left) also contains a collection, only the first one is tested for its index against the selector on the right. That's why the one with value="0" was working.
// v--- only the first is tested (and it has value="0")...
$(':checkbox').index("input[value='0']")
// ----------------------^ ...and it is at index 0 of this "collection"

alert($(':checkbox[value='1']').index());
alert($(':checkbox[value='0']').index());

You need to pass it a jQuery object: http://jsfiddle.net/ybKzJ/1/
alert($(':checkbox').index($("input[value='1']")));
alert($(':checkbox').index("input[value='0']"));
Edit:
No that doesn't seem right as the second one is working just fine.
...curious...

I'm not sure I understand why you have to use index() at all. Why not just put it all in the selector:
$('input:checkbox[value="2"]');
You can see it work in this fiddle: http://jsfiddle.net/jfriend00/Xa6hA/
If you did want to do it in multiple stages, it would be more logical to me to do it like this:
$('input:checkbox').filter('[value="3"]');
This gets all the checkboxes, then filters that list down to just the ones with value="3" which seems a lot more intuitive than the way index() appears to work.

Related

jQuery .filter() is not working

I was stuck with .filter() in my code; it was just not working. Although I have found other solution but I still don't know why the filter won't work (and where the filter should work). I searched a lot but didn't really find anything convincing.
Here's what it is:
<form id= "qform">
<input type="radio" name="choice" value="1"/> 1 <br />
<input type="radio" name="choice" value="2"/> 2 <br />
</form>
Method 1
element = $('#qform input[type=radio]');
element = $('#qform :radio');
Method 2
element = $('#qform').find('input[type=radio]')
element = $('#qform').find(':radio')
Method 3
element = $('#qform').filter('input[type=radio]');
element = $('#qform').filter(':radio');
Can anyone explain why 1) & 2) work fine but 3) doesn't?
Although jQuery docs says 3) should work fine too:
http://learn.jquery.com/using-jquery-core/selecting-elements/
What am I missing here?
Cheers!
3rd one doesn't work because it already dont have input type in the selection.
if you Provide input in selection than you can filter the type of those like below
element = $('#qform input').filter('[type=radio]');
element = $('#qform input').filter(':radio');
Reference for filter

Javascript does not recognize HTML arrays

How to pass this kind of HTML input to JavaScript so that it recognizes these array values?
<input type="checkbox" id="collection[]" value="0">
<input type="checkbox" id="collection[]" value="1">
<input type="checkbox" id="collection[]" value="2">]
The only idea I have (never played with js this way, tbh) is to reach it through:
$("#collection").val();
But I got undefined error. I have no other idea how to make javascript recognize that variable collection is an array and has to passed as such.
Thanks in advance!
Remember, IDs need to be unique within your document. So set by 'name' not by id.
You can use
$('#someid').is(":checked");
for individually checking each checkbox, or loop through them with a jQuery selector
To loop through them set
<input type="checkbox" name="checkboxes" value="0">
<input type="checkbox" name="checkboxes" value="1">
<input type="checkbox" name="checkboxes" value="2">
Then with jQuery,
$('input[name=checkboxes]:checked').each(function(i, e) {
e.val(); //The value of the checkbox that is selected
});
You cannot have Duplicate Ids. Though duplicate IDs will give you desired output in this case, it is invalid to use them for multiple elements.
<input type="checkbox" name="collection[]" value="0">
<input type="checkbox" name="collection[]" value="1">
<input type="checkbox" name="collection[]" value="2">
There are many ways you can access array based elements.
jQuery .map(): Alternative is .each()
Demo
$("[name='collection[]']").map(function(){return $(this).val();}).get()
Working Demo for checking checked inputs.
To get the checked checkbox,
$('input').change(function () {
console.log($("[name='collection[]']:checked").map(function () {
return $(this).val();
}).get());
});
$("#collection")
It mean's ,"Find me an element which id's equal collection on page" , of course it can't find anything. You can use .each function and you can use checkboxes attributes. For example ;
var myCheckBoxArray = []
$("input[type='checkbox']").each(function(i,elm){
myCheckBoxArray.push(elm);
});

how to make the condition in jquery with the best way?

<body>
<input class="forminput" type="checkbox" value="test one" checked="checked" name="VD1">
<br>
<input class="forminput" type="checkbox" value="test two" checked="checked" name="VD2">
<br>
<input class="forminput" type="checkbox" value="test three" checked="checked" name="VD3">
<br>
<input class="forminput" type="checkbox" value="test four" checked="checked" name="VD4">
<br>
<input class="forminput" type="checkbox" value="test five" checked="checked" name="VD5">
<br>
<input id="checkall" type="checkbox" checked="checked" name="checkall">
<input id="copyvalue" class="button" type="button" value="copy test">
</body>
i want to check out if the user don't check one check box then if he click the copy test, it will alert a box saying" you at least check one box."
$(document).ready(function(){
$("#copyvalue").click(function(){
if (!$(.forminput).checked){
alert('teet');
}
});
but the code doesn't work.
Your syntax is wrong, and you're missing a closing brace and parenthesis.
You can write
$(document).ready(function(){
$("#copyvalue").click(function(){
if ($(".forminput:checked").length === 0){
alert('teet');
}
});
});
Note that the selector is a string.
The :checked selector filters the elements to checked checkboxes.
This code checks whether there are any :checked .forminput elements.
Part of this problem is that you're missing a closing brace and parenthesis, the code should look like this,
$(document).ready(function() {
$("#copyvalue").click(function() {
// ...
});
});
As #Luis has pointed out, another problem is that you didn't quote the selector for the ".forminput" elements. If you quote them properly, it will look like this:
if (!$(".forminput").checked){
alert('teet');
}
But this still won't work, because as #SLaks and #james have pointed out, ".checked" is not a property that you can call on the jQuery object.
I will give credit to #SLaks for coming up with the middle part of the code that checks for checked elements, i.e.
if ($(".forminput:checked").length == 0){
alert('teet');
}
The reason why you use the length property of the jQuery object is because every jQuery object is a collection of the elements matched by the selector (see http://api.jquery.com/Types/#jQuery):
A jQuery object contains a collection
of Document Object Model (DOM)
elements that have been created from
an HTML string or selected from a
document.
So if the selector for checked input boxes returns a length 0 jQuery object, it means none of the input boxes were checked.
The reason why you wouldn't want to use the jQuery attr method instead,
$(document).ready(function(){
$("#copyvalue").click(function(){
if (!$('.forminput').attr("checked")){
alert('teet');
}
});
});
Is because the attr method get's the value of the attribute for the first element in the set of matched elements. So if every input box except for the first one were checked, the code would trigger a false alert.
the selectors need to be quoted,and checked is a selector rather than a method.
$(document).ready(function(){
$("#copyvalue").click(function(){
if ($(".forminput:checked").length==0){
alert('teet');
}
});
});

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

In jQuery, how do I select an element by its name attribute?

I have 3 radio buttons in my web page, like below:
<label for="theme-grey">
<input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>
<label for="theme-pink">
<input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label>
<label for="theme-green">
<input type="radio" id="theme-green" name="theme" value="green" />Green</label>
In jQuery, I want to get the value of the selected radio button when any of these three are clicked. In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?
$("<radiobutton name attribute>").click(function(){});
Please tell me how to solve this problem.
This should do it, all of this is in the documentation, which has a very similar example to this:
$("input[type='radio'][name='theme']").click(function() {
var value = $(this).val();
});
I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.
To determine which radio button is checked, try this:
$('input:radio[name=theme]').click(function() {
var val = $('input:radio[name=theme]:checked').val();
});
The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.
Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal. I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.
$('input:radio[name=theme]:checked').val();
another way
$('input:radio[name=theme]').filter(":checked").val()
This works great for me. For example you have two radio buttons with the same "name", and you just wanted to get the value of the checked one. You may try this one.
$valueOfTheCheckedRadio = $('[name=radioName]:checked').val();
The following code is used to get the selected radio button value by name
jQuery("input:radio[name=theme]:checked").val();
Thanks
Adnan
For anyone who doesn't want to include a library to do something really simple:
document.querySelector('[name="theme"]:checked').value;
jsfiddle
For a performance overview of the current answers check here
I found this question as I was researching an error after I upgraded from 1.7.2 of jQuery to 1.8.2. I'm adding my answer because there has been a change in jQuery 1.8 and higher that changes how this question is answered now.
With jQuery 1.8 they have deprecated the pseudo-selectors like :radio, :checkbox, :text.
To do the above now just replace the :radio with [type=radio].
So your answer now becomes for all versions of jQuery 1.8 and above:
$("input[type=radio][name=theme]").click(function() {
var value = $(this).val();
});
You can read about the change on the 1.8 readme and the ticket specific for this change as well as a understand why on the :radio selector page under the Additional Information section.
If you'd like to know the value of the default selected radio button before a click event, try this:
alert($("input:radio:checked").val());
You can use filter function if you have more than one radio group on the page, as below
$('input[type=radio]').change(function(){
var value = $(this).filter(':checked' ).val();
alert(value);
});
Here is fiddle url
http://jsfiddle.net/h6ye7/67/
<input type="radio" name="ans3" value="help">
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">
<input type="radio" name="ans2" value="test">
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">
<script type="text/javascript">
var ans3 = jq("input[name='ans3']:checked").val()
var ans2 = jq("input[name='ans2']:checked").val()
</script>
If you want a true/false value, use this:
$("input:radio[name=theme]").is(":checked")
Something like this maybe?
$("input:radio[name=theme]").click(function() {
...
});
When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.
I you have more than one group of radio buttons on the same page you can also try this to get the value of radio button:
$("input:radio[type=radio]").click(function() {
var value = $(this).val();
alert(value);
});
Cheers!
can also use a CSS class to define the range of radio buttons and then use the following to determine the value
$('.radio_check:checked').val()
This worked for me..
HTML:
<input type="radio" class="radioClass" name="radioName" value="1" />Test<br/>
<input type="radio" class="radioClass" name="radioName" value="2" />Practice<br/>
<input type="radio" class="radioClass" name="radioName" value="3" />Both<br/>
Jquery:
$(".radioClass").each(function() {
if($(this).is(':checked'))
alert($(this).val());
});
Hope it helps..
$('input:radio[name=theme]').bind(
'click',
function(){
$(this).val();
});
You might notice using class selector to get value of ASP.NET RadioButton controls is always empty and here is the reason.
You create RadioButton control in ASP.NET as below:
<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />
And ASP.NET renders following HTML for your RadioButton
<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>
For ASP.NET we don't want to use RadioButton control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.
The only remaining feasible way to get the value of the RadioButton using jQuery is using css class as mentioned in this answer to a totally unrelated question as following
$('span.radios input:radio').click(function() {
var value = $(this).val();
});

Categories

Resources