Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS document.getElementById execute on Button click

I am extremely new to JavaScript, so bear with me.

I have the following code:

<input id="test" name="test" type="text" value="" /> 
<input id="test" type="button" value="Go!" /> 
<script type="text/javascript">
    window.location.href="http://www.thenewendurancefitness.com/" + document.getElementById('test').value;
</script>

I would like the code to only be executed upon a button click. The function is to add the user input data to the end of the url and then upon the button click, load that url.

As of now, when I load the page, it automatically executes and goes to the url.

like image 736
user3573194 Avatar asked Apr 25 '14 13:04

user3573194


2 Answers

  1. You have two input fields with the same ID, that's a no go! Change the second one to something different!

  2. Put your current javascript code into a function

    function clickHandler(event) {
        // Your code...
    }
    
  3. Attach an event listener to your container

    var myContainer;
    
    // assign element from DOM
    myContainer = document.getElementById(ID_OF_CONTAINER);
    
    // attach event handler
    myContainer.addEventListener('click', clickHandler);
    

That should do the trick

like image 102
Luketep Avatar answered Nov 11 '22 21:11

Luketep


<input id="test" name="test" type="text" value="" /> 
<input id="test2" type="button" onclick="fnc()" value="Go!" /> 
<script type="text/javascript">
function fnc(){
window.location.href="http://www.thenewendurancefitness.com/" + document.getElementById('test').value;
}

</script>
like image 4
Marin Vartan Avatar answered Nov 11 '22 22:11

Marin Vartan