I am trying to delegate a function with a change in radio button selection.
$(document).ready(function(){
$('body').on('change', 'radioBtnName', function(e){
$(this).after('<p>"No click me!"</p>');
});
});
What I want to be able to do is to pass some values to the handler function. Like
{param1:"hell", param2:"world"}
And then to access these values inside the function (e) by
e.data.param1
How do I include these parameters and give them values in setting the delegate. I am creating the radio buttons on the fly and want to associate the function with a change in selection.
This could be easily done with data-*
attributes if they are per element. So have the button with:
<input type="radio" data-param1="hell" data-param2="world" />
And get them using:
$(this).data("param1");
$(this).data("param2");
Also, if you call the $(this).data()
, it will return you the whole data
object.
Store them as data attributes on the radio buttons:
$(document).on('change', 'radioBtnName', function(e){
var $button = $(this);
var param1 = $button.data("param1");
var param2 = $button.data("param2");
// do whatever you want with the values :)
});
Note use document
instead of body
for delegated events. This avoids the need for a DOM ready handler (and avoids a bug with body
)
If I got you right you want to pass extra parameters with the .on()
method. I hope the following example helps you.
$(document).on('change', '#radioBlock input[type="radio"]', {param1: 'hell', param2: 'world'}, function(e){ console.log(e.data.param1); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="radioBlock"> <input type="radio" id="one" name="one" value="One"> <input type="radio" id="two" name="two" value="Two"> <input type="radio" id="three" name="three" value="Three"> </div>
You can use $(this).data()
like this:
$(function() { $("body").on('click', "#radioBlock input[type='radio']", function(e) { alert('Data Value - ' + $(this).data('value')); }) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="radioBlock"> <label> <input type='radio' name='radio_input' data-value='1'> Radio 1 </label> <label> <input type='radio' name='radio_input' data-value='2'> Radio 2 </label> <label> <input type='radio' name='radio_input' data-value='3'> Radio 3 </label> </div>
Hope this helps!
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.