简体   繁体   中英

Radio button 'undefined' value

I have a problem - why is this code non working ?

<input type="radio" name="one" value="xxx" onclick="test()"/>
//below in the same file
<script>
    function test()
    {
        if (this.value=="xxx")
        {
            alert('ok');
        }   
    }               
    </script>

There is no alert after clicking radio button. When I've tried to display the value of a radio button - it is showing 'undefined', not 'xxx' - why ?

cheers

 <input type="radio" name="one" value="xxx" onclick="test(this)"/>
<script>
    function test(radioItem)
    {
        if (radioItem.value=="xxx")
        {
            alert('ok');
        }   
    }               
    </script>

It is showing undefined, because the function is called when the input is clicked, but the function is not bound to the input, so when it is called there is no element bound to the click, so the click is triggered, but this is undefined. Try adding an ID to the input and then binding the function to the click event, like this:

 <input id="testDiv" type="radio" name="one" value="xxx" /> <script> document.getElementById('testDiv').onclick = function() { if (this.value == "xxx") { alert('ok'); alert(this.value); } } </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