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");
});
});
Related
I've got a working script that when loaded (as part of a Chrome extension) on a page it modifies the onclick events to include a setInterval value with a little random math. What I'd like to do is have a text field on the page that allows me to input a value in ms rather than hard coding it in the js file. Nothing I've tried so far has worked. I've included a beginning version that adds a text field but, I can't get it to use the value I type in the text field in the function in place of the 240000 that's there now.
Thanks in advance for any help!
$(function() {
var automiss = document.getElementsByClassName("row")[0];
automiss.insertAdjacentHTML('beforebegin', '<input style="margin-bottom:4px;" type="text" name="newbutval" id="newbutval"/>');
if (document.URL.indexOf("missions.game") > 0) {
$('.btn.startBtn.btn-large').each(function() {
var current = $(this).attr("onclick");
$(this).attr("onclick", "setInterval(function(){if (Math.random() > 0.3) {" + current + "}}, 240000);");
});
}
});
//Below is the working script - THANK YOU!
$(function()
{
if (document.URL.indexOf("missions.game") > 0){
var automiss = document.getElementsByClassName("row")[0];
automiss.insertAdjacentHTML('beforebegin', '<input style="margin-bottom:4px;" type="text" name="newbutval" id="newbutval"/>');
$('#newbutval').on('change',function(){
$('.btn.startBtn').each(function(){
var current = $(this).attr("onclick");
var newvalue = parseInt($("#newbutval").val());
$(this).attr("onclick", "setInterval(function(){if (Math.random() > 0.3) {" + current + "}}," + newvalue + " );");
});
})
}
});
You can use $("#newbutval").val() to get the input's value, but as the input's type is text, you would probably want to parse the value as an int as well:
parseInt($("#newbutval").val())
I am pulling some text from a database and I have , and I would like to replace them with <br> don't really know why it's not working any ideas?
JS Code
$( document ).ready(function() {
//.MoreInfoText
var $infotext = $('.MoreInfoText').text().replace(/\+/g, '<br>');
$.each($infotext, function() {
$('.MoreInfoText').text($infotext);
});
});
Text as its coming from the DB:
Ryan open 30/01/1998, ryan added numberOFIteams of NameOFIteams
1st use replace(/\,/g, '<br>')); yours only replace +
(note the g means replace all, you can also make the search case-insensitive pass the "i" parameter ex: /gi)
2nd use $('.MoreInfoText').html() so your <br> are treated as HTML instead of string.
$( document ).ready(function() {
//.MoreInfoText
$('.MoreInfoText').html($('.MoreInfoText').text().replace(/\,/g, '<br>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="MoreInfoText">11111,22222,33333,44444,55555</span>
It should be .replace(/,/g,"<br>") so all ,s get replaced with <br>. Right now it's replacing + with <br>.
Also to iterate over every element with class MoreInfoText replacing , with <br> modify your code like this:
$('.MoreInfoText').each(function() {
var text = $(this).text().replace(/,/g, '<br>')
$(this).html(text);
});
Try to use the following code:
$( document ).ready(function() {
//.MoreInfoText
var $infotext = $('.MoreInfoText').text().replace(',', ' ');
$.each($infotext, function() {
$('.MoreInfoText').text($infotext);
});
});
I would recommend avoiding the usage of <br /> for adding line breaks, you may consider using <p> instead.
$( document ).ready(function() {
//.MoreInfoText
$('.MoreInfoText').each(function() {
var moreArray = $(this).text().split(',');
var $infotext = '';
for(var i = 0; i < moreArray.length; i++){
$infotext += '<p>' + moreArray[i] + '</p>';
}
$(this).empty().html($infotext);
});
});
If paragraphs are not already placed each on a new line, you can add a CSS rule for that. This helps separating the content from the presentation, which is what CSS is for.
I am trying to replace the selected text in the p tag.I have handled the new line case but for some reason the selected text is still not replaced.This is the html code.
<p id="1-pagedata">
(d) 3 sdsdsd random: Subject to the classes of this random retxxt wee than dfdf month day hello the tyuo dsds in twenty, the itol ghot qwerty ttqqo
</p>
This is the javascript code.
function SelectText() {
var val = window.getSelection().toString();
alert(val);
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/\r?\n|\r/g,""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/[^\x20-\x7E]/gmi, ""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(val,"textbefore" + val + "textAfter"));
}
$(function() {
$('#hello').click(function() {
SelectText();
});
});
I have also created a jsfiddle of the code.
https://jsfiddle.net/zeeshidar/w50rwasm/
Any ideas?
You can simply do $("#1-pagedata").html('New text here');
Since your p doesn't content HTML but just plain text, your can use both html() or text() as getter and setter.
Also, thanks to jQuery Chaining you can do all your replacements in one statement. So, assuming your RegExp's and replacement values are correct, try:
var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));
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);
});
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>