Pawan Pawan - 3 months ago 8
HTML Question

Try to change warm unselect object in form

I'm new to jquery. Now I'm trying to change those unselected objects into red border to warn the user to fill in some values.

if($("select:visible").val()==undefined ){

$(this).css({"border-color":"red"});
}


but it doesn't seem to change anything. I want to change "those" if if statement is true. how can i implement it?

Also, Im trying to make the border red. But I don't want to just make it red. Instead I want the effect just like the bootstrap "input" with that blue border when "onfocus". Is it possible to do so?

Answer

this isn't set per block, it's set per function, so $(this) doesn't select the element just referenced in the if condition. Keep a reference to the element instead:

var mySelect = $("select:visible");
if (mySelect.val() == undefined) {
  mySelect.css({"border-color":"red"});
}

Except that the above assumes there will be only one element. The following technique will handle any number of elements:

$("select:visible")
  .css({"border-color":""})                         // remove border from all
  .filter(function() { return this.value === "" })  // select empty ones
  .css({"border-color":"red"});                     // add border

Note that that uses this, but inside the function passed to .filter(). So what it does is first grab all visible select elements, then reduce that set to the ones with no value, then set those ones to have a red border.

You'd be better off adding and removing a class though, so that you can apply whatever additional formatting you like without having it all hard-coded inside your JS.:

$("select:visible")
  .removeClass("invalid")
  .filter(function() { return this.value === "" })
  .addClass("invalid");

Here's a small demo:

$("button").click(function() {
  $("select:visible")
    .removeClass("invalid")
    .filter(function() { return this.value === "" })
    .addClass("invalid");
});
select {
  border-color: blue;
}
.invalid {
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="">Please select a value</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select>
<option value="">Please select a value</option>
<option value="1">Whatever</option>
<option value="2">Blah</option>
</select>
<br><br>
<button>Test Validation</button>