-1

I have a function that is to be executed on click of a button. It is not working when I click the button. All of my other functions work when I click the button.

Javascript:

window.onload = function() {
    var button = document.getElementById("test");
    test.onclick = function() {
        var summonerid = document.getElementById("username").value.length;
        function summonerName() {
            if(summonerid = 4){
                alert("Come on");
            }
            else {
                alert("wai");
            }
        }
    }
}

Html:

<input type="text" name="summoner" id="username" maxlength="16" autocomplete="off" style="font-size: 22pt; font-family: times new roman">
<input type="submit" id="test" style="font-size: 22pt; font-family: times new roman">
Volune
  • 4,324
  • 22
  • 23

2 Answers2

1

Line by line corrections:

window.onload = function() {
    var button = document.getElementById("test");
    // Typo!
    button.onclick = function() {
        var summonerid = document.getElementById("username").value.length;
        // This was never called
        function summonerName(id) {
            // this assigned 4 to summonerid 
            if(id === 4){
                alert("Come on");
            }
            else {
                alert("wai");
            }
        }
        summonerName(summonerid);
    };

};
max
  • 96,212
  • 14
  • 104
  • 165
  • Shouldn't the `summonerName(summonerid);` be _inside_ the onclick listener? (Please clean indents) – Volune Aug 20 '14 at 00:17
  • You´re correct, I was writing in the browser and got lost in indentation... – max Aug 20 '14 at 00:25
  • 1
    By the way, `test.onclick` worked, since the element has id `test` so it's accessible with that name in the global scope. So it's more a bad practice than a typo. – Volune Aug 20 '14 at 00:27
0

Well, You could simplify your code a bit like this

HTML :

 <input type="button" id="test" value="Submit" onclick="summonerName()"/>

JS :

function summonerName()
{
  var summonerid = document.getElementById("username").value.length;
  if(summonerid==4)
  {
    //Do what needs to be done
  }
}

Hope this helps.

MDJ
  • 266
  • 2
  • 8