简体   繁体   中英

Specifying the first character in an input field

I've got an input field with a place holder.

<input id="showInfo" type="text" placeholder="Search product" />

I'm allowing to search a product by its code. Every product begins with S . example: S12548, S25487, S87425

How can I make sure the first character is S when the keypress() function is fired?

$('#search').keypress(function(e){

});

You can use indexOf() to check if the first character of the typed string is s or S .

$('#search').keypress(function (e) {
    var text = $(this).val().trim();

    if (text.indexOf('S') === 0 || text.indexOf('s') === 0) {
        // Valid
    } else {
        // Invalid, then add a at the start
        $(this).val('S' + text);
    }
});

Demo using Regular Expression.

You can also use regex to check if the string starts with s/S

 $('#search').keyup(function(e) { var text = $(this).val().trim(); $(this).toggleClass('error', !/^s/i.test(text)); }); 
 .error { border: solid 1px red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <input type="text" id="search" /> 

You can also use regex to check if text starts with s .

if (/^s/i.test(text)) {
    // Valid

You need to check on blur of the input try this code and hit right if you like

$(document).ready(function () {
    $("#showInfo").blur(function () {
        var is_s = $(this).val();
        if (is_s.charAt(0) == 's' || is_s.charAt(0) == 'S') {
            alert("Check for prod");
        } else {
            alert("Do not check for prod");
        }
    });
});

You might wanna think about something like this:

if ([ID].charAt(0) == 's' || [ID].charAt(0) == 'S') {
    return;
} else {
    [ID].insert(0, s);
}

You can try this.

$('#search').keypress(function (e) {
    var text = $(this).text().trim();

    if (text.charAt(0).toLowerCase() == 's') {
        // Condition True  - Do Something
    } else {
        // Condition False - Do something
        return false;
    }
});

You can use keyCode to check if it 'S''

$('#search').keypress(function(e){
  if(e.keyCode == 83) {
     // continue ...
  }
}

If you're using jQuery use jQuery Validator plugin and something like this:

$.validator.addMethod("searchCode", function(value, element) {
    var aux = $('#search').value;
    return aux.charAt(0) == "S";
} 

You can do something like this...

<script type="text/javascript">
$(function() {
    $('#showInfo').keyup(function(e) {
        var value = $(this).val();
        if (value.substring(0, 1) != 's') {
            $(this).val('');
            $(this).css('border', '1px solid #ff0000');
        }
    });
});
</script>

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