1

I am trying to do data validation on an editable field using an onchange event trigger. When the event fires, I am passing the event. My function tries to display the innerHTML in an alert but it always returns null.

Here is my code:

<head>
<script>
   function chkchg(evt) {
     alert(evt.innerHTML);
   }
</script>
</head>
<body>
  <table>
    <tr>
    <td><input class='patched' contenteditable='true' type='text' onchange='chkchg(event.target);' value='Yes'></td>
    <td><input class='excluded' contenteditable='true' type='text' onchange='chkchg(event.target);' value='No'></td>
    </tr>
  </table>
</body>

It seems pretty simple but I don't know what is wrong.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
T Riley
  • 11
  • 1
  • 3
  • `innerHTML` returns the HTML between tags like `
    HTML
    `. You however are trying to get the `value`. [See this answer for that.](http://stackoverflow.com/questions/4173391/javascript-get-element-value)
    – samiles Oct 31 '16 at 15:06

2 Answers2

0

Try passing in only the event to the chkchg function and reference the target property inside of the function. But the real fix here is referencing the value property of the input instead of innerHTML:

<head>
 <script>
  function chkchg(evt) {
   alert(evt.target.value);
  }
 </script>
 </head>
 <body>
  <table>
   <tr>
   <td><input class='patched' contenteditable='true' type='text'   onchange='chkchg(event);' value='Yes'></td>
   <td><input class='excluded' contenteditable='true' type='text' onchange='chkchg(event);' value='No'></td>
  </tr>
 </table>

J_Everhart383
  • 354
  • 1
  • 6
0

If you want the value of the input, why not use this.value. And innerHTML won't work on input fields. you need to use value.

<script>
    function chkchg(evt) {
        alert(evt);
    }
</script>
<table>
    <tr>
        <td>
            <input class='patched' contenteditable='true' type='text' onchange='chkchg(this.value);' value='Yes'></td>
        <td>
            <input class='excluded' contenteditable='true' type='text' onchange='chkchg(this.value);' value='No'></td>
    </tr>
</table>

Or using this. You then can access other properties.

<input class='patched' id='patched' contenteditable='true' type='text' onchange='chkchg(this);' value='Yes'>

<script>
    function chkchg(evt) {
        alert(evt.id + " - " + evt.value);
    }
</script>
VDWWD
  • 35,079
  • 22
  • 62
  • 79