jQuery Ajax checkbox value - javascript

I have checkboxes on my page for which I would like to send their state back to the database via ajax. I know how to use jquery with ajax and how to work with SELECT and OPTIONS, but I don't know to do the same things with several checkboxes and how to get the value from them.
Everything works when id is attached to one checkbox, but when i attach id to several checkboxes it doen'twork(except first check box)
Any ideas?
my code looks like this->
<form>
<div class="checkbox" >
<label><input type="checkbox" value="1" id="item">что то</label>
<label><input type="checkbox" value="1" id="item">Шорты</label>
<label><input type="checkbox" value="3" id="item">Классическая</label>
</div>
</form>
<script>
$(document).ready(function () {
$('#item').on('click',function(){
var name = $('#item').val();
$.post('load.php', {name:name}, function(data){
$('#name-data').html(data);
});
});
});
</script>

Use a class. Ids are expected to be unique on a single page. Classes are used to group elements together.
<tag id="a">A</tag><tag id="a">B</tag> $('#a')
becomes
<tag class="a">A</tag><tag class="a">B</tag> $('.a')

Id should be unique you can use class instead of Id.

Related

Get group radio button selected value via jquery

How can I get the selected radio button value via jQuery? I tried:
var selectedPlan = $("input[name=Plan[packageId]]:checked'").val();
alert(selectedPlan);
bBt didn't work.
<td style="vertical-align: top;">
<input type="radio" value="1" name="Plan[packageId]">
<lable>3 Games</lable><br>
<input type="radio" value="2" name="Plan[packageId]">
<lable>5 Games</lable><br>
<input type="radio" value="3" name="Plan[packageId]">
<lable>10 Games</lable><br>
</td>
here is the fiddle http://jsfiddle.net/vk3z45an/
You need to escape the CSS meta characters or wrap them in quote for preventing the selector from breaking:
var selectedPlan = $("input[name='Plan[packageId]']:checked").val();
Working Demo
You need to escape the [] characters in the name attribute of the selector (or wrap them in quotes) and remove the un-matched apostrophe at the end. Try this:
var selectedPlan = $("input[name=Plan\\[packageId\\]]:checked").val();
alert(selectedPlan);
// alternatively:
// var selectedPlan = $("input[name='Plan[packageId]']:checked").val();
Updated fiddle
Note that you're running your code on load of the page and your HTML has no radio selected by default. I added a checked attribute to one of the radios so you can see it working. Also, your original fiddle did not include jQuery so I added that too. Finally, the element is label, not lable.

jQuery else clause not working [duplicate]

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

Check 2 checkboxes with one click on dynamically made list of checkboxes

I have a list of checkboxes that go together. One is for a name the other is for a price. I need to check the one for price and the corresponding name one gets automatically checked.
Here is my code:
<input id="name1" name="name1" value="Option Name 1" type="checkbox">
<input id="price1" name="price1" value="125" type="checkbox">Option Name 1<br>
<input id="name2" name="name2" value="Option Name 2" type="checkbox">
<input id="price2" name="price2" value="150" type="checkbox">Option Name 2<br>
<input id="name3" name="name3" value="Option Name 3" type="checkbox">
<input id="price3" name="price3" value="175" type="checkbox">Option Name 3<br>
How can I do this with javascript? I could do it if it were only one set, but I don't know how I would do this without making a separate function for each one. This list of check boxes is created dynamical with PHP, so there will be more or less depending on the item in the database that is selected.
probably something like this?
Add class name and price for the checkboxes for easy detection. And using event deleagtion since you are dynamically appending the
$(document).on('change','.name, .price', function () { //provide a container selector instead of document.
$(this).next('br').prevAll(':eq(1),:eq(0)').prop('checked', this.checked);
});
Fiddle
if you dont want to add another class to the markup then use startswith selector, and for both way toggle.
$(document).on('change',':checkbox[id^=name],:checkbox[id^=price]', function () { //provide a container selector instead of document.
$(this).nextUntil('br').andSelf().prev().andSelf().prop('checked', this.checked);
});
Fiddle
This just select the next available br
Give the price inputs a class of "price" or something similar, and give the name inputs a class of "name" or somthing similar.
Then bind the events using the class selector, and find the corresponding checkbox using next('.price') or previous('.name')
I'd add a class to each input and it's easy from there:
$(document).ready(function() {
$(".name").change(function(){
if($(this).is(":checked")){
$(this).next().attr("checked","checked");
}else{
$(this).next().removeAttr("checked");
}
})
});
checkout jsfiddle: http://jsfiddle.net/megarameno/BSYvE/
Don't use <br> anymore, instead, wrap them in divs. That way they can be recognized as a DOM group and your JS can be intelligent - no need for a bunch of event handlers!
This example uses jQuery: http://jsfiddle.net/Nu8w9/2/. It checks the whole row either way, which I think is what you want. Interpreting your question literally, it would just be $('.row').on('change input:nth-child(2)', function (e) { $(e.target).closest('.row').find('input:nth-child(1)')[0].checked = e.target.checked; });

Radio Button Control in jquery

I'm new to Web development and jQuery.
I'm trying to build an ASPX page with two RadioButton controls that must perform the following actions:
On page load, one of the two must be selected depending on a flag from an object on the ASPX page. Lets call it customer.Id. If the Id is true, select RadioButton one must be set else select RadioButton 2 must be set.
At any point after page load the user selects a RadioButton, the other must be deselected.
When RadioButton two is clicked, hide a Table named "employee table" and when RadioButton one is clicked, show that Table.
Can anyone please tell me how I can get this functionality in jQuery functions?
Not sure about .NET but in Classic ASP you would write a variable like this <%=customerID%>.
In jQuery, I think you can do something like this:
<input type="radio" id="radio1"> Yes
<input type="radio" id="radio2"> No
<table border="1" id="employeeTable">
<tr><td>This is the table</td></tr>
</table>
... and then some jQuery:
$(document).ready(function() {
var customerID = <%=customerID%> // asp variable
if (customerID != "") {
$('#radio1').prop('checked', 'checked');
} else {
$('#radio2').prop('checked', 'checked');
}
$('#radio1').click(function() {
$('#employeeTable').fadeIn('fast');
})
$('#radio2').click(function() {
$('#employeeTable').fadeOut('fast');
})
})
You can have a look/play here: http://jsfiddle.net/qcLtX/7/
Try changing the customerID value to nothing, like var customerID = "".
Good luck
UPDATE
Where I have used .prop: If you are using jQuery version 1.6 or greater, you should use .prop, otherwise, use .attr.
Radio buttons are grouped by their name attribute, like so (source).
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>
If the radio buttons are grouped, then selecting any one of them automatically delselects all the others in that group.
So the buttons cannot have a distinct name. If you want to distinguish between radio buttons (without referring the their value), you should add an id.
<input type="radio" name="sex" id="m" value="male" />
You can set the selected radio button on page load declaratively in markup, or using jquery.
Declarative version:
<input type="radio" checked="checked" name="sex" value="male" />
jQuery:
$(document).ready(function(){
$("#m").attr("checked", "checked");
});

jQuery/JavaScript - Hide / Show Drop down box pending on Radio Button

I want to make it so that the drop-down is only displayed when the radio button (option 3) is clicked and have it hidden if either 1 or 2 is selected. What would be the best way to complete this? I have a little bit of experience with JavaScript and slim to none with jQuery but it seemed like it might be the way to go.
Thanks for any help,
Dan
Here is the HTML code I have as of now:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" /> Option 1 </label>
<label><input type="radio" name="select" /> Option 2</label>
<label><input type="radio" name="select" /> Option 3</label>
</div>
<div id="list" style="display: none;">
<label>Please Select From the List:
<select>
<option>True</option>
<option>False</option>
</select>
</label>
</div>
$(document).ready(function(){
$("[name=select]").change(function(){ // Whenever the radio buttons change
$("#list").toggle($("[name=select]").index(this)===2); // Only keep the list open when it's the last option (First option = 0, Third option = 2)
});
});
This code in action.
Assuming you are using jquery, as it sounds like it from your question, you could modify your HTML like so:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" id="option1" /> Option 1 </label>
<label><input type="radio" name="select" id="option2" /> Option 2</label>
<label><input type="radio" name="select" id="option3" /> Option 3</label>
</div>
<div id="list">
<label>Please Select From the List:
<select id="mySelect">
<option>True</option>
<option>False</option>
</select>
</label>
</div>​
</p>
Then you could write some jquery like so:
$(document).ready(
function()
{
$("#option1, #option2, #option3").click(
function()
{
if (this.id == "option3")
$("#mySelect").hide();
else
$("#mySelect").show();
});
});​
You can see it working here: http://jsfiddle.net/AVFuY/3/
EDIT: I removed the unneeded class and just used the id's so as to not confuse and add unnecessary code.
Since this is a fairly basic question, I think it'll be instructional to walk you through the jQuery documentation while I answer your question. If you know truly nothing about jQuery, I recommend following this short tutorial first -- it will make things much, much easier for you in the future: jQuery Documentation - Getting Started With jQuery
Your requirement is that something happens (in this case, another element is hidden/shown) when we click the radio buttons. There's two parts to this problem: first, we need to find the radio buttons, then we need to make something happen when we click it.
1. Finding the radio buttons
Take a look at the jQuery Selector documentation here: http://api.jquery.com/category/selectors/
As you can see, there's a specific pseudo-selector for radio buttons, ":radio". We want to select everything inside of the element with ID "buttons", so this is how the selector will look in total:
$("#buttons input:radio");
By the way, it's called a "pseudo-selector" because it filters items we've already selected (in this case, input tags inside of a div with id "button"). Pseudo-selectors always start with a ":".
2. Making something happen when we click them
Consult the jQuery Events reference here: http://api.jquery.com/category/events/
We want the ".click()" event here, clearly. Once we've selected our elements, we can apply a click handler to them like this:
$("#buttons input:radio").click(function() {
// make something happen here
alert("input button clicked: " + $(this).index());
});
Note that this will apply the same click handler to all three of the input buttons, but you can access the specific element that was clicked via the "this" keyword. Wrapping $() around it makes it into a jQuery selection rather than just a Javascript object and allows us to call jQuery functions on it.
3. Hiding and showing the list element conditionally
Let's extend the code above to actually hide and show that other div, depending on which item was clicked. We're going to refer to the jQuery Effects documentation so that we can make hiding and showing it exciting: http://api.jquery.com/category/effects/
The functions we'll be using are ".slideUp()", which hides an element, and ".slideDown()", which shows it. We'll also be using the ".index()" function I used in the previous example to figure out which button was clicked, although I recommend giving the button a unique ID in the future so that your code isn't dependent on the order of the buttons. Here's the final code:
$("#buttons input:radio").click(function() {
// if it was the third button (0-indexed, so the 3rd one is index 2)...
if ($(this).index() == 2) {
// display the element with ID "list"
$("#list").slideDown();
}
else {
// hide the element with ID "list"
$("#list").slideUp();
}
});
Sorry for the length of this answer, but hopefully it was more conducive to your understanding of jQuery than "copy and paste this 3-line super-compact solution".
<label><input type="radio" name="select" onclick="document.getElementById('list').style.display=this.checked?'':'none'" /> Option 3</label>
Without changing your markup:
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
if (myindex == 2)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});
EDIT: Another option: just show it on the last button in the list.
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
var lastone = $("#buttons input:radio[name=select]:last").index("#buttons input:radio[name=select]");
if (myindex == lastone)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});

Categories