使用Javascript或jquery从表单字段构建URL

Tro*_*roy 17 javascript jquery

我有一个简单的问题,我似乎无法找到适合其他地方的解决方案.我正在尝试使用Javascript或jquery创建URL构建器表单.Bascially,将采取两个表单字段的值,将它们添加到预先设定的网址,并显示在上提交的第三场.

生成的URL可能是http://www.mydomain.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>
Run Code Online (Sandbox Code Playgroud)

提前致谢!特洛伊

epa*_*llo 23

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

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

alert($("#form1").serialize());
Run Code Online (Sandbox Code Playgroud)

如果您只想做几个字段,那么只需让选择器选择那些字段即可.

alert($("#variable1, #variable2").serialize());
Run Code Online (Sandbox Code Playgroud)


cla*_*rkf 7

怎么样......

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);
Run Code Online (Sandbox Code Playgroud)

这将选择所有<input>的S ON form1type='text'和它们连接成一个查询字符串.见encodeURIComponent().


Orrrr .....你可以使用.serialize().谢谢@prodigitalson.