简体   繁体   中英

get selected value of radio button

I am new to Javascript. I have a code snippet like this:

<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>  

On selecting a radio button, I want to know which option is selected (op1/op2/op3).

To get the value of the selected radioName item of a form with id myForm: $('input[name=radioName]:checked', '#myForm').val()
Here's an example:

$('#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>

Think this helps you.

How about this:

<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>

in your .js:

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

 <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> 

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