重定向GET表单并在另一个url中执行操作


Redirect GET form with action in another url

我有一个表单,其操作设置为"/resumtls"。但我有一个txt输入,我想检查它是否为空,以重定向到"/results"以外的另一个位置。这可能吗?代码示例如下:

<form id="results" action="/results" method="get">
<select id="country" name="country">
....
</select>
<input type="text" name="id">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>

有什么想法吗?这可以用jquery完成吗?

当然可以在提交处理程序中做到这一点警告:我不会将idname赋予表单控件。这确实会引起混淆:如果this指的是表单,那么this.id是指表单的id还是指具有name="id"的文本字段?

    if( !!this.somefield.value ) { //did not want to write this.id.value !!!!
      this.action = '/other-url';
    } else {
      this.action = '/results';
    }

$(function() {
  $('#results').on('submit', function(e) {
    e.preventDefault(); // just so we can see that form action changes
    if( !!this.somefield.value ) {
      this.action = '/other-url';
    } else {
      this.action = '/results';
    }
    alert( this.action );
    //$(this)[0].submit(); //now submit the form
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="results" action="/results" method="get">
<select id="country" name="country">
</select>
<input type="text" name="somefield">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>

是的,这是可能的。只需使用jQuery .prop()设置表单元素的action属性。

举个简单的例子:

var valid = false;
// go though validation here
if (false === valid) {
    $('#results').prop('action', '/some/url/to/redirect/to');
}

HTML5提供了"required"属性,该属性将阻止表单被发布,像这样使用

<input type="text" name="id" required="required">

或者,如果你更喜欢重定向到其他页面,你可以这样做

<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
    <script>
        $("#results").submit(function (e){
            e.preventDefault();
            if($("#results input[name='id']").length < 1){
                window.location.href = "your detiny url";                    
            }
            else{
                this.submit();
            }
        });
    </script>