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.
$("#selectsearch").change(function() {
var action = $(this).val() == "people" ? "user" : "content";
$("#search-form").attr("action", "/search/" + action);
});
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);
});
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>
It's better to use
$('#search-form').setAttribute('action', '/controllerName/actionName');
rather than
$('#search-form').attr('action', '/controllerName/actionName');
So, based on trante's answer we have:
$('#search-form').submit(function() {
var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
$("#search-form").setAttribute("action", "/search/" + formAction);
});
Using setAttribute
can save you a lot of time potentially.
setAttribute
save any time over using jquery attr
?
If you want to change from Pure javascript means use follow methods. Same as Ankush Kumar's code with Extra methods
function 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"; }
Is required that you have a form? If not, then you could use this:
<div>
<input type="hidden" value="ServletParameter" />
<input type="button" id="callJavaScriptServlet" onclick="callJavaScriptServlet()" />
</div>
with the following JavaScript:
function callJavaScriptServlet() {
this.form.action = "MyServlet";
this.form.submit();
}
Success story sharing
prop
instead ofattr
. Example =$("#search-form").prop ("action", "/search/" + action);