LunaLuna
LunaLuna

Reputation: 61

if-statements keeps returning true

My code in Javascript:

function saveChanges() {
var formData = {
    ProjectId: $('#rz-project').val(),
    ArticleId: $('#rz-article').val()
};

if (formData.ProjectId != null && formData.ArticleId != null)
{
    $.ajax({
        url: baseUrl + 'Time/EditReport',
        type: "post",
        data: { timeReport: formData },
        success: function (result) {
            success("Changed");
        },
        error: function (err) {
            alert(err.statusText);
        }
    })
}
else {   }

Also tried with the !== , but it's the same.

When I debug I can see that the values is null, but it execute the if-statement as it was true.

I've been googling but someone used if($()), but I don't so I don't see the problem? Tried with my validations but because the form isn't posting I couldn't get it to work (got 2 buttons but it treated both as the same so I had to change from posting to just a "html.beginform" with a id).

Upvotes: 1

Views: 81

Answers (2)

Davide Cannizzo
Davide Cannizzo

Reputation: 3134

The values are not null, you must be mistaken. The value of an <input> element can't be null, at most it's just going to be empty, which is what you should check for, as @sifanovi059 suggested.

JavaScript implicitly casts string values to boolean values indicating whether the string isn't empty (str.length > 0), so you can try this:

if (formData.ProjectId && formData.ArticleId)

Upvotes: 2

sifanovi059
sifanovi059

Reputation: 19

Use

if (formData.ProjectId != "" && formData.ArticleId != "")

Upvotes: 2

Related Questions