Reputation: 87
I'm would like to create an object in javascript which prints the number entred but I get this error.
Déclaration d'objet.html:30
Code :
<script type="text/javascript">
// <!--
function Init()
{
var test= new Object;
test.affiche= function()
{
var champ=Number(document.getElementById("champSaisie").value);
alert(Number(champ+4));
};
}
</script>
</head>
<body onload="Init()">
<p><label for="champSaisie">Saisissez un nombre : </label><input type="text" id="champSaisie"></p>
<p><input type="submit" onclick="test.affiche()" value="Effectuer le calcul"></p>
</body></html>
Upvotes: 0
Views: 568
Reputation: 23863
The variable that you are creating, test
is local to your Init
function.
When you try to access test
in your onclick
handler, it is looking for test
at the global level, which doesn't exist.
I've updated your code to use addEventListener
instead.
function Init() {
var test = {};
test.affiche = function() {
var champ = Number(document.getElementById("champSaisie").value);
alert(Number(champ + 4));
};
document.getElementById("calc").addEventListener("click", test.affiche);
}
Init();
<p>
<label for="champSaisie">Saisissez un nombre :</label>
<input type="text" id="champSaisie">
</p>
<p>
<input id="calc" type="submit" value="Effectuer le calcul">
</p>
Upvotes: 3
Reputation: 816404
test
is local to the function Init
. You cannot access it in the event handler (onclick="test.affiche()"
) because it is not global.
In this example there is no reason to put the code inside Init
at all, you can just directly put
var test= new Object;
test.affiche= function()
{
var champ=Number(document.getElementById("champSaisie").value);
alert(Number(champ+4));
};
into the <script>
. This would make test
global. There is no benefit in waiting for the page to load before creating the object.
You could also create a global variable from inside Init
.
However, the better solution would probably be to avoid globals and bind the event handler inside Init
instead of using inline event handlers.
Related: What is the scope of variables in JavaScript?
Upvotes: 2