1
votes

I have put auto click function on my form. I want to auto click submit button only once. But my code is continuously clicking on submit button. Due to that my page is continuously auto reloading.

I want to just click once on the button. How can I do that?

<form action="" method="POST">
        <input type="text" size="80" name="url"  value="https://drive.google.com/file/d/<?php echo $_GET['id']; ?>/view"/>
        <input type="submit" id="btn" value="PLAY" name="submit" />
    </form>

<script>
window.onload = function(){
document.getElementById('btn').click();
}
</script>
3
I believe that the button is being clicked and then the page is being reloaded, so it's being clicked again and again. Consider defining the "action" of the form so it would send the user to another page, or using PHP check if the form has being posted and if yes - don't print the javascript code. - Ofir Baruch
Set a flag in php to do that and use it as a switch. - Rajendran Nadar

3 Answers

0
votes

The two answers given are good, however users can manipulate and mess with these stored session items and therefore allows for manipulation of validation.

To avoid users messing with your validation you can check if the form has been posted in PHP. This is especially important when dealing with sensitive user information.

<?php if(!isset($_POST['submit'])) { ?>
<script>
   window.onload =  function ()
    {
        document.getElementById('btn').click();     
    }
</script>
<?php } ?>
1
votes

You can use localstorage to determine if you have already submitted the form or not, and submit the form based on this value

window.onload = function(){
    if (localStorage.formSubmitted !== 'true') {
        localStorage.setItem("formSubmitted", "true");
        document.getElementById('btn').click();
    }
}
0
votes

You can also store it in localstorage when the button is clicked for the first time. And before you execute the click event, check if that storage is set. Like this:

window.onload = function() {
    if (!localStorage.getItem('buttonClicked')) {
        localStorage.setItem('buttonClicked', 'true');
        document.getElementById('btn').click();
    }
}