-1

I am curious why it doesnt alert 5 when i click the button. anyone know why? http://jsfiddle.net/bm8dd/

<center>
   <input id='1' type='text' onfocus='1();'>
   <input id='2' type='text' onfocus='2();'>
   <br>
   <br>
   <button type='button' onclick='3()'>Button</button>
</center>
<script>
    var x = 5;
    function 3() {
        alert(x);
    }
</script>
Alkis Kalogeris
  • 17,044
  • 15
  • 59
  • 113
  • 2
    Tips: 1. Learn to use jsFiddle, put JS code in its own panel, click the JSHint button to find about errors. 2. Check your browser console. – elclanrs Jul 30 '14 at 05:43
  • Use your console: `Uncaught SyntaxError: Unexpected number`. – Marty Jul 30 '14 at 05:43
  • 1
    If you absolutely must have functions named this way, you could do something like `window["1"] = function(){ ... }`, called via `window["1"]()`. – Marty Jul 30 '14 at 05:46

4 Answers4

7

Because you cannot start a functions name with a number.

Also, its same with the id (not now) but its a general practice of not to start the ids with the numbers too.

Consider naming your functions appropriately like field1() or field2() so it makes sense when someone else reads your code, that's called Naming Convention.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
3

3 is not a valid function name. Functions must begin with an alphabetical character (A-Za-z) or $ character.

Also, please avoid <center> as it is no-longer valid HTML.

Dai
  • 141,631
  • 28
  • 261
  • 374
2

Follow the naming conventions,
You cannot start a function name with numbers

Try as one, two, three

    <input id='1' type='text' onfocus='one();'>
    <input id='2' type='text' onfocus='two();'>
    <br>
    <br>
     <button type='button' onclick='three()'>Button</button>

Between script tags

     var x = 5;
     function three() {
         alert(x);
     }
Naveen Kumar Alone
  • 7,536
  • 5
  • 36
  • 57
1

You can not name functions numbers, try this,

<input type="button" value="test" />


    $('input[type=button]').click( function() {
     alert("test");   
    });

Sometimes jsfiddle can be a pain when doing alert functions.

You have to make sure to separate your html css and js as much as you can and leave out script tags

Here is a working example,

Click Here

wuno
  • 9,547
  • 19
  • 96
  • 180