Simplify jQuery for detecting change of an input's value [duplicate] - javascript

This question already has answers here:
How to detect a textbox's content has changed
(15 answers)
Closed 8 years ago.
I am tracking the number of characters typed into a textarea are < 140. I am currently only catching characters on 'keyup' but also want to track if a user copy/paste into the textarea. Any suggestions?
$(function(){
var limitDiv = $("#limit");
var limit = limitDiv.data("limit");
var button = $("input");
$("textarea").on("keyup", function(){
var total = this.value.length;
var diff = limit- total;
var condition = diff < 0 || total === 0;
limitDiv.text(diff).toggleClass("red", condition);
button.prop("disabled", condition);
}).trigger("keyup");
})

There is a paste event in jQuery, though its not used very frequently. It seems to still work as of jQuery 2.1.0.
$("#input").on("paste", function(e){
//code goes here
});
http://jsfiddle.net/gty70qc9/2/

Just add a paste event:
$(function(){
var limitDiv = $("#limit");
var limit = limitDiv.data("limit");
var button = $("input");
$("textarea").on("keyup paste", function(){
var total = this.value.length;
var diff = limit- total;
var condition = diff < 0 || total === 0;
limitDiv.text(diff).toggleClass("red", condition);
button.prop("disabled", condition);
button.value(total);
});
})
textarea {
width: 100%;
height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<input type="button" value="Submit">
<div id="limit" data-limit="15"></div>

Related

How do I limit the amount of checkbox checked with JavaScript(no jquery please)

I'm making a Node Express multiple choice test, and each question has different amount of correct answers. I have my answers coming from a database auto-populate in PUG. However my Function doesn't work right, when I click over the limit of correct answers, the alert pops up but then the answer is checked anyways. What am I doing wrong?
I tried making a function that tracks how many answers checked, but can't get it to stop after it reaches the limit.
block content
header.header USA Government Test
main.q-card
p.q-promt #{question}
small (Please choose #{mcLimit} answers)
hr
each answer in answers
label.container
| #{answer.Answer_prompt}
input(type='checkbox' name='answer' onclick="ckLimit()")
span.checkmark
hr
script.
function ckLimit() {
var limit = #{mcLimit};
var total = 0;
var inputTag = document.getElementsByTagName('input');
var x = inputTag.length;
for (var i = 0; i < x; i++) {
if (inputTag[i].checked) {
total += 1;
}
if (total > limit) {
alert(`Please select only ${limit}`);
this.checked = false;
return;
}
}
}
everything works accept the: this.checked = false;
It continues to check answers. This what my code looks like now:
header.header USA Government Test
main.q-card
p.q-promt #{question}
small (Please choose #{mcLimit} answers)
hr
each answer in answers
label.container
| #{answer.Answer_prompt}
input(type='checkbox' name='answer' onclick="return ckLimit()")
span.checkmark
hr
script.
function ckLimit() {
var limit = #{mcLimit};
var total = 0;
var inputTag = document.getElementsByTagName('input');
var x = inputTag.length;
for (var i = 0; i < x; i++) {
if (inputTag[i].checked) {
total += 1;
}
if (total > limit) {
alert(`Please select only ${limit}`);
this.checked = false;
return;
}
}
}
Add return keyword to the below statement.
input(type='checkbox' name='answer' onclick="ckLimit()")
thus becoming
input(type='checkbox' name='answer' onclick="return ckLimit()")
Without return, onclick proceeds on allowing the default action of checking. Once onclick gets false value, it stops the action.
Edit:
In function ckLimit, return should return false.
if (total > limit) {
alert(`Please select only ${limit}`);
this.checked = false;
return false;
}

Counter is not changing color according to the function

the counter needs to turn red when i reach 10 characters. When i reach 10 characters, i have to press any button again in order for the counter to turn red. When i delete the characters, the counter remains red instead of going back to black.
<script>
function ceScriu(){
var numeInput = document.querySelector("[name='nume']");
var nume = numeInput.value;
var nu = nume.toString().toLowerCase();
var divInput = document.querySelector("[name='divul']");
var div = nu.length;
document.querySelector("[name='divul']").innerHTML = div;
numeInput.onkeypress = function(){
if(div === 10){
event.preventDefault();
divInput.classList.add("counter");
}else{
divInput.classList.remove("counter");
}
}
}
</script>
I want the counter to turn red when i enter the 10th character and i want the counter to turn back to black when i start deleting characters after i reached the 10th.
1.) By declaring the variables before the onkeypress, you're passing the original values. It might be better to check the length/value again inside the keypress function.
2.) Onkeypress does not work with backspaces. You should use "onkeyup" in order to detect the backspace change.
3.) If you want to detect 10 or more characters (and keep the box red until the length is less than 10), you should use div >= 10 as a comparison (more than or equal to 10)
`
function ceScriu(){
// *1
var numeInput = document.querySelector("[name='nume']");
var nume = numeInput.value;
var nu = nume.toString().toLowerCase();
var divInput = document.querySelector("[name='divul']");
var div = nu.length;
document.querySelector("[name='divul']").innerHTML = div;
// *2 numeInput.onkeypress = function(){
/* New event check*/
numeInput.onkeyup = function(){
/* End new event check*/
/* New length Check */
let nume = numeInput.value;
let nu = nume.toString().toLowerCase();
let div = nu.length;
/* End new length check */
// *3 if(div === 10){
/* New comparison */
if(div >= 10){
/* End new comparison */
event.preventDefault();
divInput.classList.add("counter");
}else{
divInput.classList.remove("counter");
}
}
}
`
Hope that helps!
onkeypress is not suitable in this case. You can use either onkeyup or oninput event. To restrict the inputs up to certain length you can use maxlength attribute.
Try the following way:
function ceScriu(el){
var divInput = document.querySelector("[name='divul']");
var div = el.value.trim().length;
document.querySelector("[name='divul']").textContent = div;
if(div === 10){
divInput.classList.add("counter");
}
else{
divInput.classList.remove("counter");
}
}
.counter{
color:red;
}
<input name="nume" oninput="ceScriu(this)" maxlength="10"/>
<div name="divul"></div>
You need define a style ".counter" first and put the script and style inside the tags, your code works when you try to press 11 times, if i put 1234567890 and try to put another, the style changes and set the red color
.counter{
color:red;
width:100px;
}
<script>
function ceScriu(){
var numeInput = document.querySelector("[name='nume']");
var nume = numeInput.value;
var nu = nume.toString().toLowerCase();
var divInput = document.querySelector("[name='divul']");
var div = nu.length;
document.querySelector("[name='divul']").innerHTML = div;
numeInput.onkeypress = function(){
if(div === 10){
document.querySelector("[name='divul']").classList.add("counter");
event.preventDefault();
}else{
divInput.classList.remove("counter");
}
}
}
</script>
</head>
Thank you for all your answers. Some of them were of help and led me to this result.
It seems that all i needed to do was just add 2 more IF statements.
I'm adding the code here.
function ceScriu(){
var numeInput = document.querySelector("[name='nume']");
var nume = numeInput.value;
var nu = nume.toString().toLowerCase();
var divInput = document.querySelector("[name='divul']");
var div = nu.length;
document.querySelector("[name='divul']").innerHTML = div;
numeInput.onkeypress = function(){
if(div >9){
event.preventDefault();
}else{
divInput.classList.remove("counter");
}
}
if(div<10){
divInput.classList.remove("counter");
}
if(div>9){
document.querySelector("[name='divul']").classList.add("counter");
}
}

Auto-adjusting textarea to be the same height as inner-text onkeydown

I'm trying to auto adjust the height of a textarea onkeydown, but it's only working partially. When you're typing text into the textarea, it auto-adjust the height of the textarea per new line of text, which is what I want. But when you're backspacing the text, it auto-adjust the height of the textarea per character-backspaced when you're on the last 5 characters of every last line. What am I doing wrong?
#textarea {
overflow: hidden;
}
<textarea id = 'textarea' onkeydown = "adjust()"></textarea>
<script>
function adjust() {
document.getElementById("textarea").style.height = document.getElementById("textarea").scrollHeight+'px';
} //end of function adjust()
</script>
Create your textarea:
<textarea id="textarea" onkeyup="InputAdjust(this)"></textarea>
then create a function to do the auto height
<script>
function InputAdjust(o) {
o.style.height = "1px";
o.style.height = (25+o.scrollHeight)+"px";
}
</script>
now its +25px, you can change it.
example: https://jsfiddle.net/urp4nbxf/1/
Try this :
$("#textarea").on("keydown",function(){
if($(this).css("height").replace("px","") < $('#textarea').get(0).scrollHeight - 5)
$(this).css("height",($('#textarea').get(0).scrollHeight-5) + "px");
});
Example : https://jsfiddle.net/DinoMyte/dpx1Ltn2/2/
The code below will work, but you will have to manually count how many characters fit in per row, in the textarea. How many characters fit in per row will depend on the cols of the textarea, and of course the font-size of the text.
#textarea {
overflow: hidden;
}
<textarea id = 'textarea' cols = '7' rows = '1' onkeydown = "adjust()"></textarea>
<script>
function adjust() {
var maxCharactersPerColumn = 9; //You have to manually count how many characters fits in per row
var key = event.keyCode;
if (key == 8 || key == 46) {
var length = document.getElementById("textarea").value.length-2;
} //end of if (key == 8 || key == 46)
else {
var length = document.getElementById("textarea").value.length;
} //end of else !(key == 8 || key == 46)
var rows = Math.floor(length/maxCharactersPerColumn)+1;
document.getElementById("textarea").rows = rows;
} //end of function adjust()
</script>

Stop users from entering text into an textarea field after a certain amount of characters have been entered

I'm trying to stop users from entering data into a textarea after the character count has reached its limit. And is it possible for the character count to keep track of how many characters have been entered even after the page has been refreshed?
Jquery
$('.character-count').text('4000 characters left');
$('#description').keyup(function(){
var max = 4000;
var len = $(this).val().length;
var ch = max - len;
$('.character-count').text(ch + ' characters left');
});
Try this:
var max = 10;
$('#description')
.keydown(function(event){
if (event.keyCode != 8 && event.keyCode != 46 && $(this).val().length >= max) {
event.preventDefault();
}
})
.keyup(function(){
var $this = $(this),
val = $this.val().slice(0, max),
val_length = val.length,
left = max - val_length;
$('.character-count').text(left + ' characters left');
$this.val(val);
});
After each keyup textarea value is cut off after max symbols.
Keydown event is blocking after value length reached max,but you can still press backspace (8) or delete (46) keys.
use local storage in order to deal with later use
HTML
<textarea name="userText" id="description" cols="30" rows="10"></textarea>
<div class="character-count"></div>
jQuery
$(function(){
var comment = $('#description');
var val = localStorage.getItem( comment.attr('id') ),
max = 4000,
len = val.length,
left = ( max - len ) ;
// if the value exists, set it
if (val) {
comment.val(val);
$('.character-count').text( left + ' Character(s) left');
}
});
$('#description').on('keyup', function (e) {
var $this = $(this),
max = 4000,
val = $this.val(),
val_length = val.length,
remain = ((max - val_length)>=0)?(max - val_length):0;
$('.character-count').text(remain + ' Character(s) left');
if( val_length > max ){
$this.val(val.slice(0,max));
}
// let's check if localStorage is supported
if (window.localStorage) {
localStorage.setItem($(this).attr('id'), $(this).val());
}
});
SEE DEMO
There is a built-in HTML5 attribute maxlength, which will restrict the count of entered symbols. There is no need to reinvent it yourself:
$("input").on('input', function() {
var left = this.maxLength - this.value.length;
$("span").text(left + " characters left");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" maxlength="5"/>
<span>5 characters left</span>
Also, if you use keyup handler, then the user can easily type your text somewhere else and paste as many characters as he wants. Use input.
Talking about "to keep track of how many characters have been entered even after the page has been refreshed", you may use cookies, but it is a doubtful feature. Any user can easily replace or empty any cookies or other local storage. If this limitation is really important, implement it server-side.
You can save the entire text entered by the user in the cookie as suggested by coolguy and on refresh you can just retrieve the cookie data and display in the text area as well as the character count tracker.
<script>
$(function () {
var descText = $.cookie('description');
var descTextArea = $('#description');
var maxLength = descTextArea.data('maxLength');
if (descText) {
descTextArea.text(descText);
$('.character-count').text((maxLength - descText.length) + ' characters left');
}
else {
$('.character-count').text(maxLength + ' characters left');
}
descTextArea.keydown(function (event) {
var max = maxLength;
var len = $(this).val().length;
var ch = max - len;
if (ch < 0 ) {
event.preventDefault();
return false;
}
$('.character-count').text(ch + ' characters left');
$.cookie('description', $(this).val(), {path: '/'});
});
});
</script>
Using keydown after referring answer by legotin.
HTML file is:
<textarea id="description" data-max-length="4000"></textarea>
<span class="character-count"></span>
I am using jquery.cookie plugin.
Use e.preventDefault() to stop handling.
e.preventDefault();
$('.character-count').html('20 characters left');
var len = 0;
var max = 20;
$('#description').keydown(function (e) {
var code = e.keyCode;
if(len == max && code != 8)
{
e.preventDefault();
return false;
}
len = $(this).val().length;
var ch = max - len;
$('.character-count').text(ch + ' characters left');
});
try this
Fiddle

Javascript Limit Commas

I have a function that displays a countdown next to a text field for the number of characters in the field (think twitter)
<script language="javascript" type="text/javascript">
function countDown(control, maxLen, counter, typeName) {
var len = control.value.length;
var txt = control.value;
var span = document.getElementById(counter);
span.style.display = '';
span.innerHTML = (maxLen - len);
if (len >= (maxLen - 10)) {
span.style.color = 'red';
} else {
span.style.color = '';
}
}
</script>
And the next field down takes a comma separated value. Example:
tomato, apple, orange, pear
and I'd like to limit that list to 5 things (and 4 separating commas).
How can I make a similar function that counts down for the number of commas in the input.
I got this started, but it's not changing the value in the span.
my Javascript
<script language="javascript" type="text/javascript">
var max = 5;
function commaDown(area,ticker){
// our text in the textarea element
var txt = area.val();
// how many commas we have?
var commas = txt.split(",").length;
var span = document.getElementById(ticker);
//var commas ++;
if(commas > max) {
// grab last comma position
var lastComma = txt.lastIndexOf(",");
// delete all after last comma position
area.val(txt.substring(0, lastComma));
//it was count with + 1, so let's take that down
commas--;
}
if (txt == '') {
commas = 0;
}
// show message
span.innerHTML = (max-commas);
}
</script>
and my html (I think the problem lies here)
<input id="choices" type="text" name="choices" class="text medium" onkeyup="commaDown('choices','limit');"/> <span id="limit">5</span><br/>
Any ideas?
Something like this (assuming you have a text field with id csv)
document.getElementById('csv').onkeydown = function(e){
if (!e) var e = window.event;
var list = this.value.split(',');
if (list.length == 5 && e.keyCode == '188' )
{
// what to do if more than 5 commas(,) are entered
// i put a red border and make it go after 1 second
this.style.borderColor ='red';
var _this = this;
setTimeout(function(){
_this.style.borderColor='';
_this.disabled=false;
},1000);
// return false to forbid the surplus comma to be entered in the field
return false;
}
}
example at http://www.jsfiddle.net/gaby/YEHXf/2/
Updated Answer
You seem to have mixed parts of jQuery in your code and that causes the script to fail
var max = 5;
function commaDown(_area, _ticker){
var area = document.getElementById(_area);
// our text in the textarea element
var txt = area.value;
// how many commas we have?
var commas = txt.split(",").length;
var span = document.getElementById(_ticker);
//var commas ++;
if(commas > max) {
// grab last comma position
var lastComma = txt.lastIndexOf(",");
// delete all after last comma position
area.value = txt.substring(0, lastComma);
//it was count with + 1, so let's take that down
commas--;
}
if (txt == '') {
commas = 0;
}
// show message
span.innerHTML = (max-commas);
}
live example at http://jsfiddle.net/z4KRd/
here is a solution:
test: http://jsbin.com/ulobu3
code: http://jsbin.com/ulobu3/edit
if you never used jsBin before, it is very easy, on the left side you have the javascript code (like if it was in your HTML code, and in your right side you have the html code.
and you just need to add /edit to the end of a jsbin url to edit that code, and save any new revisions to that code.
I added jQuery framework to make the example faster to code.

Categories