Use HTML Search bar input to call javascript function

So I have a navbar form, where I basically want someone to input either a 3 digit number or 5 digit number, and so I am trying to use what is in the search bar input and call the function using that number, and depending on that open up a certain link. I can't get it to work though, I am having trouble with my function being called, and then as a result of the button being clicked, it opens the appropriate link. I'd appreciate any help.

HTML:

<form class="navbar-form" style="width: 200px">
        <div class="input-group">
             <input type="text" 
                    class="form-control" 
                    id="submit"/>
             <button class="input-group-addon">
                  <i class="fa fa-search" 
                     style="color: #fff" 
                     onclick="searchButton()">
                  </i>
             </button>
        </div>              
</form>

Javascript:

var input = document.getElementById('submit');

function searchButton() {
    var str;
    if (input.length == 3) {
        str = '#/root/home/three/' + input.value;
        <a href="str"></a>
    }
    else if (input.length == 5) {
        str = '#/root/home/five/' + input.value;
        <a href="str"></a>
    }    
    else{
        alert('Invalid input');
    }  
};

http://jsfiddle.net/BootstrapOrBust/wg1s25bq/3/

Upvotes: 0

Views: 2843

Answers (1)

Alper Cinar
Alper Cinar

Reputation: 861

use

location.href = "url adress that you want to open";

instead of writing html link tag

<a href="str"></a>

into the javascript code

you can get current url of the web page by using

document.URL

and you can generate your url string by appending the search input to the current url string , in addition to that, if you want to load a new page , your appending url string shouldnt start with a hash character (#)

var input = document.getElementById('submit');

var currentUrl = document.URL;

function searchButton() {
    var str;
    if (input.value.length == 3) {
        str = 'root/home/three/' + input.value;
        location.href = currentUrl + str;
    }
    else if (input.value.length == 5) {
        str = 'root/home/five/' + input.value;
        location.href = currentUrl + str;
    }    
    else{
        alert('Invalid input');
    }  
};

Upvotes: 1

Related Questions