Add text to parameter before sumbit form

2019-08-03 23:33发布

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.

2条回答
The star\"
2楼-- · 2019-08-04 00:18

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>
查看更多
小情绪 Triste *
3楼-- · 2019-08-04 00:18

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.

查看更多
登录 后发表回答