Remaining characters if data exists Javascript - javascript

I have a web site where users create an account and that information is saved to a JSON. When the user hits "save" the page refreshes and that data is echoed in the field pulling from the JSON. The problem I am experiencing is in one text area I want to limit the amount of characters. The script works perfectly IF there is no data in that textarea. The problem, that I can't figure out, is if there is data, because the user saved it, the countdown text is still 100 and the user can continue typing more information. What I want is when the page refreshes, the Javascript counts the JSON information pre-filled in that text area and counts. Basically once the user saves the data into the JSON and the page refreshes the Javascript counts whatever text is pre-populated. Hope this makes sense. Here are the codes I have.
The text area
<textarea spellcheck="false" id="textarea" maxlength="100"
name="welcome" required><?php if (!empty($main_data->welcome))
{ echo urldecode($main_data->welcome); } ?></textarea>
The Javascript:
<script>
$(document).ready(function() {
var text_max = 100;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
</script>

You can trigger() the event after binding it on page load. The method will execute the event handler and thus the desired result will be achieved.
Execute all handlers and behaviors attached to the matched elements for the given event type.
$('#textarea').on(......).trigger('keyup'); //Notice here
$(document).ready(function() {
var text_max = 100;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').on('keyup', function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
}).trigger('keyup'); //Notice here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea spellcheck="false" id="textarea" maxlength="100" name="welcome" required>PrefilledText</textarea>
<div id="textarea_feedback"></div>
However, I would recommend you to create a method. Then you can invoke it on page load and use it as event handler.
function setFeedback() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
}
//Set on page load
setFeedback();
//Bind event
$('#textarea').on('keyup', setFeedback);

Replace your code to the following:
<script>
$(document).ready(function() {
$('#textarea').keyup(showRemainingCharacters).trigger("keyup");
});
function showRemainingCharacters() {
var maxLength = 100,
currentLength = $('#textarea').val().length,
remainingLength = maxLength - currentLength;
$('#textarea_feedback').html(remainingLength + ' characters remaining');
}
</script>

Related

How to make js work with specific html blocks?

I have the following js code
$(function () {
"use strict";
var maxText = $("textarea").attr("maxlength"),
ourMessage = $(".message");
ourMessage.html('<span>' + maxText + '</span> Characters Remaining');
$("textarea").keydown(function () {
var textLength = $(this).val().length,
remText = maxText - textLength;
ourMessage.html('<span>' + remText + '</span> Characters Remaining');
});
$("textarea").keyup(function () {
var textLength = $(this).val().length,
remText = maxText - textLength;
ourMessage.html('<span>' + remText + '</span> Characters Remaining');
}); });
and the following html code snippet:
<div class="form-group">
<textarea id="field" placeholder="Type Here" maxlength="3000" rows="10" cols="40"></textarea>
<div class="message"></div>
</div>
and it works fine.
But I need more than one of html snippets on the same page and I don't know how to change the code so <div class="message"></div> only changes when "it's" textarea is used.
Assuming the div is always directly after the textarea, you can simply call the next method on the textarea to get the div.

Running a script for 2 (or more) instances on same page

I have a "characters remaining" counter for my Shopify store that shows how many characters a customer has left to enter in a text box. It works perfectly when I have one text box on the page, but if there are two or more, the countdown text does not show at all. Any ideas on how to get this to run for multiple times on the same page?
$(document).ready(function() {
var text_max = $('#line_item_text').attr('maxlength');
$('#personalization_feedback').html(text_max + ' characters remaining ');
$('#line_item_text').keyup(function() {
var text_length = $('#line_item_text').val().length;
var text_remaining = text_max - text_length;
$('#personalization_feedback').html(text_remaining + ' characters remaining ');
});
});
Instead of using id on HTML elements, you need to use classes because the same id is not allowed more than once into an HTML document, if you add it then it does not work.
So use classes and loop the code over each element like you adding using id.
$(document).ready(function() {
$('.line_item_text').each(function(idex,ele){
var text_max = $(ele).attr('maxlength');
$(ele).next().html(text_max + ' characters remaining ');
$(ele).keyup(function() {
var text_length = $(ele).val().length;
var text_remaining = text_max - text_length;
$(ele).next().html(text_remaining + ' characters remaining ');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="50" class="line_item_text"></textarea>
<div id="txt1"></div>
<textarea maxlength="50" class="line_item_text"></textarea>
<div id="txt2"></div>

Retrieve textarea's id on keypress

On keypress in a textarea, I need to select the id and separate it. How is this possible?
If I have some jQuery code:
$(document).on("keypress", "textarea", function(){$(this).
How can I get the textarea's id and separate it like if the id is id="ta1"
Assuming you are just interested in the numeric value part of the ID, you could easily strip off all non-numeric characters using a Regular Expression using the replace() function :
$('textarea').keypress(function(){
// Get your ID
var id = $(this).attr('id');
// Strip off any non-numeric values
var idNumber = id.replace(/\D+/g, '');
});
Working Example
$('textarea').keypress(function() {
// Get your ID
var id = $(this).attr('id');
// Strip off any non-numeric values
var idNumber = id.replace(/\D+/g, '');
alert('<textarea> #' + idNumber + ' was typed in');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>Text Area 1</pre>
<textarea id='ta1'></textarea>
<hr />
<pre>Text Area 2</pre>
<textarea id='ta2'></textarea>
<hr />
<pre>Text Area 3</pre>
<textarea id='ta3'></textarea>
try this
$('body').on('keypress','textarea',function(){
var id = $(this).attr('id')
var ta = id.substring(0,2);
var num = id.substring(2);
});

How do I create a textarea countdown with jQuery?

I'm working on this survey form, and I'm trying to code a comment area that has a character limit of 500. From what I've seen, I'm doing everything "right", but clearly I must be overlooking something.
Here is my jsFiddle.
HTML
<span class="char-remain">500 Characters remaining</span>
<textarea class="comment" rows="10" cols="50" maxlength="500">Enter Text Here</textarea>
jQuery
comment = $(".comment");
comment.on("keyup change", function(){
charCount = $(this).text().length;
charRemain = 500 - charCount;
$(this).prev("span").text("(" + charRemain + ")");
alert(charRemain + "Characters Remaining");
});
The alert is there really for me to see if it's working or triggering at all, which it isn't. What am I missing?
You have an error in the first line.
$(document).ready(function {
Only change to:
$(document).ready(function() {
As you're trying to get the length of the comment field, you need to use the .val() function. It's an equivalent to .value in plain JavaScript.
However, you can optimize your code by using the next:
var maxlength = parseInt(comment.attr("maxlength"), 10);
The code above will store the comment's field maxlength. So you might try with:
$(document).ready(function() {
var comment = $(".comment");
var maxlength = parseInt(comment.attr("maxlength"), 10);
comment.on("keyup keypress change", function() {
charCount = $(this).val().length;
charRemain = maxlength - charCount;
//$(this).prev().prev("span").text(charRemain + " Characters remaining");
$(".char-remain").text(charRemain + " Characters remaining");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span class="char-remain">500 Characters remaining</span>
<br />
<textarea class="comment" rows="10" cols="50" maxlength="500">Enter Text Here</textarea>
As suggested #TiesonT. in the comments, you could easily get the span content by using:
$(".char-remain").text(charRemain + " Characters remaining");
In this context you don't need to worry about tags between the comment field and the span content.
Updated:
You might bind with the keypress event to get the current length while the user is pressing a key.
comment.on("keyup keypress change", function() {
You made two errors here.
Your document ready did not have the right syntax secondly, getting the value from a text area is not text() but it is val().
$(document).ready(function() {
comment = $(".comment");
comment.on("keyup change", function() {
charCount = $(this).val().length;
charRemain = 500 - charCount;
$(this).prev("span").text("(" + charRemain + ")");
alert(charRemain + "Characters Remaining");
});
});

Textarea value remain the same after submitting a form

My previous problem has been fixed, now I need to ask how to keep a textarea from resetting its input after a form is submitted. Here is the jsFiddle: http://jsfiddle.net/rz4pnumy/
Should I change the form in the HTML?
<form id="form1" method="GET">
(the form does not go into a php file or anything else, i'm using it to submit the textarea input and use the variables I made using jQuery to make a paragraph on the same page)
or something in the JS?
$(document).ready( function () {
$('#form1').on('submit', function (event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
var verb1 = $('#verb1').val();
var edibleobject = $('#edible-object').val();
var monster1 = $('#monster1').val();
var adjective3 = $('#adjective3').val();
var monster2 = $('#monster2').val();
var verb2 = $('#verb2').val();
$('body').append(
'<div id="para">' +
'<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' +
'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
'on a table surrounded by a knot of curious people. </p>' +
'</div>'
);
}
});
function validate() {
var success = true;
$('.input').each(function(i, item) {
if ($(item).val() === "")
{
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}
else
{
$(item).removeAttr('style')
// to remove border
}
});
return success;
}
});
The contents get emptied after pressing submit and I only see the completed paragraph for a split second.
You need to prevent the default event handler from executing whether validate passes or not, so you need to remove the if statement around the event.preventDefault() call. The preventDefault is the function that is keeping the from from submitting and re-loading your page.
Also, your Fiddle was not set to jQuery (it was set to no-library) so that may have also been causing you issues during your testing.
Edited for example of what I'm talking about:
$('#form1').on('submit', function (event) {
// block the form from submitting by
// preventing the event's default behaviour from executing.
event.preventDefault();
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
... etc ...
I would use php and set a variable to the GET value of the textarea and set the value of the textarea to that variable

Categories

Resources