简体   繁体   中英

Error when trying to clear a text bar from a button

When I click the button ( id="ClearText4" ) to clear a text bar, an error occurs and the page refreshes. What am I doing wrong?

<form method="post" target="imgChart4">
    <input type="submit" value="Chart 4" />
    <input type="text" id="ChartBar4" name="ChartBar4" style="width: 286px;"><br>
</form>

<img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="Chart 4"/>

<form  action="" method="post" id="ClearText4">
    <button onclick="limpartexto4()">Limpar Texto 4</button>
</form>

<script type="text/javascript">
    function limpartexto4() {
        var btn = document.getElementById('ClearText4');
        btn.onclick = function(){ document.getElementById('ChartBar4').value="" };
    }
</script>

You have things turned around a little You can remove the form tag around that button and actually get rid of the javascript function as well. Since there's only one thing to do, just put that in the onclick attribute.

<form method="post" target="imgChart4">
  <input type="submit" value="Chart 4" />
  <input type="text" id="ChartBar4" name="ChartBar4" style="width: 286px;"><br>
</form>
<img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="Chart 4" />
<button onclick="document.getElementById('ChartBar4').value=''">Limpar Texto 4</button>

 <form method="post" target="imgChart4"> <input type="submit" value="Chart 4" /> <input type="text" id="ChartBar4" name="ChartBar4" style="width: 286px;"><br> </form> <img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="Chart 4"/> <form action="" method="post" id="ClearText4"> <button onclick="limpartexto4()">Limpar Texto 4</button> </form> <script type="text/javascript"> function limpartexto4() { var btn = document.getElementById('ClearText4'); btn.onclick = function(e){ e.preventDefault(); document.getElementById('ChartBar4').value="" }; } </script>

Your form has a method = "post" that's why this happens.

<form method="post" target="imgChart4">

Because Form is posted to action="" properties mentioned.

You can use e.preventDefault() in the function to avoid default action.

function limpartexto4() {
    var btn = document.getElementById('ClearText4');
    btn.onclick = function(e){ 
     e.preventDefault();
  document.getElementById('ChartBar4').value="" };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM