Creating a notification for specific choices in a dropdown menu

I am working on a form that includes a select element with multiple options. Depending on the option selected, a different form will be displayed.

My concern is if a user starts filling out one form and then decides to select another option, I want to add an alert asking if they want to clear the form they have already started filling out if they confirm. Is this possible?

$("select").change(function () {
$('div.box').hide();
    $('div.box.'+$(this).val()).show();
});


<h2>SELECT YOUR TEST!</h2>

                <select id=a>
                    <option value="chem">Chemical Analysis Testing Request Form</option>
                    <option value="fat">Fatigue Testing Request Form</option>
                    <option value="hard">Hardness Testing Request Form</option>
                    <option value="neutral">Neutral Salt Spray Testing Request Form</option>
                    <option value="stress">Stress Corrosion Testing Request Form</option>
                    <option value="tensile">Tensile Testing Request Form</option>
                </select>                             





                <!-- Test One -->


                <div class="chem box">

                <h2>Chemical Analysis Testing Request Form</h2>


                <label>Accreditation / Approval required:</label><br>
                <input type="checkbox" value="ISO17025/UKAS">ISO17025/UKAS<br>
                <input type="checkbox" value="Nacap">Nacap <br>
                <input type="checkbox" value="other">Other 
                <br>
                <br>
                <br>
                <label>Material / Allow type:</label>
                <input type="text">
                <br>
                <br>
                <br>                
                <label>Can a Drawing be Supplied:</label><br>


                Yes<input type="radio" onclick="yesnoCheck();" name="yesno" id="yesCheck"> 
                No<input type="radio" onclick="yesnoCheck();" name="yesno" id="noCheck">

                <br>       

                <div id="ifYes" style="display:none">               
                Image upload: <input type='file' id='yes' name='yes'><br>
                </div>

                <div id="ifNo" style="display:none">
                If no can you sepcify form and dimensions:<br>
                <textarea type='text' id='other3' name='other3'></textarea><br>






                </div>

To see a demo, click here: Demo fiddle

Answer №1

Check out this helpful code snippet: example and see an example with a clear form here

var hasFormChanged = false;
$("select").change(function () {
    var option = $(this).val();
    if(hasFormChanged)
    {
        var confirmChange = confirm ('Your changes will be lost, proceed?');
        if(confirmChange)
        {
            $('div.box.active').find('input[type=text]').val('');
            $('div.box.active').find('input[type=radio],[type=checkbox]').prop('checked',false);
            displayForm(option);

        }else
        {
            return false;
        }
    }
    displayForm(option); 

});

function displayForm(option)
{
    $('div.box').removeClass('active').hide();

    $('div.box.'+option).show().addClass('active');
    hasFormChanged = false;
}

$('div.box').find('input').on('change',function(){
hasFormChanged = true;
});

Answer №2

If you need to prompt the user for confirmation before proceeding, you can utilize a confirm box like this:

if ( confirm("Are you sure you want to delete this item?") ) {
    // implement logic to delete item
}

Check out this updated example.

If you prefer not to use the default confirmation dialog, you have the option of creating your custom popup or making use of a library such as jQuery UI Dialog for more advanced functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying div content as null in jQuery dialog initiated with AJAX

Utilizing ajax, I have developed a dialog that includes a table. This method was necessary due to the complexity of nested MySQL queries based on a variety of dynamically generated factors and user selections. The functionality works seamlessly. My goal i ...

validating price ranges with the use of javascript or jquery

<!DOCTYPE html> <html lang="en"> <head> <title>My Page Title</title> </head> <body> <form method="post" action="process-form.php"> Price Range: From <input type="text" id="price-from"> ...

What is the best way to create a delay so that it only appears after 16 seconds have elapsed?

Is there a way to delay the appearance of the sliding box until 16 seconds have passed? <script type="text/javascript"> $(function() { $(window).scroll(function(){ var distanceTop = $('#last').offset().top - $(window).height(); ...

Is it possible to utilize JSX independently of React for embedding HTML within a script?

Is it possible to incorporate inline HTML within a script using a library such as jsx? <script src="jsx-transform.js"></script> <script type="text/jsx"> define('component', function () { return (<div>test html code< ...

Flex items are overflowing, rather than adjusting their size

Here .header { display: flex; font-family: monospace; background: papayawhip; align-items: center; justify-content: space-between; margin-left: auto; } ul { display: flex; background: papayawhip; gap: 10em; list-style-type: none; f ...

Is it possible to run quirks mode in one frame while running standards mode in another?

Back in the IE6 days, I developed an old application that relies on frames instead of iframes and runs in quirks mode. Now, I'm wondering if it's possible to have one frame remain in quirks mode while another operates in standards mode when using ...

The alignment of flexbox within a list item is not positioned at the top as expected

When I place a flexbox inside a list item, the content is being pushed down by what seems to be a full line height. I have tried various CSS properties like setting margin-top: 0 for the flexbox, margin-top: 0 for its children, adding flex-wrap to the fle ...

Exploring unit tests: Customizing an NGRX selector generated by entityAdapter.getSelectors()

Let's imagine a scenario where our application includes a books page. We are utilizing the following technologies: Angular, NGRX, jest. To provide some context, here are a few lines of code: The interfaces for the state of the books page: export int ...

When making jQuery Ajax calls, the $_POST variable may be empty and a warning about headers already being sent may also

I've been working on a PHP project and encountered an issue with sending data from an HTML page using jQuery Ajax to another PHP page. After numerous attempts to debug the problem, I still can't figure out why $_POST is empty when I try to echo. ...

Solving layout issues / Techniques for determining element heights

This new question is in relation to my previous one: How to position relative elements after absolute elements I have updated the JsFiddle from that question to better represent my current HTML, which I unfortunately do not have a URL for at the moment. Y ...

Error message 'MODULE_NOT_FOUND' occurs while executing a Docker application

Although I successfully created a docker image, I am encountering issues when trying to run it. This is the command that I am using for running: docker run coderpc/test-server Displayed below is the error message that appears in the console. Error: Canno ...

How to make views in React Native adjust their size dynamically in a scrollview with paging functionality

Has anyone successfully implemented a ScrollView in React Native with paging enabled to swipe through a series of images? I am having trouble making the image views fill each page of the scroll view without hardcoding width and height values for the image ...

I am having trouble with my jQuery login function not properly connecting to the PHP file

Hey there, I've been working on creating a login system from scratch by following an online tutorial. The initial Javascript is functioning properly as it detects errors when the inputs are empty. However, once I enter text into the input fields and c ...

Encountering silence: React JS fetch call left unanswered by Sinatra server

Exploring the realms of Sinatra and React JS, I am venturing into making a GET call from my React website to a Sinatra server in order to display plain text. The Sinatra Server script: require 'sinatra' set :root, 'lib/app' before d ...

Is the format of this HTML tag correct?

I was provided with a code from our design department to add to a page, and since I am relatively new to the design aspect of things, I'm seeking clarification. Is this a valid tag? Also, what does <--if subcontent add rel="test1"--> mean? The c ...

Having trouble applying CSS styles to an element using JavaScript

Hello, I have an unordered list with some list elements and I am trying to apply a CSS style to highlight the selected list element. However, the style is not taking effect as expected. function HighlightSelectedElement(ctrl) { var list = document.ge ...

Ensuring the safety of JavaScript requests made to a Web Service

In my project, there is a page that triggers a JSon script when a button is clicked. This script interacts with a web service. To ensure security, the code behind the page generates a script containing an object with a unique code. This code is then added ...

I am in the process of creating several checkboxes and am looking to incorporate some added functionality

Currently, I am working on a project that involves creating multiple checkboxes. My goal is to implement a specific functionality where only one checkbox can be checked in each group with the correct or incorrect value. Once all groups have been selected, ...

How to Transform JSON Element into a JavaScript Array in AngularJS?

Implementing AngularJS to fetch values in JSON format using $resource call. The model element I require is a Javascript array structured as: [ [1328983200000, 40], [1328983200000, 33], [1328983200000, 25], [1328983200000, 54], [1328983200000, 26], [1328 ...

I'm encountering a RangeError in nextjs when trying to pass props to a child component

I'm a beginner with Next.js. I've been attempting to pass props to a child component that is a response from an API call. However, every time I try to add the props in the child component, I encounter a RangeError: Maximum call stack size exceed ...