我有一个由两个下拉字段组成的表单。
<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>
我想收集这些信息并执行一些操作,但在我想验证之前。但我不确定在哪里放置验证码。这是我的#a; ajax_js&#34;文件。
$(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);
}
});
});
在functions.php中,我已经注册了jquery验证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' );
请检查此代码,一切正常,但问题是验证是否正常或ajax部分正常工作。请建议我执行ajax和验证的好方法。感谢你。
现在我想清除表格。我使用了以下代码。
$.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);
}
});
答案 0 :(得分:0)
试试这个
$(document).ready(function(){
$('#validation').validate({
rules: {
car: {
required: true
},
fruit: {
required: true
}
},
submitHandler: function(form) {
var car = $('#car').val();
var fruit = $('#fruit').val();
$.ajax({
url: ajax_url,
type: "POST",
data: { action: 'test', get_car: car, get_fruit: fruit},
cache: false,
processData: false,
success: function(data) {
$('#insert').html(response);
}
});
return false;
},
// other options
});
});