最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Binding onchange event using JS (Syntax error) - Stack Overflow

programmeradmin3浏览0评论

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 plete example of what I'm tryign to acplish.

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()

JS FIDDLE

Any help with this would be much appreciated.

Regards,

-B.


EDIT TUE 4 JULY

I ended up pletely 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 ma 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.

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 plete example of what I'm tryign to acplish.

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()

JS FIDDLE

Any help with this would be much appreciated.

Regards,

-B.


EDIT TUE 4 JULY

I ended up pletely 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 ma 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.

Share Improve this question edited Jul 4, 2017 at 10:59 Lewis asked Jul 4, 2017 at 10:03 LewisLewis 2,2045 gold badges34 silver badges55 bronze badges 2
  • Syntax error means that your js is not valid, like the sentence is not a correct part of the JavaScript language, meaning your code does not get executed at all. – Martin Meeser Commented Jul 4, 2017 at 10:10
  • @ Martin Meeser I'm aware of what a syntax error means, I was lack luster on why specifically it was throwing that particular error. – Lewis Commented Jul 4, 2017 at 11:01
Add a ment  | 

4 Answers 4

Reset to default 2
  • You have used ma 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.

    function myFunction() {
    
       var a = document.getElementsByName('field-one')[0];
    
       var b = document.getElementById('box-2');
    
       var c = document.getElementById('dept');
    
       c.setAttribute('onchange', myFunction);
    
       if (b.checked) {
         a.disabled = false;
         a.placeholder = 'Enter Your Full Name.';
       } else {
         a.disabled = true;
         a.placeholder = 'Not Applicable.';
     } 
    
    }
    
    myFunction();
    

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); // semicolon + don't call it

  if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Enter Your Full Name.';

  } else {
    a.disabled = true;
    a.placeholder = 'Not Applicable.';
  }
}

myFunction(); // call the func
@import url('https://fonts.googleapis./css?family=Open+Sans');
* {
  margin: 0;
  padding: 0;
}

h3 {
  color: #fff !important;
  padding-left: 0 !important;
}

#txt-field {
  position: relative;
  height: 100vh;
}

#col {
  width: 40%;
  margin: 0 auto;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.spacer {
  margin-bottom: .5em;
}

.original {
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.3) 100%), url(http://imageshack./a/img661/3954/bwalqa.jpg);
  background-position: center center;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

.txt {
  font-family: "Open Sans", Arial, Helvetica, sans-serif !important;
  font-weight: 200 !important;
  letter-spacing: 4px !important;
  font-size: 26px !important;
  text-transform: uppercase;
  color: #272727;
  padding: .5em;
}

.stretch {
  box-sizing: border-box;
  width: 100%;
}

.shift {
  margin-top: 9%;
}

.boxes {
  box-sizing: border-box;
  width: 100%;
  margin: auto;
  padding: 1.5em;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.6) 0%, rgba(0, 0, 0, 0.6) 100%);
  margin-top: 1.5em;
}


/*Checkboxes styles*/

input[type="checkbox"] {
  display: none;
}

input[type="checkbox"] + label {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 20px;
  font: 14px/20px 'Open Sans', Arial, sans-serif;
  color: #ddd;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

input[type="checkbox"] + label:last-child {
  margin-bottom: 0;
}

input[type="checkbox"] + label:before {
  content: '';
  display: block;
  width: 20px;
  height: 20px;
  border: 1px solid #6cc0e5;
  position: absolute;
  left: 0;
  top: 0;
  opacity: .6;
  -webkit-transition: all .12s, border-color .08s;
  transition: all .12s, border-color .08s;
}

input[type="checkbox"]:checked + label:before {
  width: 10px;
  top: -5px;
  left: 5px;
  border-radius: 0;
  opacity: 1;
  border-top-color: transparent;
  border-left-color: transparent;
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
}

.selectpicker {
  margin: 3em 3em;
}
<div id="txt-field" class="original box">

  <select title="Please Select" class="selectpicker" name="dept" id="dept" required="true">
    <option value="">Choose...</option>
    <option value="1">Winter</option>
    <option value="2">Spring</option>
    <option value="3">Summer</option>
    <option value="4" selected="selected">Autumn</option>
  </select>

  <div id="col">

    <h3 class="txt spacer">Dynamic input, based on checkbox state...</h3>
    <input type="text" name="field-one" class="txt stretch" />

    <div class="boxes">
      <input type="checkbox" id="box-2" onChange="myFunction()" checked>
      <label for="box-2">Apply a name?</label>
    </div>
  </div>
</div>

You have a syntax error in your code. This:

 // Bind onchange event.
  c.setAttribute('onchange', myFunction()),

Please change to this:

// Bind onchange event.
  c.setAttribute('onchange', myFunction);

Also, when calling function, omit the keyword function: So, call it like this:

myFunction();

You are missing semi-colon (;). Remove the ma and replace it with a semi-colon. Look at this working fiddle. That Should be

// Bind onchange event.
  c.setAttribute('onchange', myFunction());

and remove the last line i.e

function myFunction()

EDIT

Remove this line.

c.setAttribute('onchange', myFunction());

Call the funtion at the end like

myFunction();

Keep the inline binding i.e onchange="myFunction()"

Here's the updated fiddle: https://jsfiddle/9fzqegso/26/

You have at least 2 issues

1) this must end with a semi colon:

Incorrect:

  c.setAttribute('onchange', myFunction()),

Corrected:

  c.setAttribute('onchange', myFunction());

2) Function must have a body:

Incorrect:

function myFunction()

Corrected:

function myFunction(){
//future codes here

}

I moved this codes into the function (myFunction) for it to work:

    // Text field element.
  var a = document.getElementsByName('field-one')[0];


  // Checkbox element.
  var b = document.getElementById('box-2');
    if (b.checked) {
    a.disabled = false;
    a.placeholder = 'Enter Your Full Name.';

  } else {
    a.disabled = true;
    a.placeholder = 'Not Applicable.';
  }
发布评论

评论列表(0)

  1. 暂无评论