javascript - Change selected item from inside onchange event -
in following select box:
var sval=1; function foo(v) { sval=number(v); } ... <select name="sval" onchange=" if (confirm('...?')) foo(this.value); else $(this).val(sval);"> <option value="1">1 <option value="2">2 <option value="3">3
the idea confirm selected item change. if not confirmed change old value.
- if confirm returns true, working expected
- if confirm returns false, select gets value 1, regardles of
sval
why changing selected item not work inside onchange handler?
edit: following code based on ejay_francisco's answer proper job:
var vals = 1; $("#svalue").change(function() { if (confirm('...?')) vals=number(this.value); else $(this).val(vals); });
but not clear reason inline code $(this).val(sval)
resets select 1
i've modified code , how i've done it
working fiddle :
javascript :
$( "#svalue" ).change(function() { if (confirm('...?')) { vals =$('#svalue').val(); $('#svalue').val(this.options[this.selectedindex].value); }else{ $('#svalue').val(vals); } });
html :
<select id="svalue"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option>
edited :
here's how done inline : working fiddle
html:
<select name="sval" onchange="if (confirm('...?')) {foo(this.value);sval=(this.value);} else $(this).val(sval);"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option>
javascript :
var sval=1; function foo(v) { $('#svalue').val(v); }
apparently forgot change value of sval
whatever user has clicked. code sval=(this.value);
on onchange
part.
Comments
Post a Comment