How can I make function work with span instead of textarea? - javascript

I want to use
<span id="cLeft">10</span>left.</div>
instead of
<textarea id="cLeft">10</textarea>left.</div>
My function below works fine with textarea id="cLeft" but doesn't fire with span id="cLeft". What's wrong with my code?
myTrail.addEventListener('keypress', function countChars() {
var limitChars = "10";
var stringChars = document.getElementById("myTrail").value;
var lengthChars = stringChars.length;
if (lengthChars <= limitChars) {
document.getElementById("cLeft").value = limitChars - lengthChars;
} else {
document.getElementById("myTrail").value = stringChars.substr(0, 10);
}
});
Here is JSFiddle:
http://jsfiddle.net/pshmM/3/

a <span> has no value
document.getElementById("cLeft").textContent = limitChars - lengthChars;

If you're using a <textarea> you should alter its value:
document.getElementById("cLeft").value = limitChars - lengthChars;
But, if you're using a <span> it has no value, it instead has content, or in other words:
document.getElementById("cLeft").innerHTML = limitChars - lengthChars;
innerHTML !

Related

Subtract number in span

I would like 5 left do -1 e.g. become 4 left.
HTML
<span class="small">5 left</span>
jQuery
// Store the 5 left in "numberStock" variable
var numberStock = parseInt($(".small:first").text());
// Subtract with "numberStock -1"
var minusStock = numberStock - 1;
// Here comes the issue, how do I add the new content?
$(".small:first").attr(minusStock "left");
Question
How do I add the new numberStock number 4 and text left?
A solution in plain Javascript
Array.prototype.forEach.call(document.getElementsByClassName('small'), function (a) {
a.innerHTML = a.innerHTML.replace(/\d+/, function (v) {
return v - 1;
});
});
<span class="small">5 left</span>
You can use replace:
// Store the 5 left in "numberStock" variable
var numberStock = parseInt($(".small:first").text());
// Subtract with "numberStock -1"
var minusStock = numberStock - 1;
console.log(minusStock);
// Here comes the issue, how do I add the new content?
var original = $(".small:first").text();
var toAdd = original.replace(original[0], minusStock);
$(".small:first").text(toAdd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
Use String#replace method with a callback function.
// use text method with callback where second
// argumnet is old text
$(".small:first").text(function(i, txt) {
// replace text with decremented value
return txt.replace(/\d+/, function(m) {
return m - 1;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
UPDATE : With pure JavaSript do something like this.
// since you just want the first element use
// querySelector otherwise you need to use
// querySelectorAll and then need to iterate
// over them
var ele = document.querySelector(".small");
// update text content of span element
ele.textContent = ele.textContent.replace(/\d+/, function(m) {
return m - 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="small">5 left</span>
i am not sure if i understood your question, but if i did here is a way to do it , which is pretty close to what you were trying to achieve
var numberStock = parseInt($('.small').text())
var minusStock = numberStock - 1;
$('.small').text(minusStock + ' left');
here is a fiddle in case you want to test around with it
https://jsfiddle.net/09wcjp7b/

Using .html() to clear previous random string not working

I am writing a short function that appends a random string that is equal in length to a given word. For example, if you input the word 'hello' it would return a random string that is 5 letters long.
This part works as expected. However, I am using $('output').html(""); to overwrite the last random string. I have used this for other functions before and it has worked as expected but it does not here. I have tried moving it around the function to see if it has something to do with the order of the function but it's not deleting the previous random string.
What am I doing wrong?
Fiddle here
HTML:
<input type="text" id="input">
<button id="button">Click Me</button>
<div id="output"></div>
JavaScript:
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
$(document).ready(function () {
$('#button').on('click', function () {
var value = ($('#input').val());
for (i = 0; i < value.length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
};
$('#input').val("");
$('#output').html("");
$('#output').html(text);
});
});
The problem is not with the .html() part. The problem is that your var text is never getting reset.
For reference - http://jsfiddle.net/oo5eLbpu/2/
Updated answer will be as follows
var possible = "abcdefghijklmnopqrstuvwxyz";
$(document).ready(function() {
$('#button').on('click', function() {
var text = ""; // moved the variable inside the click handler
var value = ($('#input').val());
for (i = 0; i < value.length; i++) {
text += possible.charAt(Math.floor(Math.random() *
possible.length));
};
$('#input').val("");
$('#output').html("");
$('#output').html(text);
});
});
Additionally, you can remove the following line from code
$('#output').html("");
As the line beneath it sets the content of the element.
For reference - http://jsfiddle.net/oo5eLbpu/4/
For documentation - http://api.jquery.com/html/
You need also reset variable text,
$('#button').on('click', function() {
text = '';
// your code
});
Example
or move text variable from parent scope to onlick handler
$('#button').on('click', function() {
var text = '';
// your code
});
Example
Also you don't need
$('#output').html("");
because you set content
$('#output').html(text);
Try
$('#output').empty();
From: https://api.jquery.com/empty/

get content of element after slicing his span

I have the next element:
<div id = "mydiv">
abc
<span>123</span>
</div>
document.getElementById('mydiv').textContent returns me: abc123
I want to get only the text of mydiv ('abc'). so I wonder if there is an option to use jquery in order to get it? maybe get all the content of an element except for span element..
and then getting his text..
p.s. I know I can wrap abc in span and then get it, but I wonder if there is another option to do it without changing my element..
DEMO JSFIDDLE
Try this ,
console.log($("#mydiv").clone() .children().remove().end().text());
You must select yours DIV by ID, then run through its "childrens" property and check their nodeType (textNodes has 3);
var div = document.getElementById("mydiv");
var result = "";
for(var i = 0; i < div.length; i++){
var node = div[i];
if( node.nodeType === 3 ){
result += node.data;
}
}
console.log(result);
Since you've included jQuery you can do this
var p = $('#mydiv').clone();
p.find('span').remove();
console.log(p.text());
DEMO
Using jQuery:
$(document).ready(function() {
alert($('#mydiv span').text());
});
If you expect to have more html elements inside your div, user regular expression to extract plain text after getting whole html content from div.
var re = /<.+>/;
var str = "abc<span>123</span>";
var newstr = str.replace(re, "");
Should give "abc"

Can you use appendChild to add an element to a div that had a dynamically created id?

I am trying to add some <p> elements to a div using Javascript. The function loops to create a predetermined amount of these divs. My id for the div is created every time the function runs, and is just 'div' plus a number (e.g.: div1, div2, div3, etc.)
Here is my code:
var divNum = 'div';
function myFunction () {
var divTag = document.createElement("div");
divTag.id = "div";
divTag.className ="info";
document.body.appendChild(divTag);
var idXX = divNum;
$('#div').attr('id',idXX);
var text = document.createElement("p");
text.id = "1";
text.className ="text1-2";
text.innerHTML = "A";
*"PROBLEM HERE"*.appendChild(text);
divNum = divNum + 1;
}
My question is, can you do something to where it says *"PROBLEM HERE"* that makes it append a div with id equal to my var idXX?
Just use divTag.
That line would look like this:
divTag.appendChild(text);
I may be misunderstanding the question, but it seems to me that the "PROBLEM HERE" line should just be this:
$('#'+idXX).append(text); // literally doing what you asked
Or simply this:
divTag.appendChild(text); // better approach since it doesn't have to go look for it.
Also, why do you create the div and then change its ID? Also, divNum is initialized as "div", not 0 like is presumably intended...
If you want to use jQuery and not mix it with base javascript:
var divNum = 'div';
function myFunction () {
var divTag = $("<div>").
.attr("id", divNum)
.addClass("info");
.appendTo($("body"));
$("<p>")
.attr("id", "1")
.addClass("test1-2")
.html("A")
.appendTo(divTag);
divNum = divNum + 1;
}
Looks like your using jQuery to set the attribute id.
$('#div').attr('id',idXX);
You should be able to do everything in jQuery
var divNum = 0;
function myFunction() {
var _p = $('<p>').text('A').addClass('text-1-2')
$('<div>').attr({'id':'div'.concat(++divNum)}).addClass('info').html(_p).appendTo('body');
}

JQuery Truncate Text and insert

I am using some Jquery to insert a element before another element as below:
$(document).ready(function () {
$('a[href*="FolderCTID"]').each(function () {
$(this).closest('tr').find('div[class^="ExternalClass"]').before(this);
});
});
I am able successfully insert before the element
But, .find('div[class^="ExternalClass"]') in the script above is the element i want to truncate before inserting on runtime.
Please help me, how i can truncate the text before i actually insert
Thanks in advance
var someelement = $(this).closest('tr').find('div[class^="ExternalClass"]');
someelement.html(function(i,h){ return h.substring(0,10); });
someelement.before(this);
Try this:
var truncateLength = 10;
$(document).ready(function(){
$('a[href*="FolderCTID"]').each(function(){
var div = $(this).closest('tr').find('div[class^="ExternalClass"]');
var text = div.text();
div.text(text.subString(0, text.length > truncateLength ? truncateLength : text.length));
div.insertBefore(this); // insertBefore rather than before
});
});

Categories

Resources