I want to make simple Jquery function like this:
function switchButton($param) {
$param.on('change', function() {
var result = $($param +'.switch-field input[name=switch]:checked').val();
alert(result);
});
}
Execute like this:
switchButton(('.switch-field input'));
Please help to format this function correctly. Thank you.
1 Answer 1
JSFiddle: https://jsfiddle.net/xpvt214o/111367/
function switchButton(element) {
element.on('click', function() {
alert(element[0].id); // do something
});
}
switchButton($('#btn1'));
switchButton($('#btn2'));
answered Apr 12, 2018 at 17:23
user3271960
Sign up to request clarification or add additional context in comments.
4 Comments
Grufas
Ok, I will ask it differently, how to convert code below to proper function: function switchButton() { $('.switch-field input').on('change', function() { var result = $('.switch-field input[name=switch]:checked').val(); alert(result); }); } So it can be used as easy as possible in different places.
Stephen P
@LifeIsShort - if you need to clarify your question, then Clarify your Question ... don't try to shovel more code in comments.
lang-js
switchButton($('.switch-field input'));missing the$. And then your inner lookup would need to be changed to$param.find('.switch-field input[name=switch]:checked').val()$('input').val(). Just be aware of the differences.