简体   繁体   中英

javascript jquery selecting radio buttons

I have a php script that outputs many divs, in each div is a radio button with a specific value. I want to create a better user experience by having the radio button selected when the div is clicked, which isn't much of a problem when I use jquery. The problem is, when the radio button itself is clicked and not the div, the following clicks don't have the effect of selecting the radio button any more. I also tried to remove the checked attribute on every radio button before checking the selected one, but this doesn't work. Here is how I do it:

$(".fontCellDiv").click(function(){ 
     $(this).find("input").attr("checked", true);
 });

Has anyone an idea?

Use .prop() instead of .attr()

From the documentation:

Attributes vs. Properties

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

 $(".fontCellDiv").click(function(){ $(".fontCellDiv").find("input").removeAttr('checked'); $(this).find("input").attr("checked", true); }); 
 .fontCellDiv{ width: 100px; background-color: #0f0; margin-bottom: 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div class="fontCellDiv"> <input name="sameGroup" type="radio" /> </div> <div class="fontCellDiv"> <input name="sameGroup" type="radio" /> </div> <div class="fontCellDiv"> <input name="sameGroup" type="radio" /> </div> 

Check this sample.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM