1

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.

2
  • 1
    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() Commented Apr 12, 2018 at 17:18
  • 1
    This is a normal JavaScript function; a jQuery function is attached to the jQuery prototype and called on jQuery objects like $('input').val(). Just be aware of the differences. Commented Apr 12, 2018 at 17:25

1 Answer 1

1

JSFiddle: https://jsfiddle.net/xpvt214o/111367/

function switchButton(element) {
    element.on('click', function() {
        alert(element[0].id); // do something
    });
}

switchButton($('#btn1'));
switchButton($('#btn2'));
Sign up to request clarification or add additional context in comments.

4 Comments

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.
@LifeIsShort - if you need to clarify your question, then Clarify your Question ... don't try to shovel more code in comments.
What @StephenP said. Also, take the template code I gave you above and fork off that. Don't wait for someone to give you the exact code you need for your application just so you can copy paste it or you're going to have a rough time in software development.
@LifeIsShort Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.