manu29.d manu29.d -4 years ago 115
HTML Question

jQuery radio button on change does not work

I have seen this question and I have seen this fiddle.

My

Fiddle
here. It's a simple question. Why doesn't it work?

#html
<input checked="checked" id="article_format_html" name="article[format]" type="radio" value="html">Some meaningful value
<input id="article_format_text" name="article[format]" type="radio" value="text">Another Value

#js
$("input[name='article[format]']:radio").change(alert('hola'));


Edit:



On popular demand I did this:

.change(function(){alert('hola')});


Fiddle.

Result: Doesn't work.

Edit 2: (Why I had the problem)



So, JS-Fiddle wraps your js code in the head of the
iframe
that is your
Result
section. For jQuery selectors (or any js that manipulates the DOM) to work properly, it has to be executed *after* the DOM element has been rendered. Hence, wrapping your code on ready and/or just before
body
closes, is the safest way to ensure that your query selectors don't return
undefined
.

Answer Source
  1. Use a callback or anonymous function block
  2. You are using jQuery 1.11 (better to use .on syntax)

Demo: http://jsfiddle.net/abhitalks/e5ByP/2/

$("input[name='article[format]']:radio").on("change", function() { 
    alert('hola'); 
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download