Search code examples
javascriptfunctionbuttoninputlocation-href

How to add a function in a addEventListener function in javascript?


I have a problem with my function I made a if function in my addEventListener and when I click in the button it seems like the button take the value of the id="dollar" in the span, I don't know why and when I make a console log of the id="dollar", the browser show me the value of th input, I don't know why ?

With this code it seems like he only take the value of 1000 .

<div>

    <p id="dollar">1000</p>

    <input  type="range"  min="0" max="40000" step="100" value="0" 
    oninput="showDollar(this.value)" onchange="showDollar(this.value)">

</div>

<button id="bouton">OBTENER CREDITO</button>

<script type="text/javascript">
    var nombre = document.querySelector('span').innerHTML;
    var bouton =  document.getElementById('bouton');

    function showDollar(newDollar){

        document.getElementById('dollar').innerHTML = newDollar;

    }

    bouton.addEventListener("click", function(){

        if(nombre<750){
            location.href = "https://www.google.com";
        }
        else{
            location.href = "https://www.youtube.com";
        }

     }); 

 </script>

Solution

  • in you're listenere you check the value of number but number is define only one time when the page is load.

    Before test de value you need to update it :

    bouton.addEventListener("click", function(){
        nombre = document.getElementById('dollar').innerHTML
        if(nombre<750){
            location.href = "https://www.google.com";
        }
        else{
            location.href = "https://www.youtube.com";
        }
    
     }); 
    

    And i change document.querySelector('span').innerHTML by document.getElementById('dollar').innerHTML

    to retrieve the value of number, i think it was what you need