ChatGPT解决这个技术问题 Extra ChatGPT

JavaScript:如何根据选择更改表单动作属性值?

我正在尝试根据下拉菜单中的选定值更改表单操作。

基本上,HTML 如下所示:

<form class="search-form" id="search-form" method="post" accept-charset="UTF-8" action="/search/user">
<select id="selectsearch" class="form-select" name="selectsearch">
<option value="people">Search people</option>
<option value="node">Search content</option>
</select>

<label>Enter your keywords: </label>
 <input type="text" class="form-text" value="" size="40" id="edit-keys" name="keys" maxlength="255" />

<input type="submit" class="form-submit" value="Search" id="edit-submit" name="search"/>
</form>

如果选择“people”(默认情况下),则操作应为“/search/user”,如果选择内容,则操作应为“/search/content”

我仍在四处寻找,但无法找到如何做到这一点。


c
cletus
$("#selectsearch").change(function() {
  var action = $(this).val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + action);
});

这比我尝试的要好得多...谢谢
工作完美。谢谢。我更新了此代码以更改提交操作而不是表单更改操作。
如果您为移动设备设计,最好在“提交”时更改操作以解决性能问题。在下面检查我的答案。
使用 prop 而不是 attr。示例 = $("#search-form").prop ("action", "/search/" + action);
T
Tiny

如果您只想更改表单的操作,我更喜欢在表单提交时更改操作,而不是在输入更改时更改操作。它只触发一次。

$('#search-form').submit(function(){
  var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + formAction);
}); 

A
Ankush Kumar

javascipt中的简单易行

<script>

  document.getElementById("selectsearch").addEventListener("change", function(){

  var get_form =   document.getElementById("search-form") // get form 
  get_form.action =  '/search/' +  this.value; // assign value 

});

</script>

s
scode102

最好用

$('#search-form').setAttribute('action', '/controllerName/actionName');

而不是

$('#search-form').attr('action', '/controllerName/actionName');

因此,根据 trante 的回答,我们有:

$('#search-form').submit(function() {
    var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
    $("#search-form").setAttribute("action", "/search/" + formAction);
}); 

使用 setAttribute 可能会为您节省大量时间。


为什么 DOMElement setAttribute 会比使用 jquery attr 节省任何时间?
M
Madhan

如果您想从纯 javascript 进行更改,请使用以下方法。与具有额外方法的 Ankush Kumar's 代码相同

函数 fn_one(){ document.formname.action="https://google.com/search?q=form+submit+using+name"; } function fn_two(){ document.getElementsByName("formname")[0].action="https://google.com/search?q=form+submit+using+name+method+2"; } function fn_three(){ document.getElementById("formid").action="https://google.com/search?q=form+submit+using+ID"; }


J
JustCarty

需要有表格吗?如果没有,那么你可以使用这个:

<div>
    <input type="hidden" value="ServletParameter" />
    <input type="button" id="callJavaScriptServlet" onclick="callJavaScriptServlet()" />
</div>

使用以下 JavaScript:

function callJavaScriptServlet() {
    this.form.action = "MyServlet";
    this.form.submit();
}

this.form.submit();将没有任何意义,因为实际上没有任何形式,因此 - 无需提交