Question

I'm trying to remove/add the disable attribute to my button with the id of 'register'. This is the code I've tried, but it doesn't work..

$(document).ready(function() {

 $('.tos').click(function(){
    var isChecked = $('.tos').is(':checked');
    if(isChecked)
      console.log("True");
      $('#register').removeAttr("disabled");
    else
      console.log("False");

  });

});

I get this error in my console, but I have no idea what it means.

Uncaught SyntaxError: Unexpected token else 

This is the button I want to remove/add the disabled attribute to.

<button type="submit" id="register" name="register" class="btn btn-block btn-color btn-xxl" disabled>Create an account</button>

Any help would be appreciated!

Was it helpful?

Solution

Uncaught SyntaxError: Unexpected token else

This is because you haven't used {} syntax in your if statement. Not using them is fine, but only when you have one line to execute. In this case, your else is the second line and is breaking the "only one line without curly brackets" rule.

Use curly brackets:

if(isChecked) {
      console.log("True");
      $('#register').removeAttr("disabled");
} else
     console.log("False");

OTHER TIPS

You don't have braces around the first if body. Should be:

if(isChecked) {
      console.log("True");
      $('#register').removeAttr("disabled");
}
    else {
      console.log("False");
}

Technically the second set of braces are optional, but it's worth using them

if(isChecked)
  console.log("True");
  $('#register').removeAttr("disabled");
else
  console.log("False");

What is that?


if(isChecked){
  console.log("True");
  $('#register').removeAttr("disabled");
}else{
  console.log("False");
}

Now this is how you do it correctly ;)

For if else statements, you can use one of these two syntaxes:

//either....
if (condition)
    one_action();
else
    one_other_action();
//or....
if (condition) {
    one_action()
    more_actions()
} else {
    one_other_action();
    and_some_more();
}

So, you can omit the {} around the block of actions to do when the condition is true only if the block contains a single action. Since you're doing a console.log and a jQuery function, the if else statements are interrupted, and JavaScript no longer recognises that you're in it. Because of that, it won't see the else coming. To make this work, simply put {} around it like the other answers show.

dont forget {...}

$('.tos').click(function(){
    var isChecked = $('.tos').is(':checked');
    if(isChecked){
      console.log("True");
      $('#register').removeAttr("disabled");
    } else {
      console.log("False");
    }
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top