Senior Gamer Senior Gamer - 2 months ago 9
jQuery Question

Jquery white spaces

Alright so Im trying to check if these fields are just blank (white spaces or no informations has been entered) but if I just press space few times inside of them It wont detect them as empty at all, it will just process it normally.

$("form.ajax_call").submit(function(e) {
var name = $.trim($('#project_name').val()),
price = $.trim($('#value_change').val()),
description = $.trim($('#project_description').val());

if (name === '') {
alert("Please enter the project name");
e.preventDefault();
return false;
}
if (price === '') {
alert("Please enter the project price");
e.preventDefault();
return false;
}

if (description === '') {
alert("Please enter the project description");
e.preventDefault();
return false;
}

});

Answer

You could replace the jquery trims with the native JS trim, and replace === "" with length < 1;

$("form.ajax_call").submit(function(e) {
    var name = $('#project_name').val().trim(),
        price = $.trim($('#value_change').val().trim(),
        description = $('#project_description').val().trim();

    if (name.length<1) { 
        alert("Please enter the project name"); 
        e.preventDefault();
        return false;
    }
    if (price.length<1) { 
        alert("Please enter the project price"); 
        e.preventDefault();
        return false;
    }

    if (description.length<1) { 
        alert("Please enter the project description"); 
        e.preventDefault();
        return false;
    }

});