javascript check radio buttons automatically

前端 未结 2 1901
滥情空心
滥情空心 2021-01-11 23:28

I wanna check radio buttons automatically: I tried this code but it does not work: Radio buttons have 3 different values, I wanna select the radio button with value \'clean\

相关标签:
2条回答
  • 2021-01-12 00:27

    you might try setting the "checked" attribute instead.

    var getElements = function()
    {
        var x = document.getElementsByTagName("input");
        var oldname = '';
    
        for(var i = 0; i < x.length; i++)
        {
            if(x[i].type == 'radio' && x[i].name != oldname && x[i].value == 'clean')
            {
                x[i].checked = true;
                oldname = x[i].name;
            }
        }
    };
    

    The problem with this function is that it will attempt to check all the radio buttons, so if they belong to a group (which is usually the case), only the last radio button from each group will be selected. If that is your intention, then great, otherwise it bears thinking about how to decide which button is selected, and breaking the loop. You can see in the function above that I have decided to select only the first button in the group, by checking the name attribute of the element.

    I hope this helps you!

    • Matt

    UPDATE

    Another way to handle this, using jQuery, would be:

    var getElements = function(){
      var oldname = '';
      $.each($('input[type="radio"]'), function(){
         if($(this).attr('name') != oldname && $(this).val() == 'clean'){
            $(this).checked = true;
            oldname = this.name;
         }
      });
    };
    
    0 讨论(0)
  • 2021-01-12 00:28

    Give your radio buttons "names" would make things a lot easier

    <input type="radio" name="myradios" value="clean"/>
    <input type="radio" name="myradios" value="somethingelse"/>
    
    var elements = document.getElementsByName('myradios');
    for (i=0;i<elements.length;i++) {
      if(elements[i].value == "clean") {
        elements[i].checked = true;
      }
    }
    

    Working example : http://jsfiddle.net/Dwzc9/

    Updated

    getElementsByName doesn't seem to be supported in all IE versions ... so you could use the following based on your original example :

    var allElems = document.getElementsByTagName('input');
    for (i = 0; i < allElems.length; i++) {
        if (allElems[i].type == 'radio' && allElems[i].value == 'clean') {
            allElems[i].checked = true;
        }
    }
    

    Working example : http://jsfiddle.net/Dwzc9/2/

    0 讨论(0)
提交回复
热议问题