kexxcream kexxcream - 3 months ago 13
HTML Question

Prevent double submission of form using jQuery

Problem:

I have a script where the user can press the keys C or M to choose an option. Once either key is pressed the form will be submitted. Since there is a strict rule that each option can be submitted once, some press multiple times.

Question:

How can I prevent users from submitting the form again after they have pressed the C or M key? I want them to be able to press either key once the page refresh after submission.

Code in PHP / jQuery:

if (in_array($checkstring, $footer))
{
echo '
<script type="text/javascript">
$(document).ready(function()
{
$(window).keypress(function(e)
{
if (e.which == 99)
{
$("input#left").val( 1 );
$("form").submit();
}
else if (e.which == 109)
{
$("input#right").val( 1 );
$("form").submit();
}
});

'.$warning.'
});
</script>
';
}

Answer

I'm thinking you are looking for something like:

which creates a Boolean variable set to false and if the variable is false and key = C|M set once to true then the function won't run submit again because once is true and not false

var once = false;
$(window).keypress(function(e){
    if(!once){
        if(e.which == 99){
            $("input#left").val( 1 );
            $("form").submit();
            once = true;
            //maybe a function to time out to reset once after x seconds?
        }else if (e.which == 109){
            $("input#right").val( 1 );
            $("form").submit();
            once = true;
            //maybe a function to time out to reset once after x seconds?
        }
    }
});
Comments