Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 844
A NewBie Avatar asked Jul 03 '26 12:07

A NewBie


1 Answers

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

like image 185
Vitorino fernandes Avatar answered Jul 05 '26 01:07

Vitorino fernandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!