2

I am building an HTML line in jQuery to append to a table in the HTML and want to capture when the input value changes. I am trying to pass a variable obj.attNewChum in the onchange attibute as follows:

contents = contents + "<input type='text' id='" + obj.cdId + "' name='" + obj.cdId + "' value='" + attMeeting + "' onchange='attendanceUpdateFunction(this.id, this.value, "+obj.attNewChum+")'>";

However, this gives the following error in the console:

Uncaught ReferenceError: N is not defined
    at HTMLInputElement.onchange (Attendance.html:1)

attendanceUpdateFunction(this.id, this.value, N)

The variable obj.attNewChum does contain the value N.

I have tried putting the variable in quotes:

contents = contents + "<input type='text' id='" + obj.cdId + "' name='" + obj.cdId + "' value='" + attMeeting + "' onchange='attendanceUpdateFunction(this.id, this.value, "+"\"'obj.attNewChum'\""+")'>";

And that gives the following error in the console:

Uncaught SyntaxError: Invalid or unexpected token
Pinke Helga
  • 6,378
  • 2
  • 22
  • 42
Glyn
  • 1,933
  • 5
  • 37
  • 60
  • `console.log(obj);` could give you an idea what actually happens. (Should be added to your question as well in order to know what we are speaking about.) – Pinke Helga Jan 11 '19 at 04:10
  • convert double quotes into single quotes and single to double – PHP Geek Jan 11 '19 at 04:34

2 Answers2

1

The best alternative would be to attach the listener properly using Javascript instead, without using inline handlers, that way you don't have to deal with any escaping issues:

const input = $("<input>")
  .prop({
    id: obj.cdId,
    name:  obj.cdId,
    value: attMeeting
  });
input.on('change', function() {
  attendanceUpdateFunction(this.id, this.value, obj.attNewChum);
});

Note that this results in the input being a jQuery object rather than a string, so rather than concatenating the new HTML, you would want to .append the new element.

If, by chance, you're just using the id to try to pass the obj.cdId to attendanceUpdateFunction, you might consider removing the id entirely and just use the plain reference to cdId:

const input = $("<input>")
  .prop({
    name:  obj.cdId,
    value: attMeeting
  });
input.on('change', () => {
  attendanceUpdateFunction(obj.cdId, input.val(), obj.attNewChum);
});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Use as follows

 contents = contents +'<input type="text" id="'+obj.cdId+'" name="'+obj.cdId+'" value="'+attMeeting+'" onchange="attendanceUpdateFunction(this.id, this.value, \''+obj.attNewChum+'\'")">';
ChandraShekar
  • 386
  • 5
  • 12