Subtract number in span - javascript

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/

Related

Increment and Decrement Javascript not working

i made a JavaScript function to increment and decrement a number in the like button, here is the function
var val = 0;
var negative = false;
$('.i-t').click(function(){
val = val + ((negative) ? -1 : 1);
negative = (negative) ? false : true;
$("#myval").text(val);
});
This function works great on the first click but clicking the second time it doesn't remove the value, is something wrong with the function? here is the button
<button id="myvals" class="myvals">
<i class="myvals" id="i-t"></i>
<span class="myvals" id="voteScore">123</span></button>
i want to change the 123 to 124 if liked and 122 if disliked and it doesn't works, i'm sorry i had to prepare the question better from the beginning
From your comments and update, what you want to do is to increase/decrease the vote count based on whether you have already clicked or not.
In that case, instead of using a variable, you can store the state using a class to support multiple vote button if you need like
$('button.vote').click(function () {
var $btn = $(this).toggleClass('voted');
$(this).find("span.score").text(function (i, val) {
return +val + ($btn.hasClass('voted') ? 1 : -1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="myvals vote"> <i class="myvals" id="i-t">here</i><span class="myvals score">123</span></button>
You need two buttons, one for up and one for down, or you could use one button and a checkbox for up or down, but I think two buttons is simpler.
When reading values from DOM elements, they're generally strings so if numbers are required, particularly for addition, don't forget to convert the value to a number before doing arithmetic.
So the buttons and code can be something like:
function vote(n) {
// Get the element to update
var el = document.getElementById('votes');
// Convert the text content to Number, then add value
el.textContent = Number(el.textContent) + n;
}
Votes: <span id="votes">123</span>
<button onclick="vote(1)">up vote</button>
<button onclick="vote(-1)">down vote</button>
Of course this is just a demo, adapt it however you wish.
Try this:
var val = 0;
var negative = false;
$('.i-t').click(function() {
val = parseInt($("#voteScore").val()) + ((negative) ? -1 : 1);
negative = (negative) ? false : true;
$("#myval").text(val);
});

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

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 !

Determining a character of a sentence when clicked on

On a random break I found myself wondering if it would be possible to use jQuery to determine a single character within a sentence when it is clicked on.
For example:
This
When the user clicks on first h, jQuery would return this to me.
The only way I could think of doing this would be to wrap each character within the sentence in a span with a class of its letter such as the following example:
<span class="clickable T">T</span>
<span class="clickable h">h</span>
<span class="clickable i">i</span>
<span class="clickable s">s</span>
Followed by a $('.clickable').click(function()) that would return its second class.
My question is: is this the most efficient way to do this?
Obviously wrapping every single letter of the document in span tags is not efficient.
I was able to spin something up that works in Chrome at least. Basically, when you click on a letter, it then triggers a double clicks which selects the word. We get the selection which actually gives us the text of the entire target element. From that, we get the letter that was clicked. We remove the selection and do what we want with the letter.
Fiddle here
$(function(){
$(document).click(function(e){
var target = e.target;
$(target).dblclick();
}).dblclick(function(){
var selection,
node,
text,
start,
end,
letter;
if (window.getSelection) {
selection = document.getSelection();
node = selection.anchorNode;
if (node.nodeType === 3) {
text = node.data;
start = selection.baseOffset;
end = selection.extentOffet;
if (!isNaN(start)) {
letter = text.substr(start, 1);
}
}
window.getSelection().removeAllRanges()
} else if(document.selection) {
//continue work here
}
if (letter) {
alert(letter);
}
});
});
You could return the innerHTML as well with:
$('.clickable').on('click', function(){
alert($(this).html());
});
As for a more efficient way to do it...maybe try this:
in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter?
You can do it with this script
$('.clickable').on('click', function(){
var html = $(this).text(); // if you want the text inside the span
var index = $(this).index(); // if you want the position among siblings
var classes = $(this).attr('class').split(" ");
var secondClass = getSecondClass(classes);
});
function getSecondClass(classArray){
if(classArray.length<2){
return null;
}else{
return classArray[1];
}
}
I've also included the html and index variables if you want to do something else with the clicked element.
Basically you split the classes of the element by spaces and then check if the array has less than two elements, in that case it returns null, otherwise it returns the second element.
jsFiddle
Well wrapping all text dyanamically with span tag , it is possible what you were looking for
JS
$(function(){
var lengthText = $('#singlecharacter').text().length;
var textValue = $('#singlecharacter').text();
var textArray = textValue.split('');
var newText = new Array();
for (var i = lengthText - 1; i >= 0; i--) {
newText[i] = "<span class='sp'>"+textArray[i]+"</span>";
};
$('#singlecharacter').html(newText);
$('.sp').click(function()
{
alert($(this).text());
});
});
HTML
<div id='singlecharacter'>THIS</div>
DEMO JSFIDDLE

Alert class based on it's length with Javascript/jQuery

So basically I'm trying to select the class "on" only, but based on the class length of 2.
<div class="film cars-0317219 on"></div>
<div class="film wall-e-0910970 on"></div>
<div class="film off up-0945232"></div>
<div class="film on finding-nemo-0266543"></div>
<div class="film off cars-0317219"></div>
Something like:
$('div.film').live('click', function(){
var classes=$(this).attr("class").split(" ");
var status=classes[classes.length=2];
alert(status);
});
Should alert "on"
Any idea how to get the alert based on the string length? (Likewise, if I put 3 instead of 2 in the code, it should alert "off")
var status=classes[1]; // the second element of the array
Better way to do what you want to do:
var isOn=$('.film').hasClass('on');
alert(isOn?'on':'off');
Remember that $('.film') will only get the 1st element with that class when perform these types of operations unless this is in a handler like click in which case you would use $(this)
You should do:
alert(classes[1]);
arrays in javascript are zero based and so the second element has an index of 1 (and the third element has an index of 2)
EDIT - now i understand the OP means the length of the word on (2 letters):
var classes=$(this).attr("class").split(" ");
for (i = 0; i<classes.length; i++){
if (classes[i].length ===2){
alert(classes[i]);
}
}
If you want to alert only classes of a certain length, you can proceed like this
a=['film', 'cars-0317219', 'on'];//same as your var classes;
var status = a.filter(function(x){
return x.length==this.size;
},{size:2});//contains ['on']
However filter is implemented for firefox, I don't know for other browsers.
function something(){
var classSplitOn =" ";
var desiredCount = 2;
var onClassSelector = ".on";
$('.film').each(function(index,elem){
var classString = elem.className;
if(classString && classString.split(classSplitOn).length == desiredCount){
var alertVal = "off";
if($(this).is(onClassSelector)){
alertVal = "on";
}
alert(alertVal);
}
});
}

How to increase div content value?

I want to increase div value +1 in certain events.How can i get div value and increase it?
this.innerHTML = +this.innerHTML + 1;
DEMO
Given:
<div id="x">42</div>
You can do this:
var $x = $('#x');
$x.text(parseInt($x.text(), 10) + 1);
For your education:
.text()
parseInt() (and always include the radix argument)
If the div's HTML is simply a number:
var element = document.getElementById('yourElementID');
element.innerHTML = parseInt(element.innerHTML, 10)+1;
Here you use below code
In javascript
--------------
var demoInt = $('#divInt').text();
demoInt =parseInt(demoInt);
In HTML
-------
<div id="divInt">111</div>

Categories

Resources