1

I am trying to select all input fields inside a certain element. I pass this element to a function, but I don't know how to go from there:

$('._save, .btn-success').click(function(){
   saveForm($('.dashboard_container'));
});

//This functions has to select all the input fields inside the given element
function saveForm(that) {
    var input = $(that, 'input'); //This does not seem to work
    input.each(function(){
       //Do something
    })
}

How to chain a variable and a selector together?

1
  • You are looking for all input inside a button tag, probably you need to look up on its parent form element.... The best way is to bind the submit event to the form! Commented Nov 12, 2015 at 8:53

2 Answers 2

2

The contextual selector takes the parameters the other way around to what you've used:

function saveForm($that) {
    var $input = $('input', $that);
    $input.each(function(){
       //Do something
    })
}

You could also use the find() method as you're passing in a jQuery object:

var $input = $that.find('input');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for both options! I tested both options by performance and there isnt much difference. So both methods seem fine!
No problem, glad to help.
0

If you need to find all input field inside some element x then you can use .find(input).

For example:

//This functions has to select all the input fields inside the given element
function saveForm(that) {
    var input = $(that).find("input"); //This does not seem to work
    input.each(function(){
       //Do something
    })
}

And you can achieve it without using .find as well (the way you were trying to do)

$('._save, .btn-success').click(function(){
   saveForm('.dashboard_container');
});

//This functions has to select all the input fields inside the given element
function saveForm(that) {
    var input = $(that + ' input'); //This does not seem to work
    input.each(function(){
       //Do something
    })
}

Comments

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.