简体   繁体   中英

Jquery modal window show only if input value lenght is more than 2

I have such code for showing modal window when i click enter on my keybord:

  $(".search-input").keypress(function(e) {
    if(e.which == 13) {
      $('#screen').css({ opacity: 0.5, 'width':$(document).width(),'height':$(document).height()});
      $('#screen').show();
      $('#loading_modal').show();    
    }
  });

but i need to custom it so, that if input with class .search-input value is less than 3, i didn't show any modal window's...

I try so:

  $(".search-input").keypress(function(e) {
    if(e.which == 13) {
      if($(".search-input").value.length > 2) {
        $('#screen').css({ opacity: 0.5, 'width':$(document).width(),'height':$(document).height()});
        $('#screen').show();
        $('#loading_modal').show();    
      }
    }
  });

but for some reasons it doesn't work( How to solve my problem?

use trim() to remove whitespace and val()

try this

  if($.trim($(this).val()).length > 2) {
      ......

This will basicly replace any text with nothing:

$(".search-input").value.replace(/{.*?}/g, '').length > 2

Try this instead:

$.trim($(this).val().replace(/[^\w\s]/g, '')).length > 2

If you really only want letters in the search string do this:

$(this).val().replace(/[^a-z]/gi, '').length > 2

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