Jquery selector input[type=text]')

JavascriptJquery

Javascript Problem Overview


I wrote a code that basically selects all input type=text element like this:

$('.sys input[type=text]').each(function () {}

How do I change it to select input[type=text] or select?

Javascript Solutions


Solution 1 - Javascript

Using a normal css selector:

$('.sys input[type=text], .sys select').each(function() {...})

If you don't like the repetition:

$('.sys').find('input[type=text],select').each(function() {...})

Or more concisely, pass in the context argument:

$('input[type=text],select', '.sys').each(function() {...})

Note: Internally jQuery will convert the above to find() equivalent

http://api.jquery.com/jQuery/

> Internally, selector context is implemented with the .find() method, > so $('span', this) is equivalent to $(this).find('span').

I personally find the first alternative to be the most readable :), your take though

Solution 2 - Javascript

$('.sys').children('input[type=text], select').each(function () { ... });

EDIT: Actually this code above is equivalent to the children selector .sys > input[type=text] if you want the descendant select (.sys input[type=text]) you need to use the options given by @NiftyDude.

More information:

Solution 3 - Javascript

If you have multiple inputs as text in a form or a table that you need to iterate through, I did this:

var $list = $("#tableOrForm :input[type='text']");

$list.each(function(){
    // Go on with your code.
});

What I did was I checked each input to see if the type is set to "text", then it'll grab that element and store it in the jQuery list. Then, it would iterate through that list. You can set a temp variable for the current iteration like this:

var $currentItem = $(this);

This will set the current item to the current iteration of your for each loop. Then you can do whatever you want with the temp variable.

Hope this helps anyone!

Solution 4 - Javascript

$('input[type=text],select', '.sys');

for looping:

$('input[type=text],select', '.sys').each(function() {
   // code
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJackView Question on Stackoverflow
Solution 1 - JavascriptAndreas WongView Answer on Stackoverflow
Solution 2 - JavascriptWouter JView Answer on Stackoverflow
Solution 3 - JavascriptJason CidrasView Answer on Stackoverflow
Solution 4 - JavascriptthecodeparadoxView Answer on Stackoverflow