简体   繁体   中英

What is wrong with my Javascript?

This is my jsfiddle(http://jsfiddle.net/mZGsp/). I was trying to answer a question here but my code won't work. Here is the code:

JS

var stateOfClick = null;

function initiateLine(){
    document.getElementById('test').innerHtml = "Started";
}

function endLine(){
    document.getElementById('test').innerHtml = "Line Ended";
}

function createLines(){
  if(!stateOfClick) {
    initiateLine();
    stateOfClick = 1;
  } else {
    endLine();
  }
}

HTML

<body>
    <input type="text" id="test" onclick="createlines()">
</body>

A couple of things,

  • change createlines() to createLines (camel-case).
  • change <element>.innerHtml to <element>.value
  • Inside JSFiddle, don't wrap your code inside a function, as then createLines won't be global which it needs to be for the onclick to work.

Here's a working example .

Not even this simple example will work on jsFiddle. You need to attach the event listener with JavaScript:

document.getElementById("someElement").onclick = function() {
  //Do stuff  
}

For input element you must use the value attribute not the innerHTML field.

function initiateLine(){
    document.getElementById('test').value = "Started";
}

also you've misspelled the innerHTML function (though not the primary problem). innerHTML is used for html elements that can contain other elements such as a div containg ap element. Input and option elements all have a value attribute that can be used to extract or set their values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM