I am using this simple script provided from a friendly lad in #javascript to uncheck radio buttons:
$('.feed').on('click', 'input[type=radio]', function() {
var myParent = $(this).closest('div');
var ref = $(this);
if( myParent.data('val') == $(this).val() ){
var ref = myParent.find('.none input');
ref.prop('checked',true);
}
myParent.data('val',ref.val() )
});
Everything works fine, see this fiddle, but when I add the attribute 'checked' to one radio button you will actually have to click twice before you can uncheck it, see this fiddle. This got me thinking, is setting 'checked' as an attribute actually equal to checking the radio button by hand? Or why am I failing this?
This has nothing to do with adding an an attribute vs clicking, it's the additional code, specifically this line:
if (myParent.data('val') == $(this).val() ){
which says, if you clicked this before, then turn it off.
However, you're not telling the code that you've already (virtually) "clicked" it.
You can do this by adding the initial value to the 'myParent', one way is to add it to the html:
<div data-val='1'>
Updated fiddle: https://jsfiddle.net/8jh2k8u8/4/
An alternative is to initialise the parent via code by finding the radio that is selected (:checked):
var startup = $(".feed input[type=radio]:checked").first();
if (startup.length) {
startup.closest("div").data("val", startup.val())
}
Updated fiddle: https://jsfiddle.net/8jh2k8u8/5/
Related
Got this script that gets the value of a checked radio button and prints it out in another tag. It works perfectly when you click a radio button, but I've realized that I need to have some of the radio buttons checked by default.
How do I change this script so that it will output the values of already checked radio buttons on page load as well?
$("input[type='radio']").click(function(){
var radioValue = $(this).val();
if(radioValue){
$(this).closest('section').find('h2 .value').text(radioValue);
}
});
Fiddle: https://jsfiddle.net/tactics/bykf31e6/4/
You can use the :checked selector to find all the checked :radio elements on load, and the loop over them to set the value of the related .value element. Try this:
$(":radio:checked").each(function() {
$(this).closest('section').find('h2 .value').text(this.value);
});
Example fiddle
Note that you should use the change event for binding to radio and checkbox elements to cater for those who navigate websites using their keyboards. Also, if you remove the check that the radio element has a value (which is redundant as they should always have a value) you can simplify the code:
$("input[type='radio']").change(setText); // when user selects
$(":radio:checked").each(setText); // onload
function setText() {
$(this).closest('section').find('h2 .value').text(this.value);
}
Example fiddle
I realize similar question had earlier been answered on stack overflow a few times. I checked all the questions and none were similar to mine.
I have a html form that has some radio buttons. In my validation I want to check if atleast one of the radio buttons are checked.
My approach so far:
All radio buttons have same class
All radio buttons have same name
I need to
check if atleast one of the radio button is selecetd
read the value of selected button.
My Javascript so far
function supportFormValidation(){
var isChecked = $('.radioButton').attr('checked')?true:false;
alert(isChecked);
return false;}
This always returns false. But when I try to read vale by individual IDs of each radio button it returns true. Is there any way I can check if a radio button is checked by using the class name.
JSFiddle: http://jsfiddle.net/evj9nch3/
Just use :checked.
var isChecked = !!($('.radioButton:checked').length);
In order to access the checked property you need to use the prop function (after 1.6 anyways). Because the value is either true or false, it's considered a property of the element not an attribute.
Nits answer is a better way of doing it, but look below for the reason why your implementation isn't working.
Take a look at this post for more info
Here is a link to the fiddle
function supportFormValidation() {
var isChecked = $('.radioButton').prop('checked') ? true : false;
alert(isChecked);
return false;
};
supportFormValidation();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' class='radioButton' checked='true' />
You can use this. I checked this is working
$(".ClassName").prop("checked", true)
I have a a reasonably quick problem to solve (I think). I have a form online and it validates the required content for the user's data, but has no validation on the first part of the form.
I've been asked however if I can make a radio button REQUIRED depending on whether an input field has been filled in.
The form can be found here:
http://www.elcorteingles.pt/reservas/livros_escolares/form.asp
So if the person start's filling in the input fields on the first line, that the radio buttons in the group become REQUIRED (for either the CDROM ou CADERNO but not both)
You can handle the focusout and blur events for the input:
$(function () {
// Handle every input type text.
// To select specific inputs, give them a common class and change the
// selector accordingly.
$("input[type=text]").on("focusout blur", function () {
// Check for inputs with class radio_btns which are in
// the parent element (li).
// Set their required property.
$(this).parent().find("input.radio_btns")
.prop("required", $(this).val().trim().length > 0);
});
});
Demo
jQuery reference (Tree Traversal)
jQuery reference (.prop())
jQuery reference (.focusout())
jQuery reference (.blur())
This will work. You can include the following JQuery code in the script tag, and also the JQuery cdn link in the head tag.
$(document).ready(function(){
$('#01titulo').focusout(function(){
if ($(this).val() !== "") {
$('[name="01caderno"]').prop('required', true);
} else {
$('[name="01caderno"]').prop('required', false);
}
alert($('[name="01caderno"]').attr('required'));
});
});
Try using the following js code its working:
$(document).ready(function(){
$(".titulo_books").each(function(){
$(this).focus(function(){
var radioChecked=0;
var currElemId = parseInt($(this).attr('id'));
var radioSelecterId = (currElemId>9) ? currElemId : "0"+currElemId;
$("input:radio[name="+radioSelecterId+"caderno]").each(function(){
if(radioChecked==0)
{
radioChecked==1;
$(this).attr("checked","checked");
}
});
});
});
});
I have checked it by executing this from console on your site and it seems to work fine. You can alter this in the way you want. I have checked one of the four available radio button. User can change the input value if required. Or you can also change the default radio button selected through my code.
Hi guys I am having a problem with Events. I have a checkbox list and I have a main check box that checks all boxes. When I clickEvent some of my checkbox list items it should add data-id attr to the "selected obj". So in my case when I press main check box to check all others every thing is ok (it simply clicks all other elements). but when i do that it empties my array. I mean if i uncheck it will be the way it supposed to be but checked (when uncheck it fills when i check it empties).
......
var selected = {};
var reload = function(){
selected = {};
$('.checkbox_all').unbind('click');
$('.table_checkbox').unbind('click');
$('.checkbox_all').bind('click', checkAll);
$('.table_checkbox').bind('click', checkMe);
}
var checkMe = function(e){
var checkbox = $(e.target);
var id = checkbox.attr('data-id');
//console.log(id);
if(checkbox.attr('checked')){
selected[id] = id;
}else{
if(selected[id]) delete selected[id];
}
console.log(selected);
}
var checkAll = function(e){
if($(e.target).attr('checked')){
$('.table_checkbox').each(function(){
if($(this).attr('checked') === false){
$(this).click();
}
});
}else{
$('.table_checkbox').each(function(){
if($(this).attr('checked') === true){
$(this).click();
}
});
}
//console.log(selected);
}
.......
HTML:
<tr><th class="table-header-check"><input type="checkbox" class="checkbox_all"/></th></tr>
<tr class=""><td><input type="checkbox" data-id="5" class="table_checkbox"></td></tr>
<tr class="alternate-row"><td><input type="checkbox" data-id="6" class="table_checkbox"</td></tr>
<tr class="alternate-row"><td><input type="checkbox" data-id="8"
....ETC\
My problem is that when i click .checkbox_all it should click on all .table_checkbox(that r cheched or uncheched)... it just clicks all checkboxes like a main checkbox... it works fine, but i have an event all other checkboxes if i click em i add some data to array when i unclick em it removes data from array.... so when im clicking checkboxes sepperatly they add /remove data to array properly... but when im clicking on main checkbox... it clicks on right checkboxes but the data array is empty when all checked and full when all unchecked... it must be the opposite way
Could you instead go for a cleaner solution, and generate selected on the fly? See here for an example (and a JSFiddle for everyone else): http://jsfiddle.net/turiyag/3AZ9C/
function selected() {
var ret = {};
$.each($(".table_checkbox"),function(index,checkbox) {
if($(checkbox).prop("checked")) {
ret[$(checkbox).prop("id")] = true;
}
});
return ret;
}
** EDIT: **
If you're looking to have an array that is added to and removed from, then this JSFiddle (http://jsfiddle.net/turiyag/pubGb/) will do the trick. Note that I use prop() instead of attr(), in most cases, especially this one, you should use prop() to get the value you want.
To work with your own code you need to understand the order of events. When you programmatically call click() on the checkbox the javascript (checkMe() for children) executes before the state of each child checkbox is changed (e.g., adding attribute 'checked'). It is because of this reason that the checkMe() function was adding and removing ids in the selected array in the reverse order. You can confirm this by adding the following debug line in the checkMe function:
console.log('Checked state of checkbox id:' + id + ' is: ' + checkbox.prop('checked'));
Case1: Clicking checkAll when it is Unchecked; it calls checkMe() for each child checkbox but finds the 'checked' attribute as undefined. So it executes the delete code. After executing checkMe the 'checked' attribute is added on the checkbox.
Case2: Clicking checkAll when it is Checked; the checkMe() function finds the 'checked' attribute previously added and fills the array. Later an event is probably fired to remove the 'checked' attribute.
I changed the following lines to quickly test this and seems to be working:
Bind checkMe on change event instead of click in reload function:
$('.table_checkbox').bind('change', checkMe);
Change the condition for unchecked children in checkAll function when the .checkbox_all is checked:
if($(this).prop('checked') === false) {/*call child click*/}
//Use prop instead of attr because it takes care of 'undefined' cases as well. If you want to keep using attr because you're on an older version of jquery then add something like:
typeof $(this).attr('checked') == 'undefined'
and also the condition when .checkbox_all is unchecked:
if($(this).prop('checked') === true) {/*call child click*/}
Hope this helps. Here's a jsbin to play with..
I've been trying to figure out how to add the attribute "checked" to a checkbox on click. The reason I want to do this is so if I check off a checkbox; I can have my local storage save that as the html so when the page refreshes it notices the checkbox is checked. As of right now if I check it off, it fades the parent, but if I save and reload it stays faded but the checkbox is unchecked.
I've tried doing $(this).attr('checked'); but it does not seem to want to add checked.
EDIT:
After reading comments it seems i wasn't being clear.
My default input tag is:
<input type="checkbox" class="done">
I need it top be so when I click the checkbox, it adds "checked" to the end of that. Ex:
<input type="checkbox" class="done" checked>
I need it to do this so when I save the html to local storage, when it loads, it renders the checkbox as checked.
$(".done").live("click", function(){
if($(this).parent().find('.editor').is(':visible') ) {
var editvar = $(this).parent().find('input[name="tester"]').val();
$(this).parent().find('.editor').fadeOut('slow');
$(this).parent().find('.content').text(editvar);
$(this).parent().find('.content').fadeIn('slow');
}
if ($(this).is(':checked')) {
$(this).parent().fadeTo('slow', 0.5);
$(this).attr('checked'); //This line
}else{
$(this).parent().fadeTo('slow', 1);
$(this).removeAttr('checked');
}
});
$( this ).attr( 'checked', 'checked' )
just attr( 'checked' ) will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />
Edit:
Based on comments, a more appropriate manipulation would be:
$( this ).attr( 'checked', true )
And a straight javascript method, more appropriate and efficient:
this.checked = true;
Thanks #Andy E for that.
It seems this is one of the rare occasions on which use of an attribute is actually appropriate. jQuery's attr() method will not help you because in most cases (including this) it actually sets a property, not an attribute, making the choice of its name look somewhat foolish. [UPDATE: Since jQuery 1.6.1, the situation has changed slightly]
IE has some problems with the DOM setAttribute method but in this case it should be fine:
this.setAttribute("checked", "checked");
In IE, this will always actually make the checkbox checked. In other browsers, if the user has already checked and unchecked the checkbox, setting the attribute will have no visible effect. Therefore, if you want to guarantee the checkbox is checked as well as having the checked attribute, you need to set the checked property as well:
this.setAttribute("checked", "checked");
this.checked = true;
To uncheck the checkbox and remove the attribute, do the following:
this.setAttribute("checked", ""); // For IE
this.removeAttribute("checked"); // For other browsers
this.checked = false;
If .attr() isn't working for you (especially when checking and unchecking boxes in succession), use .prop() instead of .attr().
A simple answer is to add checked attributes within a checkbox:
$('input[id='+$(this).attr("id")+']').attr("checked", "checked");
use this code
var sid = $(this);
sid.attr('checked','checked');