I'm in a JSF2.0 application which has many jsf files, each page could has inputs + some selectMenu . I want a concrete solution on how to display a warning message (as a Modal) when the user makes some changes in this current page (filling some inputs for example) and decide to visit other pages or close the current tabs.
-
2"I need this functionality asap." We all need our answers yesterday. – Jasper de Vries Mar 15 '18 at 10:52
-
And I need more money – Kukeltje Mar 15 '18 at 12:20
1 Answers
So there's a few parts to this.
First of all to create the modal you need a hidden div. You then need some JQuery that will detect any changes made to then pop this modal up.
You can do this by having a div looking like this with the CSS below as well:
HTML
<div class="modal hide">
<p>Content here...</p>
<button class="close">Close</button>
</div>
CSS
.hide{
display: none;
}
.modal{
position: fixed;
width: 50%;
height: 100px;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: 0 auto;
background-color: red;
color: white;
text-align: center;
}
Then add a class to anything that needs to be alerted when changed. If it's an input that has to be filled out just add the required attribute shown below For example:
<input type="text" name="example" class="change" required>
Then you can use JQuery to detect any changes and display the modal:
JQuery
$(".change").on("change", function(){
$(".modal").removeClass("hide");
});
$(".close").on("click", function(){
$(".modal").addClass("hide");
});
This then shows the modal with a button that gives the option to close it.
In regards to on leaving the page this is much more complex as you could end up giving a warning upon the user successfully submitting a form. Not to mention the user experience issues. Please refer to this answer here: Detect browser or tab closing
I've also put together a working JSFiddle for you here - https://jsfiddle.net/Rockhopper92/vsmLkqLm/

- 190
- 2
- 4
- 13
-
I think https://getbootstrap.com/docs/4.0/components/modal/ was requested by the OP. And your answer does not **cover** unsubmitted data. – Jasper de Vries Mar 15 '18 at 11:33
-
You're right it doesn't. Don't need JQuery for that just updated the answer now. Also hadn't picked up on the specific bootstrap modal part but this would still be a solution. Also nothing to stop you adding your own classes into a bootstrap modal I've done it many times. – James Mar 15 '18 at 11:50