Njinx Njinx - 16 days ago 7
HTML Question

jQuery event won't fire on HTML form submit

I'm sorry if this question has already been asked but all the solutions I've tried haven't worked for me. What I want it to do is trigger some jQuery code when the form element is submitted.
Here's my code.

JS:

$(document).ready(function() {
$('form').bind('submit', function() {
alert('hi');
var word10 = <?php echo $word10; ?>;
var word20 = <?php echo $word20; ?>;
var word1Txt = <?php echo $word1Txt; ?>;
var word2Txt = <?php echo $word2Txt; ?>;

$('div.word1').prepend("<h3 class='header'>hi" + word1Txt + "</h3>");
$('div.word2').prepend("<h3 class='header'>hi" + word2Txt + "</h3>");
});
});


HTML:

<form class="form-inline" method="post">
<input class="form-control" type="text" placeholder="First Word" name="word1" autofocus>
<input class="form-control" type="text" placeholder="Second Word" name="word2" autofocus>
<input class="btn btn-primary form-submit" type="submit" value="Compare">
</form>

Answer

Use .on() or .submit() instead and if your vars are supposed to be strings, quote them:

$(document).ready(function() {
    $('form').on('submit', function() {
        alert('hi');
            var word10 = '<?php echo $word10; ?>';
            var word20 = '<?php echo $word20; ?>';
            var word1Txt = '<?php echo $word1Txt; ?>';
            var word2Txt = '<?php echo $word2Txt; ?>';

            $('div.word1').prepend("<h3 class='header'>hi" + word1Txt + "</h3>");
            $('div.word2').prepend("<h3 class='header'>hi" + word2Txt + "</h3>");
    });
});