0

I have a HTML/JS code as shown below in which on click of Execute button, I want to display:

[{"detail":"Hello World"},{"detail":"Great News"}]

Currently, on clicking Execute button I am getting the following:

[{"detail":""},{"detail":""}]

I am wondering what changes I need to make in the JS code below so that on click of a Execute button, I am able to display:

[{"detail":"Hello World"},{"detail":"Great News"}] 

HTML:

 <input type="submit" onClick="runCode()" value="Execute" >
 <div id="console-log">
 </div>

Javascript:

$(document).ready(function() { 
})

function runCode(){
var td=new Todo()
td.addTask("Hello World")
td.addTask("Great News")
td.printList()
}


class Todo{
    constructor(name) {
        this.todolist = [];
        
        
        this.task={
            'detail':''
        }
      }
    
    addToList(newobj)
    {
        this.todolist.push(newobj)
     
    }
    addTask(taskDetail){
    
                    this.task.detail=taskDetail
            this.todolist.push(this.task)
            this.task.detail='' //clear data for next step
    
    }
    printList()
    {
            var consoleLine = "<p class=\"console-line\"></p>";

            var text= JSON.stringify(this.todolist)
         $("#console-log").append($(consoleLine).html(text));
        //alert(this.todolist)
    }
}
flash
  • 1,455
  • 11
  • 61
  • 132

1 Answers1

1

Push an object created just from the argument into the todolist property:

addTask(detail) {
  this.todolist.push({ detail });
}

The this.task property only makes things more confusing, I'd recommend avoiding it.

function runCode() {
  var td = new Todo()
  td.addTask("Hello World")
  td.addTask("Great News")
  td.printList()
}


class Todo {
  constructor(name) {
    this.todolist = [];
  }
  addTask(detail) {
    this.todolist.push({ detail });
  }
  printList() {
    var consoleLine = "<p class=\"console-line\"></p>";

    var text = JSON.stringify(this.todolist)
    $("#console-log").append($(consoleLine).html(text))
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="submit" onClick="runCode()" value="Execute">
<div id="console-log">
</div>

It would also be trivial to remove the dependency on the big jQuery library if you wanted, it's not accomplishing anything useful. Also, it'd be good practice to use addEventListener instead of an inline handler:

document.querySelector('input').addEventListener('click', () => {
  var td = new Todo()
  td.addTask("Hello World")
  td.addTask("Great News")
  td.printList()
});


class Todo {
  constructor(name) {
    this.todolist = [];
  }
  addTask(detail) {
    this.todolist.push({ detail });
  }
  printList() {
    document.querySelector('code').appendChild(document.createElement('p'))
      .textContent = JSON.stringify(this.todolist);
  }
}
<input type="submit" value="Execute">
<code>
</code>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320