我有以下JavaScript submit
函数,表单可以正常工作。但是当表单在页面上两次时它只适用于第一个表单而不适用于第二个表单。我认为我需要使用this
的东西,所以它只适用于活动表格?
HTML:
<form action="resultsnew.php" method="get" style="margin-bottom: 0" class="store-search-form">
<input type="text" name="d" value="Enter Postcode..." onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Enter Postcode...':this.value;" class="find-form-input field store-search-postcode" />
<input type="submit" onclick="java" value="Search" class="button" />
</form>
JavaScript的:
$('.store-search-form').submit(function() {
//get the input's value
var postcodeinput = $('.store-search-postcode').val();
//remove spaces
postcodeinput = postcodeinput.replace(/\s/g, '');
//if valid postcode length trim it down
if (postcodeinput.length >= 5 && postcodeinput.length <= 7) {
//set the input's value
$('.store-search-postcode').val(postcodeinput.substring(0,postcodeinput.length - 3));
}
});
答案 0 :(得分:1)
通过find
进行相对于$(this)
的搜索,即更改此内容:
var postcodeinput = $('.store-search-postcode').val();
到此:
var $this = $(this);
// ...
var postcodeinput = $this.find('.store-search-postcode').val();
(在其他地方你使用它。)
请记住,在事件处理程序中,this
指的是处理程序连接到的元素。 $(this)
为该元素创建一个jQuery实例。然后find
在该元素的后代中搜索。
答案 1 :(得分:0)
您需要使用input
引用每个表单中的$(this).find('.store-search-postcode')
,然后使用该引用:
$('.store-search-form').submit(function() {
//get the input
var postcodeinput = $(this).find('.store-search-postcode');
//get the input's value
var postcode = postcodeinput.val();
//remove spaces
postcode = postcode.replace(/\s/g, '');
//if valid postcode length trim it down
if (postcode.length >= 5 && postcode.length <= 7) {
//set the input's value
postcodeinput.val(postcode.substring(0, postcode.length - 3));
}
});