JavaScript: how to change form action attribute value based on selection?
258,740
Solution 1
$("#selectsearch").change(function() {
var action = $(this).val() == "people" ? "user" : "content";
$("#search-form").attr("action", "/search/" + action);
});
Solution 2
If you only want to change form's action, I prefer changing action on-form-submit, rather than on-input-change. It fires only once.
$('#search-form').submit(function(){
var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
$("#search-form").attr("action", "/search/" + formAction);
});
Solution 3
Simple and easy in 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>
Related videos on Youtube
Author by
n00b0101
Updated on April 28, 2021Comments
-
n00b0101 about 3 years
I'm trying to change the form action based on the selected value from a dropdown menu.
Basically, the HTML looks like this:
<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>
If "people" is selected, (which it is by default), the action should be "/search/user", and if content is selected, the action should be "/search/content"
I'm still searching around, but haven't been able to find out how to do this.
-
n00b0101 over 14 yearsThat is way better than what I was trying... Thank you
-
Ryan over 12 yearsWorked perfect. Thanks. I updated this code to change the action on submit instead of on form change.
-
SET001 almost 12 yearsthis.form.submit(); will have no sense since there are actually no forms an thus - nothing to submit
-
trante over 10 yearsIf you design for mobile devices it would be better to change action "on submit" for performance issues. Check my answer below.
-
gsinha about 8 yearsUse
prop
instead ofattr
. Example =$("#search-form").prop ("action", "/search/" + action);
-
enorl76 about 5 yearswhy would DOMElement
setAttribute
save any time over using jqueryattr
?