1

I'm getting syntax errors while trying to add an if/else statement the onclick attribute. What is the syntax for this?

<div onclick="var element = $('#selector'); if (element.val() == 'something') { alert('hello'); } else { alert('goodbye'); } ">
    Click here 
    <input type="hidden" id="selector" value="something" />
</div>

...and yes, I must have this javascript in the onclick attribute (can't move this to a function).

0

2 Answers 2

5

.val() is a jQuery method. You want to access the value property of the DOM element.

if (element.value == 'something') { 

Or create a jQuery object if you have jQuery loaded:

if ($(element).val() == 'something') { 

If you took that approach, you could always use a jQuery selector:

if ($('#selector').val() == 'something') { 
Sign up to request clarification or add additional context in comments.

2 Comments

sorry, got mixed up since I'm using jQuery. I've updated my code sample, but that's still not the problem I'm having.
@Andrew - I don't get any errors using your code. What do the errors say, and which browser are you using? Also, are you sure you have jQuery loaded?
2

Javascript DOM elements do not have a val() function. (Are you thinking of jQuery?)

Change .val() to .value.


If you are thinking of jQuery, you can write if ($('#selector').val() == 'something').

1 Comment

sorry, got mixed up since I'm using jQuery. I've updated my code sample, but that's still not the problem I'm having.

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.