1

I want to set a default value to a variable.

When the body loads it runs a function which needs the variable to get the data.
The form will do the same onchange but the form elements will be hidden and added only if the user wants to see the filter options

My current code is

var grade = document.getElementById('grade').value;

If the id grade isnt available on the first load of the i want the grade to default to 0

2 Answers 2

1

Try this, it should default it to zero.

var grade = document.getElementById('grade') == null ? 0 : document.getElementById('grade').value;
Sign up to request clarification or add additional context in comments.

6 Comments

That will give you an error: "TypeError: Cannot read property 'value' of null"
That should do it, but this feels so unnatural. I really like it better with jQuery: var grade = $('#grade').val() || 0
@landons that's not jQuery-specific syntax. It's just an (ab)use of the lazy or.
@JanDvorak I should have said "Javascript framework." To that extent, all frameworks are "(ab)use[s] of the lazy"
This is a most pointless discussion we're attempting to have here ;)
|
1

Try this:

var grade = 0;
var grade_field = document.getElementById('grade');
if (grade_field)
{
    grade = grade_field.value;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.