Keypress in text input preventing typing - javascript

I have a text input that I want to execute a function when enter is pressed. I used if condition to determine if enter is pressed but this causes the user not to be able to type in the input box. What can I put in the else condition to allow them to type normally?
JsFiddle
function addItem(e) {
e.preventDefault(); // Prevent form being submitted
var text = $('input:text').val(); // Get value of text input
var itemArr = text.split(',');
var lngth = itemArr.length
for(i = 0; i < lngth; i++)
{
$list.append('<li>' + itemArr[i] + '</li>'); // Add item to end of the list
updateCount(); // Update the count
} // End loop
$('#addItems').val(''); // Empty the text input
return false;
}
$('#addItems').keypress(function(e) {
if(e.which == 13) {
addItem();
}
return false;
});

Remove return false; from the keypress function.
$('#addItems').keypress(function(e) {
if(e.which == 13) {
addItem();
}
else {
return true;
}
return false;
});

Jusr remove return false from the keypress event
You can see this Question
return false; successfully cancels an event across browsers if called at the end of an event handler attribute in the HTML.
and to prevent form from form being submitted, you can add onsubmit="return false" to the form
Demo

Related

Conditional jQuery validation based on custom attribute

I'd like to enable/disable buttons on key up change conditionally based on a custom data attribute that matches between an input and a button. I've solved it with just one input, but it seems that when I add another one in the mix, the buttons don't seem to enable.
Furthermore, I have a hunch that it's because of .each() but I can't put my finger on it.
Here's the CodePen I've tried and failed on
var validation = $('[data-validation]');
var validate;
validation.on("change keyup", function (e) {
let validated = true;
validation.each(function () {
let value = this.value;
validate = $(this).data('validation');
if (value && value.trim() != "") {
validated = false;
} else {
validated = true;
return false;
}
});
if (validated) {
$('[data-validator=' + validate + ']').prop("disabled", true);
} else {
$('[data-validator=' + validate + ']').prop("disabled", false);
}
});
The key here is to only run your validation code for the input that was changed. As opposed to what you have, which is to run for all inputs.
To get the input that actually changed, you can utilize the .target property of the event object passed to the event handler.
Alternatively, if you remove the validation.each() entirely, it also works. That is because jQuery sets the value of this to be the DOM element (not a jQuery-wrapped element) that actually triggered the event.
var validation = $("[data-validation]");
var validate;
validation.on("change keyup", function (e) {
let validated = true;
let value = this.value;
validate = $(this).data("validation");
if (value && value.trim() != "") {
validated = false;
} else {
validated = true;
return false;
}
if (validated) {
$("[data-validator=" + validate + "]").prop("disabled", true);
} else {
$("[data-validator=" + validate + "]").prop("disabled", false);
}
});

Javascript | Enter key first time should press a button, second time should press a label or url

First time we press keyboard enter key should execute button(id="botonCorregir"). But the second time we press enter key should execute url().
I use cont, for the first time execute one part of the javascript code, and after when de cont value is 1, execute the second part of javascript code.
For some mistake, it doesn´t work.
thanks!
HTML:
<input id="respuestaUsuario"></input>
<button id="botonCorregir">Reply</button>
<a id="enlaceSiguiente" href="nextQuestion.html">Next question</a>
JAVASCRIPT:
<script>
var cont=0;
if(cont==0){
//Should enter the first press of enter
var input = document.getElementById("respuestaUsuario");
console.log('input: ', input)
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
cont++;
}else{
//Should enter the second press of enter
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("enlaceSiguiente").click();
}
}
</script>
You have a few mistakes in the code.
You are assigning the event based on the value of cont so always will have that functionality. Javascript does not re-interpret the code once the value of cont is changed.
I mean, Javascript check only one time the condition:
if(cont==0){}
This is a solution that works:
var cont=0;
var input = document.getElementById('respuestaUsuario');
input.addEventListener('keyup', function (event) {
event.preventDefault();
if (event.keyCode == 13) {
if(!cont){
alert('uno');
document.getElementById("botonCorregir").click();
cont++;
}else{
document.getElementById("enlaceSiguiente").click();
}
}
});
I guess you were on the right track, but the problem is that your Javascript only gets executed once. So, the else case will never be triggered. I refactored your code to use the check in the event listener:
var cont = 0;
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function (event) {
if (event.keyCode == 13) {
event.preventDefault();
if (cont == 0) {
cont++;
document.getElementById("botonCorregir").click();
} else {
document.getElementById("enlaceSiguiente").click();
}
}
});
I also created a codepen for you to check out.

Return false; does not work in jquery .each function

Before posting this question I tried StackOverflow but did not find the answer.
So, the question is, I have an array with some values(suppose 4,6,7,8,10 etc). I used the .each function of jquery to prompt the alert message. but my code gives me an alert message, focus to the desired input box and submit the form and does not "return false".
I want it to return false after focusing.
$(document).on('keypress','#create_invoice',function(){
$.each(newArr, function( i, l ){
//alert( "Index #" + i + ": " + l );
if($.trim($('#item_name'+l).val()).length == 0)
{
alert("Please Enter Item Name");
$('#item_name'+l).focus();
// return false; //if use this not work and submit form
}
//return false; //if use this not work and submit form
});
//return false; if i use this then submit() not work
$('#invoice_form').submit();
});
The return false works, but I think what you want is to stop the form from submitting if you returned false. That behavior can be done with this;
First put an e in the function argument then use e.preventDefault();.
What's next is make a variable that would be a boolean which would determine if you can allow the form to submit. In the code below, I used var allowSubmit.
Try the code below.
$(document).on('keypress', '#create_invoice', function(e) {
e.preventDefault();
// boolean variable
var allowSubmit = true;
$.each(newArr, function(i, l) {
if ($.trim($('#item_name' + l).val()).length == 0) {
alert("Please Enter Item Name");
$('#item_name' + l).focus();
// set the variable to false
allowSubmit = false;
return false;
}
});
// check if we could submit the form
if (allowSubmit) {
$('#invoice_form').submit();
}
});

Lower word limit in textarea

I have this code, it displays word count and applies an upper word limit. Can you tell me how I can change this code to apply lower limit? For example if user enters 299 words and hits enter, a pop up should appear and say, you didn't enter enough words. Thanks.
$("#TextArea").on('keyup', function () {
var words = this.value.match(/\S+/g).length;
if (words > 300) {
var trimmed = $(this).val().split(/\s+/, 300).join(" ");
$(this).val(trimmed + " ");
}
else {
$('#display_count2').text(words);
$('#word_left2').text(300 - words);
}
});
});
You'll need to add a keypress event to have it work when enter is pressed. If you want it to work from anywhere in your form, you could add it on the document. That way it will be run no matter where enter is pressed.
$(document).keypress(function(e) {
if(e.which == 13) {
checkWordLimit();
}
});
You could then hook this up to a function that checks the word length
function checkWordLimit() {
var words = this.value.match(/\S+/g).length;
if (words < 300) {
alert("You need to enter at least 300 words!");
} else {
$('#display_count2').text(words);
$('#word_left2').text(300 - words);
}
}
If you want to keep the word count text updated, then just keep calling that function in the keyup event:
$("#TextArea").on('keyup', function () {
checkWordLimit();
});
To have it check before it submits the form (on a button click), then you can change the function to return true/false based on the word count check, and then submit the form if it is successful. Note that this is for a regular button, not a submit button. If it's a submit button, then the submit event in the form will need to be intercepted.
$("#SomeButton").on('click', function () {
if(checkWordLimit()) {
$("#SomeForm").submit();
}
});
You need to add keydown event on that text area, and your event handler function should be something like this.
function onKeyDown(e){
if(e.keyCode == 13){ //for enterkey
var words = this.value.match(/\S+/g).length;
if(words >= 300){
//Your success code
}else{
alert("You didn't enter enough words");
}
}
}

How can I validate input when input submit is clicked prior to the submit happening?

I want it so when they click on the submit button it will first check all the fields with class="req" and if any are empty it will cease to submit and give them an error, otherwise the submit should go through.
How can I do this?
This should do it:
document.getElementById('myForm').onsubmit = function() {
var elems = document.getElementsByClassName('req');
for(var i = 0; i < elems.length; i++) {
if(elems[i].value.length == 0) {
return false;
}
}
}
That will attach the function to your form's submit event. If any of those elements are empty, the function will return false immediately, preventing the form from being submitted.
If you don't want whitespace-only values to be counted as filled, you can replace the if condition in the above with this:
if(elems[i].value.replace(/^\s+|\s+$/g,"").length == 0) {
...
Adding an "onsubmit" event handler to the form will let you take action when you need to.
<form onsubmit="checkMyForm(this)">
...
</form>
Then you can define a handler
<script>
function checkMyForm(myForm) {
for (var i = 0; i < myForm.elements.length; ++i) {
var input = myForm.elements[i];
if (/\breq\b/.test(input.className) && !input.value) {
// Has an empty required input
alert('Please enter all required inputs');
input.focus();
return false; // abort form submission
}
}
}
</script>

Categories