I want to get only the numbers(123) not the text(confirm), here is my code
<p>123confirm</p> <script type="text/javascript"> $(document).ready(function(){ $('p').click(function(){ var sd=$(this).text(); alert(sd); }); }); </script>
The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.
Answer: Use the jQuery. isNumeric() method You can use the jQuery $. isNumeric() method to check whether a value is numeric or a number. The $. isNumeric() returns true only if the argument is of type number, or if it's of type string and it can be coerced into finite numbers, otherwise it returns false .
I think a RegExp would be a good idea:
var sd = $(this).text().replace(/[^0-9]/gi, ''); // Replace everything that is not a number with nothing var number = parseInt(sd, 10); // Always hand in the correct base since 010 != 10 in js
You can use parseInt
for this, it will parse a string and remove any "junk" in it and return an integer.
As James Allardice noticed, the number must be before the string. So if it's the first thing in the text, it will work, else it won't.
-- EDIT -- Use with your example:
<p>123confirm</p> <script type="text/javascript"> $(document).ready(function(){ $('p').click(function(){ var sd=$(this).text(); sd=parseInt(sd); alert(sd); }); }); </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With