简体   繁体   中英

Javascript doesn't work as expected in bootstrap input

I want to redirect users when they type words and press enter to another page

<div class="form-group has-feedback">
    <input id="searchbox" type="text" class="form-control" placeholder="search" onkeypress="Fsearchbox(event)" />
    <i class="glyphicon glyphicon-camera form-control-feedback"></i>
</div>

<script>
function Fsearchbox(e) {
    var keynum;

    if(window.event) // IE                  
        keynum = e.keyCode;
    else if(e.which) // Other browsers                  
        keynum = e.which;

    if (keynum==13)
    {
        var x = document.getElementById("searchbox").value;
        window.location.href = '/Mo3taz/public/search/'+x;
    }
}
</script>

The problem is When I type something in the input and press enter the page does't redirect to the new location and shows a question mark after the URL of the current page http://localhost/Mo3taz/public/bio?

What is the reason for that? and how can I solve it?

From the behavior you describe, I can easily guess that your input is inside a <form> , with a GET method (which adds parameters to the URL after a ? , but your parameters are empty because your input does not have a name attribute).

When you hit enter, the form is submitted, and your redirection is not taken into account. To prevent the form from being submitted and do your redirection via JS, just add e.preventDefault();

Fixed code:

function Fsearchbox(e) {
    var keynum = e.keyCode || e.which;

    if (keynum==13){
        var x = document.getElementById("searchbox").value;
        window.location.href = '/Mo3taz/public/search/'+x;
        e.preventDefault();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM