Add text to parameter before sumbit form

坚强是说给别人听的谎言 提交于 2019-12-14 02:54:41

问题


I have a form like this

<form action="http://example.com/search" method="get">
    <input type="text" name="q">
    <input type="submit">
</form>

When I fill parameter q with some text (e.g. 'AAAAA') and submit this form, the url become to http://example.com/search?q=AAAAA.

But, I want add some text to parameter q with other text before submit. For example, if user input 'AAAAA' the parameter become 'AAAAA BBBBB CCCCC'. So the url become to http://example.com/search?q=AAAAA+BBBBB+CCCCC.


回答1:


Use JavaScript to modify the value before submit. Add an onsubmit event to the form which will get fired when you submit the button. Like this...

<form action="http://example.com/search" method="get" onsubmit="return addText();">
    <input type="text" name="q" id="q">
    <input type="submit">
</form>

<script>
function addText(){
    document.getElementById("q").value += " BBBB CCCC"; // Whatever your value is
    return true;
}
</script>



回答2:


Watch my example on jsFiddle http://jsfiddle.net/ilya_kolodnik/N9gWm/

var text_to_append = "test";
$('form').submit(function(obj) {
    obj.preventDefault();
    alert($("input[name='q']").val());
    $("input[name='q']").val($("input[name='q']").val() + text_to_append);
    this.submit();
});

At first we handle 'submit' action on form. To prevent form submit we use preventDefault(); Than we modify our query and submit the form.



来源:https://stackoverflow.com/questions/17899945/add-text-to-parameter-before-sumbit-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!