user4353372
user4353372

Reputation:

How to prevent that a JQuery button submit my form?

I am absolutly new in JQuery development and I have the following problem.

I have a form that contains this JQuery button:

<!-- RESET BUTTON: -->
<td>
    <button class="resetButton" name="submitReset" onclick="return resetSearch(); return false;">Reset</button>
</td>

Clicking this button the user reset to null two input that are into my form performing this JavaScript function:

function resetSearch() {
    var f = document.getElementById('dataDaAForm');
    f.dataDa.value = null;
    f.dataA.value = null;
    event.preventDefault();
}

The script is performed but the problem is that after that it go out from the previous function the form is submitted anyway and I don't want that this behavior happen.

How can I prevent that the form is submitted when the user click on the reset button? As you can see I also try to add this statment but it don't work:

event.preventDefault();

What am I missing? How can I fix this issue?

Another question is: is it the correct way to reset the values of the input tag of my form?

Upvotes: 2

Views: 156

Answers (3)

Chop
Chop

Reputation: 534

Try this

var form = $('#dataDaAForm')

$(".resetButton").on("click",function(e) {
    form.reset()
    e.preventDefault()
    e.stopPropagation()
})

Upvotes: -1

devqon
devqon

Reputation: 13997

The simplest way to create a reset button is an input type reset:

<input type="reset" value="Reset" />

Though if you really want to do it in javascript, the answer of James Hill will suffice

Upvotes: 0

James Hill
James Hill

Reputation: 61872

Give this a shot - you need to pass the event into the function. In addition, I've removed the need for inline JS.

$(".resetButton").click(function(e) {
    var f = document.getElementById('dataDaAForm');
    f.dataDa.value = null;
    f.dataA.value = null;
    e.preventDefault();
});

In addition to preventing the default, Javascript provides a method to reset your form:

$(".resetButton").click(function(e) {
    document.getElementById("dataDaAForm").reset();
    e.preventDefault();
});

Note: You tagged jquery, so I provided a jquery solution (although there is no jquery in your question).

Upvotes: 4

Related Questions