0

我有这个表格,它是一个简单的顶部搜索栏,如下所示。没有提交按钮。当用户点击回车时,它会被提交。

<form style="display:inline;" method="GET" action="/printers/" class="searchForm">
<input placeholder="Hit enter to search..." type="text" class="topsearchbar" value="">
</form>

然后是 jQuery。这是我从搜索框中获取值并将其添加到当前操作并需要提交的地方。但我只是不知道如何做到这一点。你能帮忙吗?

这是我的jQuery:

$(".searchForm").submit(function(event) {
event.preventDefault();

var action = ($(".searchForm").attr("action"));
var searchStr = ($(".topsearchbar").attr("value"));


if((action && searchStr) != '' &&  (action && searchStr).length >= 5)
{
alert('Ok to proceed')

var serverStr = action+'/'+searchStr;
alert(serverStr)
//Submit the form to serverStr. serverStr is the form's action

}
else
{
alert('To small to be any good')
}

}),
4

3 回答 3

0

在 keydown 事件上找到enter==13,当一切正常时,然后提交表单。

$('.topsearchbar').keydown(function(e){ 

if(e.which==13){
  var action = $(".searchForm").attr("action");
  var searchStr = $(".topsearchbar").attr("value");


  if((action && searchStr) != '' &&  (action.length && searchStr.length) >= 5){
     alert('Ok to proceed');
     $(".searchForm").submit();
     var serverStr = action+'/'+searchStr;
     alert(serverStr);
     //Submit the form to serverStr. serverStr is the form's action

  }
   else
  {
  alert('To small to be any good')
  }
  }
});
于 2012-12-19T12:13:49.690 回答
0

这是一种方法;

$(document).ready(function() {

    $('.searchForm').submit(function(event) {

        var $this = $(this),
            action = $this.attr('action'),
            query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value').

        if (action.length >= 5 && query.length >= 5) {

          // Use URI encoding
          var newAction = (action + '/' + encodeURIComponent(query));
          console.log('OK', newAction); // DEBUG

          // Change action attribute
          $this.attr('action', newAction);

        } else {
          console.log('To small to be any good'); // DEBUG

          // Do not submit the form
          event.preventDefault();
        }
    });

});​

jsfiddle

于 2012-12-19T12:04:13.383 回答
0

您也可以像这样更改操作属性

jQuery('.searchForm').attr('action', 'new-value');

如果你这样做...

jQuery('.searchForm').submit(function() {
    // ...you have to return 'true' if you want to submit after your code
    return true;
    // ...and 'false' if you want to stop the submit.
    return false;
});
于 2012-12-19T12:01:39.617 回答