user1444393
user1444393

Reputation: 233

Add an event on the radio button

I want to apply an event on my radio buttons when I click on it...

I tried with the following code: my code

<div id="inline_content">
<form class="type" >
    <header class="ui-header">
        <h2 class="ui-title">Duration</h2>
    </header>
<div class="ui-content">
        <ul class="ui-listview">
            <li class="li-has-radio">
                <label>
                    15 mn
                    <input type="radio" value="15" name="radSize" checked="checked"/>
                </label>
            </li>
            <li class="li-has-radio">
                <label>
                    30 mn
                    <input type="radio" value="30" name="radSize"/>
                </label>
            </li>
            <li class="li-has-radio">
                <label>
                    45 mn
                    <input type="radio" value="45" name="radSize"/>
                </label>
            </li>

        </ul>
    </div>
</form>
</div>

And the javascript:

$("#inline_content input[name='type']").click(function(){
alert('You clicked radio!');
// if($('input:radio[name=type]:checked').val() == "walk_in"){
    alert($('input:radio[name=type]:checked').val());
    //$('#select-table > .roomNumber').attr('enabled',false);
//}
});

But it doesn't seem work!

Thanks in advance.

Upvotes: 0

Views: 103

Answers (3)

charliegeiger89
charliegeiger89

Reputation: 46

Here is a jQuery-free version:

var input = document.querySelectorAll("input[name='radSize']");
var totalInputs = input.length;
var radioClick = function(){
    console.log(this.value);
}
for ( i = 0; i < totalInputs; i++ ) {
    input[i].addEventListener('change', radioClick, 0);
}

Upvotes: 0

rogelio
rogelio

Reputation: 1571

Change the selector, see jquery api

$("#inline_content input:radio").click(function(){
    //do something
});

your code: jsfiddle

Upvotes: 0

Oriol
Oriol

Reputation: 287980

Some problems:

  • You didn't include jQuery in the fiddle, so $ is undefined.
  • You don't have any input named type
  • You should listen to change event instead of click one, because inputs can be changed in other ways, e.g. using the keyboard.

This works (if you have jQuery):

$("#inline_content input[name='radSize']").on('change', function(){
    alert('You clicked radio!');
});

Upvotes: 3

Related Questions