2

Is it possible to put an if statement within an Array Declaration?

Code:

dayOfWeek = [if($('#sunday').checked()){$('#sunday').val()}];

Browser error: Uncaught SyntaxError: Unexpected token if.

I tried too:

$('#domingo').checked() ! $('#domingo').val() : 0

Browser error: Uncaught SyntaxError: Unexpected token !

EDIT

As @bažmegakapa answered the code that works with no error is:

diasSemana = new Array($domi.is(':checked') ? $domi.val() : null, $lun.is(':checked') ? $lun.val() : null);

This did not work:

$('#domingo').checked() ? $('#domingo').val() : 0

Browser showed this error: Uncaught TypeError: Object [object Object] has no method 'checked'

Regards!

1
  • Use [] instead of new Array(). Commented Jun 3, 2013 at 19:05

2 Answers 2

4

What you need is called the ternary or conditional operator:

$('#domingo').checked() ? $('#domingo').val() : 0

However, it is not a good idea to query the DOM twice for the same element. Save the resulting jQuery object into a variable beforehand and reuse it:

var $domi = $('#domingo');
dayOfWeek = [$domi.checked() ? $domi.val() : 0];

I don't know what .checked() is, maybe you meant .is(':checked').

Some fiddle demo to play with

Sign up to request clarification or add additional context in comments.

2 Comments

great answer! The first approach showed me an error but second worked fine. Regards
@eyyo Yep, the error is due to the .checked() function which does not exist :).
4

Try using the javascript ternary operator, documented here:

$('#domingo').checked() ? $('#domingo').val() : 0

1 Comment

This code is showing me this error: Uncaught TypeError: Object [object Object] has no method 'checked'. Thanks anyway

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.