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");
}
}
}
Related
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.
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
I have a div which contains an input element to enter some values. These values are added just above the div as a list element upon pressing enter or onFocusOut event. To this point it is fine. But if user types some value and does not press enter and directly clicks on save button, the onFocusOut function for that div should not be called. Instead it should take that typed value and call some save function. Do you have any suggestion on how to detect it?
My code snippet is here
JS:
divInput.onkeypress = function (event){
return someTestFunc();
}
divInput.tabIndex="-1";
$(divInput).focusout(function (e) {
if ($(this).find(e.relatedTarget).length == 0) {
addToList();
}
});
It is not a very delicate solution, but you could use a setTimeout before adding the item to the list and clear the setTimeout on save.button click.
Try this:
var $saveButton = $('#exampleButton')[0],
$divInput = $('#exampleInput')[0],
timedEvent = -1;
$($saveButton).on('click', function(event){
if(timedEvent) {
clearTimeout(timedEvent)
}
alert('not add to list & save');
})
$divInput.tabIndex="-1";
$($divInput).on('focusout', function(e) {
timedEvent = window.setTimeout(function() {
if ($(this).find(e.relatedTarget).length == 0) {
alert('add to list');
}
}, 200);
});
Check this working fiddle
I am having a problem validating a textbox to not allow spacing. When the user enters a space I would like it to display an alert message and then clear the textbox, but the textbox doesn't clear. This is what I have so far.
function ValidateSpace () {
var SerNum = document.getElementById("txtbox1")
if (event.keyCode == 32) {
alert("This field may contain no spaces.");
document.getElementById ("txtbox1").value=""
}
}
I have users trying to put multiple entries in this space but it should only accept one. The textbox is for inventory purposes so it would change the nature of the data if I were to remove spaces
I suppose that you have to bind keyDown event on textbox
try this jquery code to remove live the spaces
$("#IdOfTheTextBox").on("keydown", function (e) {
return e.which !== 32;
});
If you can't use jquery try with this javascript function (onkeypress event of textbox)
function NoSpace() {
if (event.keyCode == 32) {
event.returnValue = false;
return false;
}
}
if you want to remove spaces after the input you can do this
var noSpaces = document.getElementById("txtbox1").value.replace(/\s/g, "");
How can we check if the user press ten times the and reach the char size limit?
if user press more than ten times the key it display an alert, or if user typed more than one hundred chars it show another alert.
Take a look at my start sample at fiddle
Editable: <div contenteditable="true"
style="width:200px;border:3px solid red;min-height:22px;" id="tes></div>
You need to watch the events and to stop the typing after the limits are reached.
To limit and to stop typing when both events occurs, the limit of and the char size of your text box.
You must watch how this two parameters increase and when it reach the limit you need to call event.preventDefault(); to stop typing.
<div class="prompt" contentEditable=true> </div>
<script>
var counter = 0, tamanho=100;
var boxText;
$('.prompt').keypress(function(event){
boxText = $('.prompt').text();
if(boxText.length>tamanho) {
event.preventDefault();
console.log("reach the size of char");
}
if ( event.which == 13 ) {
counter++;
if (counter>=10){
event.preventDefault();//stop the enter action on the div content
console.log("reach the limit of enters");
}
}
});
</script>
You can see here a sample of manipulation of this events.
It is quite simple to check the number of enter hits like this:
$(function() {
var enterCounter = 0;
var charCounter = 0;
$(".myDiv").keypress(function(event) {
if(event.keyCode == 13) {
enterCounter += 1;
};
if(event.keyCode == 13 && enterCounter >= 10) {
event.preventDefault();
};
if(enterCounter == 10) {
alert("Too much of an enter");
};
});
});
And the same goes for number of characters, you just have to specify numeric interval representing the characters.
Or simplier way for character count is to get length of string each time you enter a character.
$(function() {
$(".myDiv").keypress(function(event) {
var text = $(".myDiv").text();
if(text.length == 100) {
alert("Too much characters");
$(".myDiv").text($(this).text().substr(0, 100));
};
});
});