0

I would like to know if and how you can pass a jquery command as function's parameter

var childs = ["#foo", "#bar"];

loopTheChilds("trigger('change')");

loopTheChilds("prop( 'disabled', true )");

var loopTheChilds = function ( operation ) {

    $.each ( childs, function ( idx, val ) {
        $( val )[operation]();
    });

}

My gol would be to obtain this

$( "#foo" ).trigger("change");
$( "#bar" ).trigger("change");

// or

$( "#foo" ).prop( 'disabled', true );
$( "#bar" ).prop( 'disabled', true );

Or know how to get the same result in any other way.

Thanks

1
  • It is possible with eval(), but using eval() is considered as bad practice. Commented May 8, 2017 at 9:59

1 Answer 1

1

You can't tell javascript what code to execute as a string unless you use eval but as mentioned in the comments this is not very safe and generally not recommended. What you can do however is make your loopTheChilds method take a function as parameter, and that function has a parameter with a reference to the element.

So you could end up doing something like so:

var childs = ["#foo", "#bar"];

loopTheChilds(function(elem) {
    elem.trigger('change');
});

loopTheChilds(function(elem) {
    elem.prop('disabled', true);
});

function loopTheChilds(func) {
    $.each(childs, function(idx, elemName) {
        func($(elemName)); //wrap in jquery selector
    });
}

Now you just pass along the function you want to execute when you call the loopTheChilds method.

Working demonstration here: https://jsfiddle.net/phpyn1t6/

Sign up to request clarification or add additional context in comments.

1 Comment

It's not exactly what I was thinking to was, but it seems to me an excellent solution. Thank you

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.