我有一个包含许多字段的表单。我正在使用JS代码来修改该表单通过GET请求提交的参数。
基本上,表单提交 3 个参数 - search_address、search_city、search_state、search_zip 以及其他参数 - 我的 JS 代码只是将地址、城市、州和 zip 参数组合成一个参数,并相应地修改搜索查询。
但是当我使用下面的代码运行页面时,原始查询会按原样执行 - 就好像 JS 代码没有效果一样。我在这里做错了什么?
这是表单 HTML 标记的 HTML 代码--
<form method="get" class="searchform" id="searchform" action="target_URL_value">
这是提交按钮的 HTML 代码--
<input type="submit" class="submit" name="submit" id="searchsubmit" onclick="JavaScript:submit_form()" style="width:20%" />
这是submit_form函数的Javascript代码--
<script>
function submit_form()
{
$('searchform').submit( function() {
var $form = $(this);
//Arvind IMP put the below paraemeter's name as s or the value of name in Search field of original header.php in parent template...
// This is a typical search string
//?post_type=property&search_keyword=&submit=Search&price-min=&price-max=&city=&state=&zip=&beds=&baths=&sqft=&status=
var data = 'post_type='+$('#post_type').val()+'&search_keyword='+$('#search_address').val()+", "+$('#search_city').val()+", "+$('#search_state').val()+", "+$('#search_zip').val()
+ '&price-min='+$('#price-min').val()+ '&price-max='+$('#price-max').val() +'&city='+$('#search_city').val()
+ '&state='+$('#search_state').val()+ '&zip='+$('#search_zip').val() +'&beds='+$('#beds').val()
+ '&sqft='+$('#sqft').val()+ '&status='+$('#status').val();
$.get( $form.attr('action'), data);
return false;
});
}
</script>
最佳答案
不要将提交事件声明到函数中。
同时删除内联代码onclick="JavaScript:submit_form()"
最后,不要忘记表单选择器 $('#searchform')
的 #
来选择 id(或 .
选择类别)
$(document).ready(function () {
$('#searchform').submit(function () {
var $form = $(this);
//Arvind IMP put the below paraemeter's name as s or the value of name in Search field of original header.php in parent template...
// This is a typical search string
//?post_type=property&search_keyword=&submit=Search&price-min=&price-max=&city=&state=&zip=&beds=&baths=&sqft=&status=
var data = 'post_type=' + $('#post_type').val() + '&search_keyword=' + $('#search_address').val() + ", " + $('#search_city').val() + ", " + $('#search_state').val() + ", " + $('#search_zip').val() + '&price-min=' + $('#price-min').val() + '&price-max=' + $('#price-max').val() + '&city=' + $('#search_city').val() + '&state=' + $('#search_state').val() + '&zip=' + $('#search_zip').val() + '&beds=' + $('#beds').val() + '&sqft=' + $('#sqft').val() + '&status=' + $('#status').val();
$.get($form.attr('action'), data);
return false;
});
});
关于javascript - 更改表单提交的 JS 代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16876020/