【问题标题】:Build URL from form fields with JavaScript or jQuery使用 JavaScript 或 jQuery 从表单字段构建 URL
【发布时间】:2010-10-24 03:04:00
【问题描述】:

我正在尝试使用 JavaScript 或 jQuery 创建 URL 构建器表单。

基本上,它将获取两个表单字段的值,将它们添加到预设 URL 并在提交时显示在第三个字段上。

生成的 URL 可能是 http://example.com/index.php?variable1=12&variable2=56

现在,这不是表单的“动作”,应用程序无法读取 URL(以获取变量),因此必须在页面上完成。

生成的 URL 将显示在名为“url”的字段中。

以下是表单示例:

<form id="form1" name="form1" method="post" action="">
  <p>
    <label>Variable 1
      <input type="text" name="variable1" id="variable1" />
    </label>
  </p>
  <p>
    <label>Variable 2
      <input type="text" name="variable2" id="variable2" />
    </label>
  </p>
  <p>
    <label>URL
      <input type="text" name="url" id="url" />
    </label>
  </p>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
  </p>
</form>

【问题讨论】:

标签: javascript jquery


【解决方案1】:

jQuery 有 serialize 构建查询字符串值。

所以如果你想做整个表格:

alert($("#form1").serialize());

如果你只想做几个字段,那么只需让选择器选择这些字段。

alert($("#variable1, #variable2").serialize());

【讨论】:

    【解决方案2】:

    使用类似...

    var inputs = $('#form1').find('input[type=text]').not('#url');
    var str = "http://www.base.url/path/file.ext?"
    inputs.each(function (i, item) {
        str += encodeURIComponent(item.name) + "=" + encodeURIComponent(item.value) + "&";
    });
    $('#url').val(str);
    

    这将选择form1type='text' 中的所有&lt;input&gt;s,并将它们连接成一个查询字符串。见encodeURIComponent()


    Orrrr .....你可以使用.serialize()Thank you, prodigitalson.

    【讨论】:

    • 既然你已经在用jQ了,为什么还要用$(inputSelector).serialize();呢?
    • 你应该在每个循环的最后一行包含这个: if(i
    【解决方案3】:

    类似下面的东西应该可以工作:

    var partFields = '#variable1,#variable2';
    
    $(partFields).change(function(){
      var url = 'static/URL/to/file.php?';
      $('#url').val(url + $(partFields).serialize());
    });
    

    但是,除非您希望人们能够覆盖 URL,否则您可能希望使用隐藏字段和常规元素来显示和提交 URL 值,在这种情况下,您会得到以下内容:

    var partFields = '#variable1,#variable2';
    
    $(partFields).change(function(){
      var url = 'static/URL/to/file.php?';
      var urlValue = url + $(partFields).serialize();
      $('#url-display').text(urlValue); // Set the displaying element
      $('#url').val(urlValue); // Set the hidden input value
    });
    

    【讨论】:

    • 我会使用@clarkf 行: var partFields = $('#form1').find('input[type=text]').not('#url');这里有工作演示:jsfiddle.net/dactivo/4Nmcx
    猜你喜欢
    • 2017-04-17
    • 1970-01-01
    • 2013-09-15
    • 2013-04-17
    • 2023-03-23
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多