简体   繁体   中英

jQuery blur function not working

I am using html and jQuery library, trying to avoid core JavaScript, just bc I do not want to mix it

I have 3 fields, when user click on field1, then click some where else, I want field1 border to turn red only.

If user click on field2 then clicks some where else, I want field2 border to turn red only.

Right now blur() works perfectly but it creates a red border on every fields. this is because I am using .input class. any idea how can I do this without getting id? bc I will have 40 fields when i am done

html code:

<asp:TextBox runat="server" id="test1" class="input green" /> <br />
<asp:TextBox runat="server" id="test2" class="input blue" />

jquery code:

$(function() {
  $(".input").blur(function() {
    if ($(".input").val().trim() == '')
      $(".input").css('border-color', 'red');
    else
      $(".input").css('border-color', '');
  });
});

Use $(this) instead of repeating class name.

 $(function() { $(".input").blur(function() { if ($(this).val().trim() == '') $(this).css('border-color', 'red'); else $(this).css('border-color', ''); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="input"/> <input type="text" class="input"/> <input type="text" class="input"/> 

Optional

Also instead of $(this).val().trim() == '' you can use $(this).val().length <= 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM