javascript - Can't assign a string to another string in an onchange = function() -
i have this:
<select id="prio" class="w60"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select>
if select value, onchange = function()
called:
var prio = document.getelementbyid('prio'); var string1 = "hello"; var string2 = ""; prio.onchange = function () { prioindex = prio.options[prio.selectedindex].text; switch (prioindex) { case '1': prioindex = " friend"; break; case '2': prioindex = " sister , brother"; break; case '3': prioindex = " mom , dad"; break; } alert(prioindex); string2 = prioindex; } alert(string2);
the alert inside function works fine not assign new string.
alert(string2)
shows string2 (undefined).
i want use string2
outside function. can't because never assigned. dont know why.
lets say, want use string2
in onchange function...
var string3; news.onchange = function () { string3 = string2.concat(' how you'); alert(string3); }
and assign string3
. if want use string3
outside onchange-function undefined
.
javascript has call 'callbacks'. callback function executed once action happens on element callback set. onchange
function executed when change prio
element on html page.
that means prio.onchange = function () { ... }
won't execute unless go html page, click on select element and change value.
thus execute once code loads browser following (it's not right understand why string2
not assigned expecting):
var prio = document.getelementbyid('prio'); var string1 = "hello"; var string2 = ""; alert(string2);
can see problem? right!!! string2
empty when alert(string2)
called! :d
you want passing string2
function within callback such following:
var foo = function ( val ) { alert('string2 value is: ' + val); }; prio.onchange = function () { prioindex = prio.options[prio.selectedindex].text; switch (prioindex) { case '1': prioindex = " friend"; break; case '2': prioindex = " sister , brother"; break; case '3': prioindex = " mom , dad"; break; } foo(prioindex); }
however if want use information in 2 different callbacks define function value whenever need it. mean:
var string2 = function () { var prio = document.getelementbyid('prio'); prioindex = prio.options[prio.selectedindex].text; switch (prioindex) { case '1': prioindex = " friend"; break; case '2': prioindex = " sister , brother"; break; case '3': prioindex = " mom , dad"; break; } return prioindex; } var string3; news.onchange = function () { string3 = string2() + ' how you'; alert(string3); }
Comments
Post a Comment