Removing an integer from an id - javascript

I have an id:
div id ="untitled-region-5"
I want to grab that id and remove 4 from it and then do some code with the new id.
So far I am trying something like this from reading about how to perform this:
var n = $(this).attr('id').match(/untitled-region-(\d+)/)[1];
But I don't know how to remove 4 from the integer.

It's still a string, that's why you can't easily use it in math. Some operations work, because they will implicitly convert the value to a number.
Use parseInt to explicitly do the conversion, so that you know what you have:
var n = parseInt($(this).attr('id').match(/\d+$/)[0]);
n -= 4;

var id = $("div").attr("id");
var n = parseInt(id.substring(id.lastIndexOf("-") + 1), 10);
I made a jsFiddle too: http://jsfiddle.net/YEWQQ/

<div id ="untitled-region-5">​
just take n and subtract 4
var n = $('div').attr('id').match(/untitled-region-(\d+)/)[1];
var newNumber = n-4;
$('div').attr('id','untitled-region-'+newNumber);

Related

Simple JS function using text inputs and parseInt, returns NaN

Can anyone help me figure out why I keep getting a NaN result?
function showShares() {
var tot = document.getElementById('total').innerHTML;
var pri = document.getElementById('price').innerHTML;
var per = document.getElementById('percent').innerHTML;
var shar = parseInt(tot, 10) * parseFloat(per) / parseFloat(pri);
document.getElementById("shares").innerHTML=Math.round(shar);
}
<td><text id="price"><%= StockQuote::Stock.quote(current_user.fund1).last %></text></td>
<td><text id="shares"></text></td>
<td><text id="percent">.50</text></td>
<p class="alignright1"><input type="text" id="total" size="8"></input>
<br><a href onclick="showShares()">here</a>
The stock quote is returning an integer in the cell ie. 25.38. it returns the same NaN if I remove the embedded ruby and place a simple integer ie. 50. The same is true if I replace the input with a number.
Thank You
Try this :
function showShares() {
var tot = document.getElementById('total').innerHTML;
var pri = document.getElementById('price').innerHTML;
var per = document.getElementById('percent').innerHTML;
var shar = parseInt(tot, 10) * parseFloat(per, 10) / parseInt(pri, 10);
document.getElementById("shares").innerHTML=Math.round(shar);
}
The percent value is a float (digit with comma) and must be interpreted by the JS engine like a float ;)
You are trying to get a value from an input element with this code,
document.getElementById('total').innerHTML
That's not the way to get the value from the input. You should use this code,
document.getElementById('total').value

How to add one to a variable to make 2 not 11

Currently this makes 11. It's for a slideshow and the var "n" equals 1 by default
function forward() {
document.getElementsByClassName("img")[0].setAttribute("class","imgout");
setTimeout( function() {
var n1 = document.getElementById("img").getAttribute("data-number");
var n=n1+1;
document.getElementById("img").setAttribute("data-number", n);
document.getElementById("img").setAttribute("src", "images/" + n + ".jpg");
document.getElementsByClassName("imgout")[0].setAttribute("class","img");
}, 500)
}
Use parseInt():
var n = parseInt(n1, 10) + 1;
Instead of:
var n=n1+1;
When n1 will be a string, because it came from the DOM, you need to convert n1 to an integer. There are many ways to do this, and really you should probably use a regular expression to validate that n1 contains what you expect first, but that being said you can try any of the following:
var n=parseInt(n1, 10)+1;
var n=(n1*1)+1;
var n=(+n1)+1;
As an aside the regex for validating the input from the DOM might be something such as:
/^-?\d+$/
Use Number():
var n = Number("1");
FIDDLE
parseInt - good choice. Also you can do
var n = n-0+1
Just remember that of you have different types "+" will convert to string and "-" will convert to numbers
Convert n1 to number as it is a string like ~~n1. The ~~n1 form is good if you know you want an integer (a 32-bit integer).
Second way is to use Number() function i.e. Number(n1) will convert n1 value into a string.
var n=parseInt(n)+1;
Documentation
Fiddle

Addition not working in Javascript

I'm really new to Javascript and trying to create a form where I'm running into some trouble...
When I use + it does not add up to the value, instead it just puts it back to back. Ex: 5+10 (510)
Here's my code if you want to take a look at it. I'd appreciate any help since I can't figure this out on my own.
var service = document.getElementById("service");
var serviceprice = service.options[service.selectedIndex].id;
var tech = document.getElementById("tech");
var techprice = tech.options[tech.selectedIndex].id;
var hours = document.getElementById("hours").value;
// The error happens here
var total = techprice * hours + serviceprice;
I also have an html part which the script gets the data from.
That happens whenever you have a string rather than a number. The + operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt takes an argument to specify the base. You almost always want base 10.
Try changing this line:
var total = techprice * hours + serviceprice;
to
var total = techprice * hours + parseFloat(serviceprice);
I suspect 'servicePrice' is a string, and it will then try to concatenate the first value (let's say: 100) with the second value (which is, not a number, but a string, let's say 'test'), the result being '100test'.
Try to convert the string to int first with parseInt or to float with parseFloat
This is not especially elegant, but I find it simple, easy, and useful:
var total = -(-techprice * hours - serviceprice);
or even:
var total = techprice * hours -(-serviceprice);
They both eliminate the ambiguous + operator.

Performing mathematical operations on attribute value

I am attempting to perform mathematical operations with JavaScript on values obtained from an attribute. The attribute is created via a PHP loop. I will give an example of one of the html tags containing the attributes, but keep in mind that there are many of these tags which contain unique attribute values.
The HTML:
The JavaScript(jQuery):
$("a[href^='secondary_imgs.php']").click(function(){
var pageWidth = $(window).width();
var maxshadowWidth = (Math.floor(pageWidth * 0.91808874)) - 2;
var mWidth = $(this).attr("mwidth");
var maxSecondaryWidth = mWidth + 60;
alert (maxSecondaryWidth);
if(maxSecondaryWidth <= maxshadowWidth) {
var shadowWidth = maxSecondaryWidth;
} else {
var shadowWidth = maxshadowWidth;
}
var shadowboxrel = 'shadowbox;width=' + shadowWidth;
$(this).attr('rel', shadowboxrel);
The operation doesn't seem to be working, and I have a feeling it has to do with my lack of experience using mathematical operations in javascript. In this case, I think something is wrong with my method of using the attribute value, in the mathematical operation.
For example, the above width attribute is defined as 593. I define the maxSecondaryWidth as mWidth + 60. I fired an alert to see what value I was getting. It should have been shown as 653, yet the value that is 'alerted' is 59360. Obviously I don't understand how to add, as the + is concatenating the two values, as opposed to adding them together. Could it have to do with needing to transform the attribute value from a string into an integer?
You have to convert to a number using parseInt(), otherwise + will do string concatenation:
var mWidth = parseInt($(this).attr("mwidth"), 10);
If the attribute can also be a float, use parseFloat() instead of parseInt().
Do this to make sure mwidth is a number:
var mWidth = parseInt($(this).attr("mwidth"), 10);
Otherwise, + will perform a string concatenation. Alternatively, if you need mwidth to be a floating point number, do this:
var mWidth = parseFloat($(this).attr("mwidth"));
You can do a couple things:
parseInt(mWidth, 10); // int
parseFloat(mWidth); // float
Number(mWidth); // number
otherwise javascript will believe it's a string.
Some less common conversions:
mWidth | 0; // int (javascript bitwise operations are 32-bit signed intergers)
+mWidth; // force Number
i think that you must do something safer (as it is always better);
You should check if it is a number or not:
DOM:
JS:
$("a[mwidth]").each(function(){
var $attr = $(this).attr('mwidth');
if(!isNaN($attr)){
sum += (parseInt($attr));
}
});
If you remove the condition the results will be NaN
Take a look at : http://jsfiddle.net/zVwYB/

jQuery / javascript variable in if statement not working

I have a variable as such:
var is_last = $('.paging a:last').attr('rel');
this returns '-400' which is correct.
However, i need to add 200 to this so the answer is '-200'
if i do this:
var is_last = $('.paging a:last').attr('rel')+200;
the variable is now '-400200'
How can i pass the variable as a value?
A.
You need to parse the output of .attr(), it to an integer first using parseInt() so you're dealing with a number (and not a string), like this:
var is_last = parseInt($('.paging a:last').attr('rel'), 10) + 200;
I reckon that #Nick Craver is correct and that parseInt is the more correct answer, but as a quick-and-dirty alternative you can also convince javascript that a variable is a number and not a string by multiplying by 1:
var x = parseInt("-400", 10) + 200;
var y = ("-400" * 1) + 200;
alert(x);
alert(y);

Categories

Resources