Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById onchange results in object is not a function

I am trying to trigger a function when value of input_1 textbox changes.

i.e. getElementById('input_1').onchange results in object is not a function.

HTML

<form method="GET" id="game_form"></form>
<table border="1" style="background-color:#FFFFCC;border-collapse:collapse;border:1px solid #FFCC00;color:#000000;width:100" cellpadding="3" cellspacing="3">
  <tr>
    <td id="cell_1"><input type="text" id="input_1" form="game_form" value="x"></td>
    <td id="cell_2"><input type="text" id="input_2" form="game_form"></td>
    <td id="cell_3"><input type="text" id="input_3" form="game_form"></td>
  </tr>
  <tr>
    <td id="cell_4"><input type="text" id="input_4" form="game_form"></td>
    <td id="cell_5"><input type="text" id="input_5" form="game_form"></td>
    <td id="cell_6"><input type="text" id="input_6" form="game_form"></td>
  </tr>
  <tr>
    <td id="cell_7"><input type="text" id="input_7" form="game_form"></td>
    <td id="cell_8"><input type="text" id="input_8" form="game_form"></td>
    <td id="cell_9"><input type="text" id="input_9" form="game_form"></td>
  </tr>
</table>

Javascript

$(window).load(
    function checkInput() {
//        alert("I am an alert box!1");
        var cell = document.getElementById('input_1');
        alert(cell.value);
        **document.getElementById('input_1').onchange**(
            doSomething()
        );
    }
);


function doSomething(){
    alert("I am an alert box!2");

}
like image 566
Damien Avatar asked Sep 12 '25 13:09

Damien


2 Answers

You're using the wrong syntax. You want addEventListener

var el = document.getElementById("input_1");
el.addEventListener("change", doSomething, false);

Or with jQuery:

var $el = $('#input_1');
$el.on('change', doSomething);
like image 135
Jivings Avatar answered Sep 14 '25 02:09

Jivings


The problem is that .onchange is property, not function.

You can, by the way, use jQuery .on() for this:

$('#input_1').on("change", function()
{
    doSomething();
});

Or .change() shortcut for .on("change", ...:

$('#input_1').change(function()
{
    doSomething();
});

If you somewhy want to use onclick instead of .change() and .addEventListener(), you can use it this way:

document.getElementById('input_1').onchange = doSomething;

Fiddle.

like image 23
Regent Avatar answered Sep 14 '25 03:09

Regent