0

I have a form that looks like this:

<form id="message">
    <input type="text" id="name" placeholder="Name">
    <textarea id="messagefield" placeholder="Message"></textarea>
    <input type="submit" value="Send">
</form>

I want to execute a function instead of the form submitting, so I have this at the bottom of my page:

$(function() {
    $("#message").on("submit", function(e) {
        e.preventDefault();
        var recipient = $("#name").val();
        var message = $("#messagefield").val();
        send(recipient, message);
    });
});

But for some reason, 19/20 times when I press Send, the page reloads and the values in the inputs disappear. Any idea why this would happen? Sometimes when I go to the page, then refresh it, then fill out the form, it works.

I've found this thread: Submit button does not work unless I refresh the page form_for Rails for some reason I think cordova may be rendering the HTML incorrectly and then fixing it on reload like described here

Turns out that's what it was. Here is a screenshot of the rendered HTML: Imgur

Some more useful information: jQuery Mobile click event.preventDefault does not seem to prevent change

Community
  • 1
  • 1
Joshua Terrill
  • 1,995
  • 5
  • 21
  • 40

2 Answers2

0

Try to use: it won't submit form

 <button type="button" name="theButton" id="msg">SUBMIT</button>

 $(function() {
$("#msg").on("click", function(e) {
    e.preventDefault();
    var recipient = $("#name").val();
    var message = $("#messagefield").val();
    send(recipient, message);
});

});

Sandeep Kapil
  • 984
  • 8
  • 14
  • Same thing happens as before... for some reason when I press it, nothing happens. But whenever I refresh and press it, it works. Same goes for anchor tags as well. – Joshua Terrill Oct 05 '15 at 05:07
0

Please return false; at the end of your function. may be form submit successfully and return true and so your controls are cleared. As Below::

$(function() {
        $("#message").on("submit", function(e) {
            e.preventDefault();
            var recipient = $("#name").val();
            var message = $("#messagefield").val();
            send(recipient, message);
            return false;
        });
    });