How to make js work with specific html blocks? - javascript

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.

Related

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>

Hide a ',' comma that repeats multiple times on a page

I'm trying to hide a ',' (comma) that appears multiple times on a CMS-generated page. See the page here:
http://www.ucd.ie/earth/sandbox/test/01.html
I have tried the following code just before the tag (without success):
<script language="javascript">
var container = $(".hide-comma");
var result = container.html().replace(/,/g, "");
container.html(result);
</script>
Enter the below code after load page completed:
$('.team-description').each(function(i , v){
var t = $(v).html().replace(/,/g, '');
$(v).html(t);
});
and see below link
https://jsfiddle.net/sajjadgol/xpvt214o/881975/
I think you want to replace all the "," inside the div. so you can do like this.. get html inside the div then replace all the ','
function replaceComma(){
$('#divWithComma').html($('#divWithComma').html().replace(",",""));
console.log('replaced the comma, if you want to see hiding the comma please run the snippet again');
}
function hideComma(){
let text = $('#divWithComma').html();
let stringArray = text.split(',');
let finalHtml = "";
for(let i = 0; i<stringArray.length-1; i++){
finalHtml += stringArray[i] + '<span style="display:none;aria-hidden=true">,</span><p></p>';
}
$('#divWithComma').html(finalHtml);
console.log("yes hide the comma");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='divWithComma'>
<p>,</p>
<input type='button' onclick='replaceComma()' value='replace comma' />
<input type='button' onclick='hideComma()' value='hide comma' />
</div>

Remaining characters if data exists 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>

jQuery replace <p> tag with line break

I have a html text like this:
<div>
<p>1111</p>
<p>2222</p>
<p>3333</p>
</div>
I want to replace <p> tag with line break but make all text into <p> tag:
<div>
<p>
1111
<br/>
2222
<br/>
3333
<br/>
</p>
</div>
I have tried with replaceWith but the result was different from what I want
Does this work for you?
$("div > p").each(function () {
$(this).replaceWith($(this).text() + "<br/>");
});
$("div").wrapInner("<p></p>");
https://jsfiddle.net/vnLnmx0c/
This is a possible solution using only javascript.
element = document.getElementById("replace"); //Replace for whatever you want
html = element.innerHTML;
html = html.replace(/<p>(.*)<\/p>/g, "$1<br />"); //$1 here contains all the html between the <p> tags. So you can change this around to what you want it to be, example: <a>$1</a>
element.innerHTML = html;
<div id="replace">
<p>1111</p>
<p>2222</p>
<p>3333</p>
</div>
You can do like this:
var ps = $("#maindiv").find("p");
var par = [];
ps.each(function(index, d){
par.push($(d).text());
});
var text = par.join("</br>");
//remove all the paragraph dom
$("#maindiv").find("p").remove();
//make aparagraph dom and add the new html text joined by </br>
$("#maindiv").append("p").html(text);
Working code here.
I have a created a fiddle for you. check it
https://jsbin.com/gazefa/edit?html,js,output
<button onclick="removePs('target')">Remove Multiple Ps</button>
<div id="target">
<p>1111</p>
<p>2222</p>
<p>3333</p>
</div>
JS
function removePs(div_id) {
var html = '<p>';
$('#' + div_id + ' p').each(function(i, p) {
html += $(p).html() + '</br>';
});
html += '</p>';
$('#' + div_id).html(html);
}

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");
});
});

Categories

Resources