0

I am missing something here. Seems like an easy question. I have this:

<form>
  <input type="text" name="name" id="name" class="form-control" placeholder="Name" required />
  <input type="text" name="address" id="address" class="form-control" placeholder="Address" required />
  ...
</form>

I want this function to work:

$('#submit').click(function() {

    var fields = $('.form-control');
    _.each(fields, function(field) {
        if( field.value == "" ) {
            field.css("background","#FFB6B5");
        }
    });

});

I get undefined is not a function on the line:

field.css("background","#FFB6B5");

Is like the field is not an element. Why this is happening?

4
  • What's with _.each? Any reason you're not using jQuery's $.each? Commented Mar 18, 2015 at 14:47
  • Good point! I am new with this, so I was mixing up jQuery and underscore.js, apparently. Thanks! Commented Mar 18, 2015 at 14:50
  • Hey as long as it works :) Commented Mar 18, 2015 at 14:54
  • I would suggest that you change the class and define your css in a stylesheet instead of setting inline styles. Commented Mar 18, 2015 at 15:00

2 Answers 2

2

As per your code field refers to underlying DOM element and .css() is a jQuery function. Thus you need to use jQuery object.

Use

$(field).css("background","#FFB6B5");

You can use .each()

Iterate over a jQuery object, executing a function for each matched element.

Example

$('.form-control').each(function( index ) {
    if(this.value == ""){
        $(this).css("background","#FFB6B5");
    }       
});
Sign up to request clarification or add additional context in comments.

Comments

0

I would do it like:

$('#submit').click(function() {

    $('.form-control').each(function() {
        if ($(this).val() === "" ) {
            $(this).css("background","#FFB6B5");
        } else {
            $(this).css("background","#FFF");
        } 
    });

});

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.