获取单选按钮的选定值

时间:2016-05-05 01:28:39

标签: javascript jquery

我是Javascript的新手。我有一个这样的代码片段:

<ul class="dropdown-menu dropdown-menu-right" onchange="onCompChange()">
                        <div class="radio" id = "compSelect">
                            <label><input type="radio" name="optradio">op1</label>
                            </br>
                            <label><input type="radio" name="optradio">op2</label>
                            </br>
                            <label><input type="radio" name="optradio">op3</label>
                        </div>
 </ul>  

选择单选按钮时,我想知道选择了哪个选项(op1 / op2 / op3)。

3 个答案:

答案 0 :(得分:0)

要获取id为myForm的表单的所选radioName项的值: $('input[name=radioName]:checked', '#myForm').val()
这是一个例子:

$('#myForm input').on('change', function() {
   var value = $('input[name=radioName]:checked', '#myForm').val(); 
   console.log(value);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radioName" value="1" /> 1 <br />
<input type="radio" name="radioName" value="2" /> 2 <br />
<input type="radio" name="radioName" value="3" /> 3 <br />
</form>

认为这有助于你。

答案 1 :(得分:0)

这个怎么样:

<input type="radio" name="opt radio" onclick="check(this.value)" value="op1" >op1</label>
<input type="radio" name="opt radio" onclick="check(this.value)" value="op2" >op2</label>
<input type="radio" name="opt radio" onclick="check(this.value)" value="op3" >op3</label>
你的.js中的

        function check(value) {
            //... use your value
        }

答案 2 :(得分:0)

&#13;
&#13;
<ul class="dropdown-menu dropdown-menu-right" >
                        <div class="radio" id = "compSelect">
                            <label><input onchange="onCompChange(this)" type="radio" name="optradio">op1</label>
                            </br>
                            <label><input onchange="onCompChange(this)" type="radio" name="optradio">op2</label>
                            </br>
                            <label><input onchange="onCompChange(this)" type="radio" name="optradio">op3</label>
                        </div>
 </ul>  

<script type = "text/javascript" language = "javascript">

  function onCompChange(radio){
   
   var content = radio.parentElement.innerHTML;
  var output = content.replace(/<\/?[^>]+(>|$)/g, "");
  alert(output);
	

}       

</script>
&#13;
&#13;
&#13;