dvlden
dvlden

Reputation: 2462

JavaScript button function swap

What I am trying to do is following: I have an input type button and I want to replace it's function on first click.

<input type="submit" class="submit-button" value="Submit" name="boom" />

So a [button] that serves for submit, I wanna show alert with some jquery plugins but lets do it here with normal javascript alert (default window).

So on first click it will be

alert('Something');

And on second click it will be default function (submit).

How can I achieve something like this?

Of course if button is clicked once, and then page reloaded, it will show same alert again on first button click.

Upvotes: 1

Views: 584

Answers (2)

Chris Clower
Chris Clower

Reputation: 5104

Try this:

<script type="text/javascript">
    var clicked = false;

    function btnClick(e) {
        if(clicked === false) {
            alert('Something');
            clicked = true;
            e.preventDefault();
            return true;
        } else {
            return false;
        }
    }
</script>

<input type="submit" onclick="btnClick(event)" class="submit-button" value="Submit" name="boom" />

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337550

Use one().

Attach a handler to an event for the elements. The handler is executed at most once per element.

Example:

$(".submit-button").one("click", function(e) {
    // will only run on first click of element
    e.preventDefault();
    alert("Something"); 
});

Upvotes: 4

Related Questions