Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to optimize jquery code with find()?

i have a form with an id="test". Inside the form i have some select, input and textarea fields.

i want to iterate through each of them and check if they are empty and then do something with them.

var editTest= $('#test');

editGeneric(editTest);

var editGeneric= function(form){
    form.children().find('select').each(
        function(){
            var values = $(this).val();
            if(values === 'select one' || values === 'Select One' || values == 0 || values == 99){
                $(this).css('border', '1px solid red');
            }
        }
    );

    form.children().find('input').each(
        function(){
            var values = $(this).val();
            if(values === ''){
                $(this).css('border', '1px solid red');
            }
        }
    );

    form.children().find('textarea').each(
        function(){
            var values = $(this).val();
            if(values === ''){
                $(this).css('border', '1px solid red');
            }
        }
    );
}

this code does what i need, but you can see that i repeat myself a few times.

how can i simplify this code so i can maybe use it with some other forms?

any ideas?, thanks

edit: thanks all

i got the code down to:

var editGeneric= function(form){

    form.children().find(':input').each( function(){
            var values = $(this).val();

            if ($(this).is('select')){
                if(values === 'select one' || values === 'Select One' || values == 0){
                    $(this).css('border', '1px solid red');
                }
            }
            if ($(this).is('input') || $(this).is('textarea')){
                if(values === ''){
                    $(this).css('border', '1px solid red');
                }
            }
        }
    );

}

editGeneric($('test'));
like image 639
Patrioticcow Avatar asked Feb 03 '26 22:02

Patrioticcow


1 Answers

You can use jQuery's :input selector, which selects inputs, selects, and textareas:

form.children().find(':input').each( ...

The only problem is that your select validation is a little different, so you can either check .is('select') to change the condition:

if (($(this).is('select')
   && (values === 'select one' || values === 'Select One'
   || values == 0 || values == 99) || !$(this).is('select') && values === ''))
   || !$(this).is('select') && values === '') {

You also don't have to use form.children.find() .. you could just use $("#test :input") or $(":input", form);

like image 84
Explosion Pills Avatar answered Feb 06 '26 12:02

Explosion Pills