How can I get an HTML form's values into a “cu

2019-07-25 23:11发布

问题:

On my site, I can access a search function by going to "mysite.com/search/search_term", where "search_term" is the term the user entered. I'm trying to get a simple one-input form to format the URL that way. One way that I can do it is make a PHP script that would redirect to the proper place. So if you navigate to "search_redirect.php?term=search_term", it would just redirect you to "/search/search_term". I want to avoid doing this, as it seems kind of redundant. If I don't find a better answer, that's probably what I'll end up doing. Now, here's what I tried so far:

I tried setting an onsubmit on the form like this:

<form onsubmit="search_navigate()" id="navbar_form">
    <input type="search" placeholder="Search Articles..." id="navbar_search"></input>
    <input id="navbar_submit" type="submit" value=">"/>
</form>

... which, onsubmit calls this function:

function search_navigate(){
    alert("well hey there");
    window.location = ("http://www.google.com");
}

When I click on the submit button, I can see the alert, but instead of taking me to Google as you'd expect, it takes me to the same page I'm on (whatever that page might be).

This is the problem I'm faced with when implementing it this way. If you have another way entirely, I'd still like to hear it.

回答1:

function search_navigate() {
    var obj = document.getElementById("navbar_search");
    var keyword = obj.value;
    var dst = "http://yoursite.com/search/" + keyword;
    window.location = dst;
}

may this work for you?


further more, to stop the form submit doing its origin function, append "return false" to the function call, that is, onsubmit="foo();return false".



回答2:

Usually when you encounter weird behaviour like this, it has something to do with the <form>. Try this:

<script type="text/javascript">
function search_navigate() {
    var obj = document.getElementById("navbar_search");
    var keyword = obj.value;
    var dst = "http://yoursite.com/search/" + keyword;
    window.location = dst;
}
</script>

<span id="navbar_form">
    <input type="search" placeholder="Search Articles..." id="navbar_search" />
    <input type="button" id="navbar_submit" value="Submit" onClick="search_navigate()" />
</span>