Block enter key when less than 4 digits entered - javascript

I'm trying to implement a code in my script that will block enter key until 4 digits entered in a text field.
Here are my forms:
<div id="inputtext">
<input type="text" id="dreamtext" maxlength="45" spellcheck='false' autofocus/>
<input type="submit" id="nextstepbutton" value="next step" onclick="window.open('step3.html','_self','resizable=yes')" />
</div>
This particular script hides submit button when < 4 characters entered and shows it when 4 or more entered. It also modifies some div content.
<script type="text/javascript">
$(function(){
$("#nextstepbutton").hide();
$("#dreamtext").keyup(function() {
var val = $(this).val();
if (val.length > 3) {
$('#nextstepbutton').show();
document.getElementById("message").innerHTML = "<h1>hit return or next step</h1>";
}
else {
$('#nextstepbutton').hide();
document.getElementById("message").innerHTML = "<h1>type please</h1>";
}
});
});
</script>
This script presses submit button when enter key pressed
<script type="text/javascript">
$("#dreamtext").keyup(function(event){
if(event.keyCode == 13){
$("#nextstepbutton").click();
}
});
</script>
Now, what is the best way to block the enter key when less than 4 digits entered? Thanks

There is a method in the keydown(/up/press) event called preventDefault.
This makes any default action not happen.
$("#dreamtext").keyup(function(event) {
if ($(this).val().length < 4) {
event.preventDefault();
}
if (event.keyCode == 13) {
$("#nextstepbutton").click();
}
});
You could also connect it to the jQuery .submit() handler.
$("#someForm").submit(function(){
if ($("#dreamText").val().length < 4) {
return false;
}
})

Related

how to read multiple value length in javascript?

I am working on a barcode scanner and currently have a problem where I need the barcode to read 2 different value lengths, currently I have it set to submit the value at 9 length.
<span>
<input type="text" id="IC-input" name="IC" onkeyup="autofill(this.value)" placeholder="Enter your IC Number" required maxlength="12">
<label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
</span>
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 9){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
now i need it to read from 12 value as well but it auto submits when the value hits 9 digits. I have tried OR function .
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 12 || value.length == 9){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
i also tried the Else function
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 12){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
else if(value.length == 9){
theButtonIsPressed(value);
}
}
But it would always read the first 9 value and leave the 3 other value unread. Does anyone have a solution for this? Thank you in advance.
Seems like you are listening to the keypress. Use a timer to cancel it. Basic idea of a debounce method.
var timer;
function autofill(value){
if (timer) window.clearTimeout(timer);
if(value.length === 9){
timer = window.setTimeout( function () {
processIt(value);
}, 50);
} else if(value.length === 12){
processIt(value);
}
}
function processIt(value){
console.log('here', value);
}
BUT That is a bad solution. Typically you set up the scanner to fire a tab or enter press so you know it is done. I would check to see if that is happening and listen for that instead. You can then just listen for that and you know the scanner is done.
var inp = document.getElementById("barcode");
inp.addEventListener("keydown", function (evt) {
if (["Tab", "Enter"].includes(evt.key)) {
evt.preventDefault();
console.log('scanner is done', evt.target.value);
}
});
<input type="text" id="barcode" />
The problem is that the autofill function runs to press the button as soon as the input box has 9 characters. It is because you are running the autofill function by the 'onkeyup' event listener attached to the input tag.
The solution is to run the autofill function after making sure there is a full length value intended. Good luck.
For a most common scene, the scanner will trigger such event one by one: focus, input character....input final 'Enter' character, so you have to take attention to the last event.
<script type="text/javascript">
window.addEventListener("load", function () {
var ic = document.getElementById("IC-input");
ic.addEventListener("focus", function (args) {
ic.value = "";
});
ic.addEventListener("keyup", function (args) {
if (args.key == "Enter") {
autofill(ic.value);
}
});
});
function autofill(value) {
console.log("Autofill:" + value)
//console.log(9 digits);
button = document.getElementById("theButton");
if (value.length == 9) {
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
</script>
<span>
<input type="text" id="IC-input" name="IC" onkeyup="input_keyup" placeholder="Enter your IC Number" required maxlength="12">
<label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
</span>

How can I fire the Tab keypress when the Enter key is pressed?

This is what I have and it works fine.
But I want to return the tab key instead of just nothing happening.
$(document).on("keypress", ":input:not(textarea):not([type=submit])", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
What I want is:
if (event.keyCode == 13) {
event.preventDefault();
return event.keyCode = 9; <<= or something similar and simple
}
This seems like a duplicate but I don't see anything to substitute enter for tab code... Tab key already knows to skip hidden and use tab orders.
I suspect what you really want is to move to the next field in the form.
If so, you can easily find the next form field and use .focus() to focus it. For instance:
var fields = $(this).closest("form").find("input, textarea");
var index = fields.index(this) + 1;
fields.eq(
fields.length <= index
? 0
: index
).focus();
Example:
$(document).on("keypress", ":input:not(textarea):not([type=submit])", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
var fields = $(this).closest("form").find("input, textarea");
var index = fields.index(this) + 1;
fields.eq(
fields.length <= index
? 0
: index
).focus();
}
});
<form>
<div>
<label>
Field 1:
<input type="text">
</label>
</div>
<div>
<label>
Field 2:
<input type="text">
</label>
</div>
<div>
<label>
Field 3:
<input type="text">
</label>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you're using tabindex to put fields in a different order than document order, you'll have to do a bit more work, basically sorting the result of find on tabindex and working from there. But that should get you going the right way.
I got the accepted answer to work for me, but I needed to figure out where to stick the code exactly:
$(document).on("keypress", ":input:not(textarea):not([type=submit])", function(event) {
if (event.keyCode == 13) {
var fields = $(this).closest("form").find("input, textarea");
var index = fields.index(this) + 1;
fields.eq(
fields.length <= index
? 0
: index
).focus();
event.preventDefault();
}
});

Submit form on keypess after verification

$(document).ready(function() {
//attach keypress event listener to the whole document
$(document).keypress(function(event){
if(event.keyCode === 13){
SearchThis.submit();
return false;
}
});
});
So now my form (SearchThis) is submitted whenever the enter key is pressed which is great however how do I modify it to check if mysearchfied has been completed before it submits?
IE. If mysearchfied is empty and the enter key is pressed don't submit the form. If mysearchfied contains text and the enter key is pressed then submit the form.
Hope you can help! Thanks...
If you just want to validate the textbox for required use HTML5 required attribute like:
<input type="text" class="form-control" name="mysearchfield"
value="" id="mysearchfield" placeholder="Company or SmartPages Category..." autocomplete="off" required>
listenOn = function(domElement) {
domElement.addEventListener('keydown', function(event) {
if (event.keyCode == 13) {
onEnterPressed();
}
});
function onEnterPressed() {
if (validateForm()) {
submitForm();
} else {
alert('Invalid form');
}
}
function validateForm() {
var inputValue = document.getElementById("myInput").value;
return (inputValue.length >= 1);
}
function submitForm() {
var formElement = document.getElementById("myForm");
alert('Submit form');
formElement.submit();
}
}
listenOn(document);
//listenOn(document.getElementById("myForm")); //You could also listen keydowns on form element(sure only if global keypress isn't exactly what you want).
<form id="myForm" action="#send.php">
<input id="myInput" type="text" placeholder="I'm empty now." />
</form>
There are two ways to validate the form.
-> Check is the form valid usind the form valid function
SearchThis.validate().valid()
-> validate each field for value as told by #n01ze
if the id of your input field is mysearchfield, then you could do it like this:
var msf = document.getElementById("mysearchfield").value;
$(document).ready(function() {
//attach keypress event listener to the whole document
$(document).keypress(function(event){
if(event.keyCode == 13){
if (msf != "") {
SearchThis.submit();
return false;
}
else
{
// some code here....
}
}
});
});
if (event.keyCode === 13) {
if ($('mysearchfied_ID_or_Class').val()!=='') {
//mysearchfied is not empty
SearchThis.submit();
}
else {
//dont submit, do your checks
}
return false;
}

How to create a javascript function that responds to a click or enter pressed?

I need the if bottom if statement to run if #nextQ is clicked (like it is currently) or if enter is pressed.
$('input[type=text]').on('keyup', function(e) {
if (e.which == 13) {
alert("enter is pressed");
return true;
}
});
$('#nextQ').click(function() {
//me.html validations
if (actual == 0 && document.URL.indexOf("me.html") >= 0){
loadNew();
}
});
If your input is wrapped in a form and that form has a submit button, it is submitted when you press enter inside the input.
Knowing this you should listen to the submit event:
The form:
<form class="myForm">
<input name="answer" type="text">
<button id="nextQ" type="submit">next Question</button>
</form>
JS:
jQuery( '.myForm' ).on( 'submit', function( event ) {
//me.html validations
if (actual == 0 && document.URL.indexOf("me.html") >= 0){
loadNew();
}
} );

how to detect textbox field empty spaces?

I need help in textbox keypress function.
If textbox fields is empty menad no need to post values.
my following functions working .if textbox fields is empty,i press enter key going nexline thats fine.but i press enter key two times values posted.
what is the problem in my code.plz help me.
$(".ppop-comment").keypress(function(e)
{
if($('#add_comment').val()=="")
{
if (e.which == 32)
return false;
}
else if (e.keyCode == 13 && !e.shiftKey && !$('#add_comment').val()==" ")
{
$("#submit-comment").click();
}
});
<form id="commentform" method="post">
<textarea id="add_comment" name="meetnewpeople[message]" class="popup-comment">
<input id="submit-comment" type="button" value="Post a comment" />
</form>
$(".ppop-comment").keypress(function(e)
{
if($('#add_comment').val().trim()!="")
{
if (e.keyCode == 13 && !e.shiftKey && !$('#add_comment').val()==" ")
{
$("#submit-comment").click();
}
}
else
{
return false;
}
});

Categories