Reputation: 981
To be honest, I think I just have to convert the values to integers, but I've tried a bunch of things and keep getting 'NaN' or something along the lines of 'cannot use this action on an object'. I want to do things like use replace to remove the % or simply apply math to it. I have tried String and parseInt() to try to convert but just get NaN.
This example gives me an alert box that says "10%" or "20%"...whatever the user types in
thisInvoiceDiscount = $("#clientSearchInvoiceDiscountTextbox").val();
percentPresent = thisInvoiceDiscount.indexOf("%");
if (percentPresent == "-1") {
}
else {
alert (thisInvoiceDiscount);
//I can't seem to do anything with thisInvoiceDiscount here
}
UPDATE: Using the 1st response:
thisInvoiceDiscount = $("#clientSearchInvoiceDiscountTextbox").val();
var numberOnly = $("#clientSearchInvoiceDiscountTextbox").val().replace(/\D/g, '');
percentPresent = thisInvoiceDiscount.indexOf("%");
if (percentPresent == "-1") {
}
else {
var integerValue = parseInt(numberOnly, 10);
alert (integerValue);
}
Upvotes: 0
Views: 64
Reputation: 150273
var numberOnly =
$("#clientSearchInvoiceDiscountTextbox").val().replace(/\D/g, '');
This will strip out every non digit char from the string.
var integerValue = parseInt(numberOnly, 10);
This will parse the string to an integer.
Of course you can make the regex
more specific targeting the %
sign:
var numberOnly =
$("#clientSearchInvoiceDiscountTextbox").val().replace(/%/, '');
Or this regex
to remove %
only if it's the last char in the string:
var numberOnly =
$("#clientSearchInvoiceDiscountTextbox").val().replace(/%$/, '');
Live DEMO (based on the update)
Note that, you better compare to an int number than a string when comparing to an indexOf
result, it will add a (very small...)boost to your code and the code won't brake if you compare with ===
Upvotes: 3