How to "build" an HTML input field with a function in oninput attribute?

I’ve been trying all possible ways I could think of, but it’s still wrong:

This is what I’m supposed to use when building the table:

<input oninput="this.value=this.value.replace(/(?![0-9])./gmi,'')"></input>

This is the JS piece, which doesn’t show any error at build:

for (var i = 0; i < ar.length; i++) {
  result += "<tr>";
  for (var j = 0; j < ar[i].length; j++) {
    result +=
      (j == 8) ? "<td><span class='dollarcurrency' >$</span><input oninput='this.value=this.value.replace(/[^0-9.,]+/gmi,'')' class='price' name='numberInputs' value='' onchange='add_to_total(this, origin);deposit(getDeposit(), origin)'></td>" :
      "<td class='align-middle' style='word-wrap: break-word;max-width: 160px;text-align:center'>" + ar[i][j] + "</td>";
  }
  result += "<td class='total_price'><strong>$0.00</strong></td>";
  result += "<td><input type='checkbox'></td>";
  result += "</tr>";
}

I’m not sure how to place "" in the replace() when it’s already enclosed in a ''.

, but when it gets built, it throws the following error:
SyntaxError: Unexpected end of input

This how it looks when inspecting the HTML:
<input oninput="this.value=this.value.replace(/[^0-9.,]+/gmi," ')'="" class="price" name="numberInputs" value="" onchange="add_to_total(this, origin);deposit(getDeposit(), origin)">

Appreciate your help!

>Solution :

You can use backquotes. They are generally used for template literals, but here it will let you have another type of string delimiter and saves you from special character escaping hell.

for (var i = 0; i < ar.length; i++) {
  result += "<tr>";
  for (var j = 0; j < ar[i].length; j++) {
    result += // backquote here so you can use "" in the replace
      (j == 8) ? `<td><span class='dollarcurrency' >$</span><input oninput='this.value=this.value.replace(/[^0-9.,]+/gmi,"")' class='price' name='numberInputs' value='' onchange='add_to_total(this, origin);deposit(getDeposit(), origin)'></td>` :
      "<td class='align-middle' style='word-wrap: break-word;max-width: 160px;text-align:center'>" + ar[i][j] + "</td>";
  }
  result += "<td class='total_price'><strong>$0.00</strong></td>";
  result += "<td><input type='checkbox'></td>";
  result += "</tr>";
}

Leave a Reply