简体   繁体   中英

Jquery on keypress

I'm looking for a function that gives an alert when a certain character key (g) is pressed in the first position of a postal code, and then disables the submit button if the postal code has a letter G in the beginning. Is this possible?

My current code to detect a key up on the postal code field at the moment is this:

 $(document).ready(function() { var someTextInputField = "#postal-code"; $(someTextInputField).on("keyup", function() { alert('not a valid postal code'); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="postal-code" /> 

Javascript without extra libraries

 document.addEventListener("input", function(e) { if (e.target.id === "postal-code") { var disable = /^g/i.test(e.target.value), submit = document.getElementById("submit"); if (disable && !submit.disabled) { alert("You cannot start a postal code with a G"); } submit.disabled = disable; } }); 
 <input placeholder="Address" /> <input id="postal-code" placeholder="Postal Code" /> <button id="submit">Submit</button> 

jQuery

 $(document).on("input", "#postal-code", function (e) { var disable = /^g/i.test(this.value), $submit = $("#submit"); if (disable && !$submit.prop("disabled")) { alert("You cannot start a postal code with a G"); } $submit.prop("disabled", disable); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input placeholder="Address" /> <input id="postal-code" placeholder="Postal Code" /> <button id="submit">Submit</button> 

You can use this.value[0] to get the first character of the input. Then test whether it's one of the allowed characters.

 $("#input").on("keyup", function() { if (this.value != '') { var firstchar = this.value[0].toUpperCase(); if (firstchar != 'A' && firstchar != 'G') { alert('not a valid postal code'); $("#submitID").prop("disabled", true); } else { $("#submitID").prop("disabled", false); } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="input"/> 

Check this fiddle http://jsfiddle.net/oyc2L9sy/12/

html:

<input id="test" type="text" />

javascript:

$(document).ready(function() {
    $("#test").on("keypress", function(e) {  
        if ((e.keyCode == '65') ||
            (e.keyCode == '71')) { 
            alert('not a valid postal code');
            return false;
        }
    });  
});

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