I have a form which consists of two dropdown fields.
<form action="" method="post" id="validation">
<div>
<input type="text" name="name">
</div>
<div>
<select id="car" name="car">
<option value="">Select....</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</div>
<div>
<select id="fruit" name="fruit">
<option value="">Select....</option>
<option value="orange">Orange</option>
<option value="papaya">Papaya</option>
<option value="avacado">Avacado</option>
</select>
</div>
<input type="submit" value="Purchase" id="submit">
</form>
I want to collect these information and perform some action but before I want to validate that. But I am not sure about where to place my validation code. This is my "ajax_js" file.
$(document).ready(function(){
$('#submit').on('click', function(e){
e.preventDefault();
var car = $('#car').val();
var fruit = $('#fruit').val();
// I am applying validation here
$('#validation').validate({
rules: {
car: {
required: true
},
fruit: {
required: true
}
}
})
$.ajax({
type: 'post',
url: ajax_url, //I have defined this in fuctions.php
data: { action: 'test', get_car: car, get_fruit: fruit},
success: function(response){
$('#insert').html(response);
}
});
});
In functions.php, I have registered the jquery validation cdn....
function add_jQuery_libraries() {
// Registering Scripts
wp_register_script('google-hosted-jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false);
wp_register_script('jquery-validation-plugin', 'http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js', array('google-hosted-jquery'));
// Enqueueing Scripts to the head section
wp_enqueue_script('google-hosted-jquery');
wp_enqueue_script('jquery-validation-plugin');
}
add_action( 'wp_enqueue_scripts', 'add_jQuery_libraries' );
function ajax_js() {
wp_enqueue_script( 'ajax_js', get_template_directory_uri() . '/assets/js/ajax.js', array( 'google-hosted-jquery', 'jquery-validation-plugin' ), null, true );
}
add_action( 'wp_enqueue_scripts', 'ajax_js' );
Please check this code, everything is working fine, but the problem is that either validation is working or ajax part is working. Please suggest me a good way to perform ajax as well as validation. Thanking you.
Now I want to clear the form. I have used the following code.
$.ajax({
type: 'post',
url: ajax_url, //I have defined this in fuctions.php
data: { action: 'test', get_car: car, get_fruit: fruit},
success: function(response){
$('#car').val(""); //This reset the value but it does not reset the selected list
//$('#car option:selected").removeAttr("selected");
//$('#car :selected').removeAttr("selected");
//$('#car').removeAttr('selected');
//$('#car :selected').prop('selected', false);
//$('#car :selected').remove(); //It removes the default value
$('#insert').html(response);
}
});