I've recently been spending some time playing with javascript event listeners in an attempt to learn a little more. However I've kinda hit a road block.
I appear to be getting a syntax error, SyntaxError: expected expression, got keyword 'if'.
The Question
If someone could elaborate and explain my mistake to me, I would be thankful. See the Js Fiddle for a more complete example of what I'm tryign to accomplish.
I've attempted to read up a bit more using MDN (This Article Imparticular) as highlighted by the console. However I'm failing to understand, my error and how it coinsides with this article.
function myFunction() {
// Text field element.
var a = document.getElementsByName('field-one')[0];
// Checkbox element.
var b = document.getElementById('box-2');
// Select Element
var c = document.getElementById('dept');
// Bind onchange event.
c.setAttribute('onchange', myFunction()),
if (b.checked) {
a.disabled = false;
a.placeholder = 'Enter Your Full Name.';
} else {
a.disabled = true;
a.placeholder = 'Not Applicable.';
}
}
function myFunction()
Any help with this would be much appreciated.
Regards,
-B.
EDIT TUE 4 JULY
I ended up completely reworking this to try and get things a little smoother. With some help from you all I was able to clarify I few things.
especially the key points highlighted by, @Kind User & @Shaminder S Aujla.
- You have used comma instead of semicolon.
- If you want to call the function, use just the name of the function.
- Don't call the function while binding it.
- Calling it like
myFunction();will throw "Too much recursion error".
The resulting change is shown below and you can also see my finished fiddle here;
window.addEventListener('load', function() {
// Select Element
var c = document.getElementById('dept');
// Text field element.
var a = document.getElementsByName('field-one')[0];
// Bind onchange event.
c.onchange = function() {
if (this.options[this.selectedIndex].value == 3) {
a.disabled = false;
a.placeholder = 'Enter Your Full Name.';
} else {
a.disabled = true;
a.placeholder = 'Not Applicable.';
}
}
})
Thanks again all, really appreciate it. :)
Regards, - B.