Reputation: 1555
I'm trying to refactor my js code to be more dry-conventioned, but stuck this error. Here is my code
function validate_field(e){
console.log(typeof e);
$(e).focusout(function(e){
var price = $(e).val();
var number = parseInt(price, 10);
console.log(number)
if (number < 0)
{
$(e).val(0);
}
})
}
$(function(){
validate_field('#price');
})
According to stacktrace error is somewhere here var price = $(e).val();
What am i missing here?
Upvotes: 1
Views: 2126
Reputation: 1212
Reassigning the variable is causing problem.
function validate_field(field){ // both variable should not be same e & 'e' of inside function
console.log(typeof e);
$(field).focusout(function(e){
var price = $(field).val();
var number = parseInt(price, 10);
console.log(number)
if (number < 0)
{
$(field).val(0);
}
})
}
$(function(){
validate_field('#price');
})
or
can use the below code directly without calling other function in script
$(function(){
$('#price').focusout(function(e){
var price = $(this).val();
var number = parseInt(price, 10);
console.log(number)
if (number < 0)
{
$(this).val(0);
}
})
});
Upvotes: 0
Reputation: 2620
try
function validate_field(e){
console.log(typeof e);
$(e).focusout(function(ev){
-------------------------------^ here you are redeclaring the e previously passed as selector
var price = $(e).val();
var number = parseInt(price, 10);
console.log(number)
if (number < 0)
{
$(e).val(0);
}
})
}
$(function(){
validate_field('#price');
})
Upvotes: 5
Reputation: 10040
You are interfering the e
argument with e
variable of function. It should be :
function validate_field(s) { // here also ? I have set "s" as parameter, you can set any word you like
console.log(typeof s); // noticed the difference here?
$(s).focusout(function(e) { // noticed the difference here?
var price = $(this).val();
var number = parseInt(price, 10);
console.log(number)
if (number < 0)
{
$(e).val(0);
}
});
}
You can also change your event argument for minor change as @dakait did.
Upvotes: 4