A NewBie
A NewBie

Reputation: 181

Set a class for a textbox on focus using Javascript

I have the following HTML Bootstrap code

 <div class="form-group">
            <label class="col-sm-2 control-label labelfont">FIRST NAME:</label>
            <div class="col-sm-6">
               <input type="text" class="form-control" placeholder="Enter the First Name" id="FirstName" onkeypress="return onlyAlphabets(event);">
            </div>
            <label class="col-sm-4 labelfont errorMsg" id="Err_FirstName">Enter the first name</label>
        </div>

My JS code on Tabout is as follows

$("#FirstName").blur(function () {
    if ($(this).val().trim().length == 0)
    {
        $(this).addClass('borderclass');
        $("#Err_FirstName").show();   
    }
    else {
        $("#Err_FirstName").hide();
        $(this).removeClass('borderclass');
    }
});

The 'borderclass' is as shown

.borderclass
{ 
     border:1px solid red;
}

The above code is working fine on Tab out.

enter image description here But on moving the focus back to the control to enter the values,I dont see the red border anymore.

enter image description here

I thought bootstrap has its own css for each control which is getting set when the focus goes back to the control.In order to fix this,I tried the following,which did not work

  $("#FirstName").focusin(function () {
    if($("#Err_FirstName").visible)
        $(this).addClass('borderclass');
});

Any help in the right direction would be appreciated.Thanks a lot.

Upvotes: 3

Views: 1711

Answers (2)

Vitorino fernandes
Vitorino fernandes

Reputation: 15951

styles were overwritten with bootstrap you can add this

.borderclass:focus {
    border: 1px solid red;
    box-shadow: 0px 0px 2px 0px red;
    outline: 0;
}

demo - http://www.bootply.com/XpOUxMMhdT

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

There is no visible property in jQuery objects.. There is however $.fn.is which does what you want. That is, you could use the pseudo-selector :visible as the argument in is method which returns a boolean.

$("#FirstName").focusin(function () {
   if($("#Err_FirstName").is(":visible"))
      $(this).addClass('borderclass');
}

Upvotes: 0

Related Questions