Reputation: 705
On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0.
when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost.
I have seen many posts about this but I'm very new to javascript so I could use some help.
I understand I have to use:
<script>
window.onbeforeunload= function() { return "Custom message here"; };
</script>
But how do I make it work with the combobox?
like if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.
I also want to prevent it from showing the prompt on each postback.
I would like to see an example.
Upvotes: 0
Views: 177
Reputation: 705
My solution:
<script type="text/javascript"
function setDirty() {
window.onbeforeunload = function () {
return 'The data will be lost if you leave this page!'
}
}
</script>
With the attribute onCange="setDirty()" added to the dropdownlist.
Thanks all for helping!
Upvotes: -1
Reputation: 124
If you're using JQuery
<script type="text/javascript">
$(window).bind('beforeunload', function () {
if ($("select[name='cbOrderSpareCustomer'] option:selected").index() > 0) {
return 'Your data will be lost.';
}
});
</script>
You don't want else return true or it will still prompt (at least, IE prompts)
Upvotes: 0
Reputation: 961
Follow the below steps to make this work
onchange
attribute to the combobox on serve side using the code:
<select id="cbOrderSpareCustomer" onchange="setDirty()">
Define your javascript as below
var isDirty = true;
function setDirty() {
isDirty = true;
}
window.onbeforeunload = function () {
if (isDirty) {
return confirm('Your unsaved changes will be lost');
}
}
Upvotes: 1
Reputation: 988
I think...
window.onbeforeunload = function(e) {
if (document.getElementById('cbOrderSpareCustomer').selectedIndex > 0) {
if (!confirm('Are you sure')) {
return false;
}
}
}
Upvotes: 1
Reputation: 66641
You get on client side the drop down list, and check the index, your code will probably be as:
<script>
window.onbeforeunload= function()
{
if(document.getElementById('<%=cbOrderSpareCustomer.ClientID%>').selectedIndex > 0)
{
return "Custom message here";
}
else
{
return true;
}
};
</script>
Upvotes: 2