jQuery Removing last two characters in a class - javascript

This should be pretty simple. I'm trying to use the slice method to remove the last two characters in a dynamically created string in a shopping cart.
So instead of having a product show as $28.00, I want the product to show up as $28. Since these values are coming from a database, I can't simply define the string in a variable, like I've seen in a lot of tutorials.
I've created a JSFiddle here:
http://jsfiddle.net/EbckS/
The jQuery that's not working is below:
$(".myclass").slice(0,-2);

You should use text.
$(".slice").text(function(i, text) {
return text.slice(0, -2);
});
i Reffers the index position of the element in the set
text Reffers the old text value
Refference

Very Simple. I uses this for getting number from a string you can use it too.
var height= "800px";
var newheight = height.substring(0,height.length-2); //string 800
newheight= parseFloat(newheight) || 0; //number 800

Related

How to change the value of innerText at a particular index?

I am trying to change the string displayed in the frontend by using a function in javascript.
let displayword = document.getElementById("displayword”)
console.log(displayword.innerText) //apple
Say, I want the change the letter “l” to something else say “i” but keep the rest of the letters unchanged how do I go around this?
Things I have tried
displayword.innerText[3] = “i” // -----does nothing----
I am confused why the above code using index does nothing, while the below does something
dash.innerText += “i” //applei
Extra question: Why does the above code using =+ change the formatting of the innerText? I want to keep the large font but it changes to regular font of the element (here I am using h1).
Thank you:)
You should look at the String documentation, especially String.slice and String.substring
In many languages, Strings can't be modified directly. Instead you "change" it by creating a new string composed of parts of the original.
As for how you'd do it in your case:
var text = displayWord.innerText;
text = text.slice(0, 3) + 'i' + text.slice(4) // apple -> appie
displayWord.innerText = text;
[Edited code slightly]
displayword.innerText = displayword.innerText.replace(oldCharacter, newCharacter);
To replace all occurrences:
displayword.innerText = displayword.innerText.replaceAll(oldCharacter, newCharacter);

google apps script counting characters in a cell

I am trying to find a way to adjust a merged cell group to show all text characters that were contained in the first cell when merged. I thought there would be a simple way to count the number of characters in that first cell and then I can adjust the height of a cell or cells by developing a formula (such as add .2 for each 30 characters).
I am using the following code to try and count the characters:
var tempValue;
var tempCount = 0;
tempValue = sprintSheet.getRange("D3").getDisplayValue();
tempCount = tempValue.length();
Unfortunately, I get the following error on the last line:
TypeError: Cannot call property length in object
I can't seem to make the transition from range / value to text to use the length property.
Short answer
Use tempCount = tempValue.length instead of tempCount = tempValue.length();
Explanation
Google Apps Script is based on JavaScript. The getDisplayValue() returns an a JavaScript string primitive. A primitive data type can use the the length property, and its called by using .length, (note that parenthesis are not used).
References
https://developers.google.com/apps-script/overview
The string length is available as a property rather than as a function call.
https://www.w3schools.com/jsref/jsref_length_string.asp
tempCount = tempValue.length;

Select a number in a div tag and subtract it from 59 and display the result in text

I am trying to select a price listed by class "ProductPrice" and subtract it from $59 to display a free shipping message but cannot get it to select the product price. Where am I going wrong?
<div><em class="ProductPrice">$16.95</em></div>
<script>
var cart = document.getElementByClassName("ProductPrice").replace('$', '');
var test = 59 - cart;
document.write('<div>Add $' + cart + 'to your cart to get free shipping.</div>');
</script>
You are selecting the DOM element which class is ProductPrice and you then try to use the replace function on it. But the problem is that the replace function is a method from the String class.
So you should first get the string value of the text contained in the element, which is:
document.getElementsByClassName('ProductPrice')[0].textContent.replace('$', '')
You could also use the innerHTML property which would get you the HTML code instead of the text value.
Also, as you can see, the function is getElementsByClassName and it returns an array of all elements with this class.
Finally, you might want to display a correct number of decimals in the resulting test variable with the help of the Number.toFixed method.
EDIT: Javascript should be smart enough to cast the string to a Number before doing the math, but in case you want to make sure, you can use parseFloat(string) to get the floating point number value of the string.
A couple of things to keep in mind.
You should use getElementsByClassName instead of getElementByClassName.
Access the particular element with bracket notation. To get the first element, append [0]
Call innerHTML before replace.
<div><em class="ProductPrice">$16.95</em></div>
<script>
var cart = document.getElementsByClassName("ProductPrice")[0].innerHTML.replace('$', '');
var promotion = 59 - cart;
document.write('<div>Add $' + promotion + ' to your cart to get free shipping.</div>');
</script>
Edit: It's probably better to use textContent instead of innerHTML.
Your answer would be:
var cart = parseFloat(document.getElementsByClassName("ProductPrice")[0].innerHTML);
var test = 59 - cart;
document.write('<div>Add $' + cart + 'to your cart to get free shipping.</div>');
parseFloat takes in a string value as a parameter and converts it into a float starting from the first number and continuing until it reaches a non-number. For example, your $16.95 (string) would become 16.95 (number). Also, getElementsByClassName returns an array of all elements with the class name "ProductPrice" so you will have to reference the first index in that array. Hope this helps!

What am I doing wrong running a jquery function on each item of a class?

I'm trying to make a line separator that will have a bit of text as a title and then follow the text with a strike-through to the edge of the page. I thought I was writing the bit of jquery properly to call the function on each instance of my separator div but apparently I'm not.
Here's what I thought it should be:
$(".separator").each(function() {
var linewidth = 706 - $(".s-text").width();
$(".s-line").width(linewidth);
});
See fiddle here: http://jsfiddle.net/WY7tL/
Solution
You must specify which .s-text element you want to select, in this case, the child of the selected .separator.
Explanation
$.each(), or $('selector').each() will loop through all the elements corresponding to the selector query that you provide it.
Each time it goes into the loop, the specific element corresponding to the index of the array of corresponding elements is selected and assigned to the variable this.
this is a DOMElement, not a JQuery object. This is why we put it within parenthesis, calling the JQuery ($) object on it: $(this).
JavaScript/jQuery
$(".separator").each(function()
{
var linewidth = 706 - $(this).find(".s-text").width();
$(this).find(".s-line").width(linewidth);
});
Pure JavaScript
var sep = document.getElementsByClassName('separator');
for (var i in sep)
{
if(sep[i].nodeType==1)
{
var linewidth = 706 - sep[i].querySelector('.s-text').offsetWidth;
sep[i].querySelector('.s-line').style.width = linewidth+"px";
}
}
JQuery Live Demo
Pure JavaScript Demo
Performance comparison
http://jsfiddle.net/WY7tL/1/
You have to call $(this).children('.class')
Look at the code in the fiddle
You need to fetch the relevant element from inside your .separator by calling find() on it
$(".separator").each(function() {
var linewidth = 706 - $(this).find(".s-text").width();
$(this).find(".s-line").width(linewidth);
});

Extracting specific text from select option boxes

It's possible I'm just misusing .filter() here, but I've been trying to extract a particular piece of text from javascript option boxes without much success.
In short, each of my option boxes has a bunch of info, then, in brackets, ([x] items left in stock).
I'd like to extract that [x], but I can't seem to get any sort of regular expression filtering working in jQuery - or, perhaps, I'm doing it wrong.
In short, if anyone could complete the below, I'd be very appreciative:
$('.productSelect').change(function() {
selectedItem = $(this + 'option:selected').text();
# Now grab the integer "x" inside the ([x] items left in stock) part of the text
[ your code here]
});
Any help very appreciated.
Something along these lines:
$('.productSelect').change(function() {
selectedItem = $(this + 'option:selected').text();
# Now grab the integer "x" inside the ([x] items left in stock) part of the text
var n = selectedItem.match(/(\()(\d+)(\))/)[2];
});
Of course, this expression depends on the fact that your data is formatted as (number) string
This should get you what you need.
var pattern=/\[(\d+)\] items left in stock/;
var qty = pattern.exec(selectedItem)[1];
So you should use the JavaScript string.match function
var s = "[100] items left in stock";
var p = s.match(regexp);

Categories