两次同一表单在页面上时提交功能

时间:2018-05-24 15:51:21

标签: javascript jquery html

我有以下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));
    }
});

2 个答案:

答案 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));
  }
});