Home >Web Front-end >JS Tutorial >Javascript converts string type to int type_javascript tips

Javascript converts string type to int type_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:14:221237browse

Here comes the depressing thing, first look at the front-end HTML:

Copy code The code is as follows:

Purchase Quantity:
pieces (in stock <%=GOODSNUM%>)

Use JS to get the value, pay attention to the JS code:
Copy code The code is as follows:

var num = document.getElementById("txtNum").value;
var goodsnum = document.getElementById( "getGoodsNum").innerHTML;

You will find that the value methods of txtNum and getGoodsNum are different.
txtNum uses .value, getGoodsNum uses .innerHTML.
Because getGoodsNum uses the span tag and txtNum is the text box.
span, table, and div have no value, so innerHTML is used to obtain the value.
txtNum belongs to the text box, label, and drop-down box all have value.
Now everyone understands.
Now let’s compare the two numbers. Everyone must be thinking that now we have obtained these two numbers.
Please see the JS code:
Copy code The code is as follows:

if (num > ; goodsnum) {
alert("The shopping quantity cannot be greater than the inventory quantity!");
return false;
}

Looking at it this way, there should be no problem. Comparing the two numbers, Then I input the data and compare. Enter num as 100 and goodsnum is 90. Verify that it is normal. Then num loses 90 and goodsnum loses 100. Verification, something went wrong, it prompted "The purchase quantity cannot be greater than the inventory quantity!" 》. What's going on? Then use alert to output the two parameters, yes, and then think about it. By the way, are these two numbers of string type? How could I forget? My brain is short-circuited. Convert it.
Two methods are now provided, One:
Copy code The code is as follows:

if ((num / 1) > (goodsnum / 1)) {
alert("The purchase quantity cannot be greater than the inventory quantity!");
return false;
}

In this way, it is OK to remove 1, but it is difficult to verify.
Two:
Copy code The code is as follows:

if (parseInt(num) > ; parseInt(goodsnum)) {
alert("The shopping quantity cannot be greater than the inventory quantity!");
return false;
}

Verification OK, passed, solved.
Author: Mr S.R Lee
Source: http://www.cnblogs.com/LeeYongze
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn