skip to Main Content

I have a variable VISIT_ID that containing value including space as Visit 1. I have passed this variable in the below onclick function. This return statement is used inside the javascript datatable column.

var Cols = [
    {
        "mData": "VISIT_ID", "sDefaultContent": "", "mRender": function (data, type, index, row) {
            return data;
        }
    },
    {
    "mData": "ALERT_ACTION", "sDefaultContent": "", "mRender": function (data, type, index, row) {
        return "<label>Not Reviewed</label><i onclick = OpenAlert('" + index.VISIT_ID + "') data-toggle='tooltip' data-placement='top'></i>";
     }
];

But while clicking on it. I’m getting this error:

Uncaught SyntaxError: Invalid or unexpected token

When I console this method. I get the result as this:

OpenAlertActionOverlay('Visit 1')

But if we console event.target, its result is coming as:

enter image description here

$(document).on('click', function (event) {
    console.log('event.target', event.target);
}




         

2

Answers


  1. This must be due to unaccounted use of ' or ". To avoid keeping track of all these quotes you can use Template_literals

    return `<label>Not Reviewed</label>
            <i onclick = OpenAlert("${index.VISIT_ID}") 
               data-toggle='tooltip' data-placement='top'>
            </i>`;
    
    Login or Signup to reply.
  2. Trying to mash strings together to form something with JavaScript inside HTML using JavaScript is hard and fragile. Avoid doing it if at all possible.

    Both standard DOM and jQuery have tools for generating DOM objects: Use them!

    You code will be more verbose, but a lot more readable.

    ...function (data, type, index, row) {
    
      function openAlert() {
        openAlert($(this).data('visit-id'));
      }
    
      const label = jQuery("<label />").text("Not reviewed");
      const italic = jQuery("<i />")
        .on("click", openAlert)
        .data("toggle", "tooltop")
        .data("placement", "top")
        .data("visit-id", index.VISIT_ID);
    
      const wrapper = jQuery(<div />);
      wrapper.append(label, italic);
    
      return wrapper;
    }
    

    Asides:

    • <label>s are for labeling <input>s and other form controls. You have no for attribute and there’s no form control inside it. You’re using the wrong element.
    • <i> elements are for marking text which would typically be rendered in print as italic (e.g. names of ships). You have no text. I’m guessing you plan to put a background image there, but that is wildly unhelpful for a variety of people (including keyboard users and screen reader users). It looks like that should be a <button> containing an <img> with an alt attribute.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search