listbox onchange event question

G

Gary W. Smith

I have a list box that contains a couple items. I would like to add a
confirmation dialog to the onchange event, so if they change the
value, it will confirm the change.

Here is what I have done in the past for other things:

onclick/onchange="javascript: if (!confirm('are you sure')) return
false;"

When I do the onchange for the list box, the dialog is presented, but
selected to cancel still results in the list item being changed. I
would like to revert back to the original value in this case. To
complicate matters, we are building the list dynamically through
ASP.Net.

Any help, or sample code, would be greatly appreciated.

Thanks,

Gary
 
T

Thomas 'PointedEars' Lahn

Gary said:
I have a list box that contains a couple items. I would like to add a
confirmation dialog to the onchange event, so if they change the
value, it will confirm the change.

Here is what I have done in the past for other things:

onclick/onchange="javascript: if (!confirm('are you sure')) return
false;"

When I do the onchange for the list box, the dialog is presented, but
selected to cancel still results in the list item being changed. I
would like to revert back to the original value in this case.

As the `change' event apparently cannot be canceled (with either `true' or
`false'), and HTMLSelectElement objects have no `defaultValue' property
(like HTMLInputElement objects do), you would end up with something like

<meta http-equiv="Content-Script-Type" content="text/javascript">
...
<script type="text/javascript">
var previousValues = {};

function handleChange(o)
{
if (!window.confirm('Are you sure to change this value?'))
{
o.value = previousValues[o.name] || "";
}
}
</script>
...
<select ...
onfocus="previousValues[this.name] = this.value;"
onchange="handleChange(this);">
...
</select>

You may instead collect the values of all HTMLSelectElement objects in the
document or in the form(s) when the `load' event of the document occurs, in
order to emulate `defaultValue'. (I'd rather the W3C DOM Level 2 HTML
interface defined that property as well for those objects.)

Unfortunately, the `change' event does not bubble in the MSHTML DOM (it does
in the W3C DOM and the Gecko DOM), so you have to attach it to each
corresponding control if you are to build a cross-browser application.

Note that for this you may also need to replace `this.value' with
`this.options[this.selectedIndex] and `o.value' with
`o.options[o.selectedIndex]'. And it will not work for multi-selects.


HTH

PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top