开发者

How do you check if a radio button has the attribute 'checked' with Prototype

I have a bit of code that checks a list if LI tags which contain radio button input's. I have some clever logic via the Chocolate Chip Javascript framework library to work out when an LI is clicked, it will apply a relevant class to display the radio button has been selected.开发者_如何转开发

However, I want to expand that logic so that it digs deeper into the LI and finds which radio button input is the one that is already selected (prior to any user choosing anything) when the page loads and apply a class to it so that it instantly highlights what is already selected.

I'm a bit new to Prototype so I'm not sure what is the best approach to do this so would appreciate any help you can offer.

So in the case below, I want to pick out button 3.

JSFiddle Link: http://jsfiddle.net/Qw6KA/

HTML:

<ul class="radioList">
   <li>
      <input type="radio" id="radio1" name="radioButton" value="Button 1">
      <label for="radio1">Button 1</label>
   </li>
   <li>
      <input type="radio" id="radio2" name="radioButton" value="Button 2">
      <label for="radio2">Button 2</label>
   </li>
   <li>
      <input type="radio" id="radio3" name="radioButton" value="Button 3" checked="checked">
      <label for="radio3">Button 3</label>
   </li>
   <li>
      <input type="radio" id="radio4" name="radioButton" value="Button 4">
      <label for="radio4">Button 4</label>
   </li>
</ul>

JS (Prototype):

$.RadioButtons = function( viewSelector, callback ) {
    var items = viewSelector + ".radioList li";
    var radioButtons = $$(items);
    radioButtons.forEach(function(item) {
        item.bind("click", function() {
            radioButtons.forEach(function(check) {
                check.removeClass("selected");
            });
            this.addClass("selected");
            this.last().checked = true; 
            if (callback) {
                callback(item);
            }
        });
    });
};

Thanks -JaXL


$.RadioButtons = function( viewSelector, callback ) {
    var items = viewSelector + ".radioList li";
    var radioButtons = $$(items);
    radioButtons.forEach(function(item) {
        item.bind("click", function() {
            radioButtons.forEach(function(check) {
                check.removeClass("selected");
            });
            this.addClass("selected");
            this.last().checked = true; 
            if (callback) {
                callback(item);
            }
        });

        // Add this bit
        if (item.select('input[checked]').length) {
            item.addClassName('selected');
        }
    });
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜