igauravkamat
igauravkamat

Reputation: 1

document.getElementById('id').innerHTML="some value" changes don't reflect

I have the below mentioned code, the changes made by innerHTML don't reflect in the browser

<body>

<script TYPE="text/javascript">
    function change(){
        document.getElementById("op").innerHTML="this works!";
        prompt(document.getElementById("op").innerHTML);
    }
</script>

<form onSubmit="change()">
    <table>
        <tr>
            <td id="a1">This</td>
           <td id="a2"><input type="text" id="t1"></td>
        </tr>
    </table>
    <input type="submit" value="submit">
</form>

// Output

    <table>
        <tr><td id="op"></td></tr>
    </table>

    </body>
</html>

The changes do take place, as shown by prompt, but are not reflected on the page.

Upvotes: 0

Views: 1155

Answers (1)

Quentin
Quentin

Reputation: 943128

JavaScript is single threaded. The browser won't run a repaint event until the function that assigned the value to innerHTML is finished.

That function won't be finished until the prompt (which is a blocking function) is cleared.

At that point, since it was trigged by a submit button, the form will be immediately submitted and a new page will be loaded (which will have the content of the table cell back in the original state).

Cancel the default event for the form.

90s style:

function change()
{
  document.getElementById("op").innerHTML="this works!";
  prompt(document.getElementById("op").innerHTML);
  return false;
}

onSubmit="return change()">

Modern style:

function change(event)
{
  event.preventDefault();
  document.getElementById("op").innerHTML="this works!";
  prompt(document.getElementById("op").innerHTML);
}
document.querySelector('form').addEventListener("submit", change);

Upvotes: 4

Related Questions