.replace() in jQuery object

Asked

Viewed 12,697 times

3

I have a code that gets a value from an HTML field. I match the value of a variable to the object in jQuery, and then use the value placed there to make some comparisons of >= or <=.

I want to put a zip code mask on the spot, but the dash (99999-999) cuts the numerical value of the zip code to the first 5 digits. I made the following code so that I could take that trace out of play and only mess with the ZIP code numbers, but for some reason it doesn’t work:

var cep = parseInt($('#ip-cep').val.toString().replace(/-/, ''), 10);

Just to clarify, I take the value of the HTML field, turn it into string, remove the trace with .replace(), and then convert back into numeral to make the comparisons.

The point is it doesn’t work. The value of cep always returns as NaN, even with input only numerical values. If I draw the trace with the replace, when the parseInt enters action there should only be numbers in place to be converted, since the mask only allows the user to type numbers.

What am I doing wrong?

2 answers

3


Is using the .val erroneously. The correct syntax is .val():

var cep = parseInt($('#ip-cep').val().toString().replace(/-/, ''), 10);
console.log(cep);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ip-cep" value="71000-123">

0

Opa, I checked here and tested with a local variable, Then I took the value with your own code to test, and it worked! (you can run in the browser to test, just press F12 and go to the Console)

var testeCep = '99999-999';
var cep = parseInt(testeCep.toString().replace(/-/, ''), 10);

That is, the problem is in the method where you take the value, which instead of . val, would be . value (without parentheses), I hope it helped! Follow the code below tested hugs!

var cep = parseInt($('#ip-cep').value.toString().replace(/-/, ''), 10);
console.log(cep);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.