Flemming Lemche Flemming Lemche - 7 months ago 19
Javascript Question

jQuery script doesn't work in Wordpress

I know this problem has been asked alot of times but I just can't get jQuery to work in Wordpress.

I have a form which is going to be used with some wp_ajax but before I get to this point I wanted to ensure that it could interact with jQuery.

The Form HTML is placed on the page and looks like this:

<div id = "content">
<form action= "" method= "post" id= "hfwpform">
<label for= "fname">First Name</label></br>
<input type= "text" name= "fname" id= "fname" required></br>
<label for= "email">Email Address</label></br>
<input type= "email" name= "email" id= "email" required></br>
<label for= "message">Your Message</label></br>
<textarea name= "message" id= "message"></textarea>
<input type= "hidden" name= "action" value= "contact_form">
<input type= "submit" value= "Send">
</form>
</br></br>
<div id= "feedback">My Feedback</div>
</br></br>
</div>


I have created a plugin which I'm using for my main php.
In this plugin I've created the enqueue lines.

add_action( 'wp_enqueue_scripts', 'load_scripts');

function load_scripts() {

if ( !is_admin() ) {

wp_register_script('hftest', get_template_directory_uri() . '/js/hf_test.js', array('jquery'), '1.0', false );
wp_enqueue_script('hftest');
}
}


I've created a subfolder for my scripts called "js" and the script that should execute when I submit the form looks like this.

(function($) {
$(document).ready(function() {
$('#hfwpform').submit(function() {
$response = "This is it!!!";
alert("Submitted");
$("#feedback").text($response);
});
});
})( jQuery );


When I submit the form the page reloads clearing the input fields instead of changing the feedback text and displaying an Alert box.

What am I doing wrong ???

Regards
Flemming

Answer

Your form is functioning properly. What you are missing is to specify in your js for the form to not execute via the default functionality.

Your code should look like this:

(function($) {
   $(document).ready(function() {
      $('#hfwpform').submit(function(e) {
         e.preventDefault(); //this is key
         $response = "This is it!!!";
         alert("Submitted");
         $("#feedback").text($response);
      });
   });
 })( jQuery );
Comments