Implementing a Modal Based on Valid Input

I'm currently developing a journal book app using Flask and Bootstrap 5. One of the features I'm working on is a deletion feature, where users can input the number of records they want to delete. I want this feature to display a confirmation modal to the user, showing the corresponding row information in the modal body. If the input is invalid (e.g. not an integer or exceeds the existing record count), Flask will show an error message using flash messaging.

HTML code snippet:

<form class="col-md-3" method="POST" autocomplete="off">
  <div class="card">
    <div class="card-body">
      <div>
        <label for="deleteform" class="d-inline">Number to delete:</label>
        <input type="text" class="form-control" id="delete_number" name="delete_number" value="1" onchange="myFunction()">
        <button type="button" class="btn" data-bs-toggle="modal" href="#confirm_modal">Delete</button>            
      </div>
    </div>
  </div>
  <div class="modal fade" id="confirm_modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Delete <span id="num_to_delete"></span> records</h5>
          <button type="button" class="btn-close"  data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <p><span id="row_text"></span></p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-color"  id='delete_entry' name="delete_entry" value="cancel">Delete</button>
        </div>
      </div>
    </div>
  </div>
</form>

JavaScript code snippet:

<script>

var number = document.getElementById('delete_number').value;
document.getElementById("num_to_delete").innerText = number;


//create_text() is function to generate modal body text
//get_row is the object corresponding to the number we want
document.getElementById("row_text").innerText = create_text(get_row);


function myFunction() {
    number = document.getElementById('delete_number').value;
    document.getElementById("num_to_delete").innerText = number;
    get_row = obj[size - Number(number)];
    document.getElementById("row_text").innerText = create_text(get_row);
}

</script>

Python code snippet: (outline of how I want the flashing messages to work)

num = request.form.get('delete_number')
if num != "":
    if num.isdigit():
        num = int(num)
        if num <= len(list_of_sheets):
            # remove last n items
            list_of_sheets = list_of_sheets[:len(list_of_sheets) - num]
            with open('file.pkl', 'wb') as
                pickle.dump(list_of_sheets, f)
            flash('Succeed', category='success')
        else:
            flash('Error', category='error')
    else:
        flash('Error', category='error')
else:
    flash('Error', category='error')

Currently, the modal will always appear regardless of the input's validity. I understand that the modal pops up before submission, while my flash message is generated after submission. I'm wondering if there's a way to conditionally show the modal – if the input is valid, show the modal, else just submit and display the error messages.

I'm not very experienced in web development, so any assistance would be greatly appreciated. 🙏

Answer №1

After experimenting with JavaScript, I came up with a solution.

var del = document.getElementById('delete_button');

function myFunction() {
    number = document.getElementById('delete_number').value;
    document.getElementById("num_to_delete").innerText = number;    

    if (isNaN(number)) {
      // not a number
      // submit form to catch error
      del.removeAttribute('data-bs-toggle');
      del.removeAttribute('href');
      del.setAttribute('type', 'submit');

    } else {
      // is a number
      if (Number(number) <= size) {
        del.setAttribute('type', 'button');        
        del.setAttribute('href', '#delete_modal');
        del.setAttribute('data-bs-toggle', 'modal');            
        
        get_row = obj[size - Number(number)];
        document.getElementById("row_text").innerText = create_text(get_row);
      } else {
        // not enough rows
        // submit form to catch error
        del.removeAttribute('data-bs-toggle');
        del.removeAttribute('href');
        del.setAttribute('type', 'submit');
      }
    }
}

This modification will activate the button to open the modal if the input is valid, and switch the button's type to submit if the input is invalid.

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

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

The submission is processed regardless in Firefox

var form0 = document.forms[0]; form0.onsubmit = function(e){ alert("form submitted"); var email = form0.elements["email"].value; var url = "https://bpi.briteverify.com/emails.json?address="+email+"&apikey=my-key&callback=emailResult"; ...

"I have successfully removed the URL from index.html. However, I am now wondering how I can include them in app

I have modified the URL in index.html to remove query parameters, but now I need my app.component.ts file to still be able to access and work with those query params using ActivatedRoute. However, when I implemented the script in index.html to remove query ...

What is the best way to alter the text of a button when the mouse hovers over it?

I'm looking to create a button that can dynamically change the text inside it when the cursor hovers over it, and then revert back to the original text when the cursor moves away from it. I attempted this in VScode using "document.getElementById().inn ...

Exploring the synergies of Next.js and Node.js thread pooling

In my current project, I am utilizing nextJS with NodeJS and looking to implement child processes or workers. The code provided by NextJS itself is functioning perfectly. The relevant code snippets: NextJS with NodeJS Another resource I referred to: Nex ...

The JavaScript error occurred: TypeError - Unable to access the property 'map' as it is undefined

import Link from 'next/link' export const getStaticProps = async () => { const res = await fetch('https://jsonplaceholder.typicode.com/users'); const data = await res.json(); return { props: { ninjas: data } } } const ...

Setting `tabBarVisible` to false does not function properly within a stackNavigation nested element

Details on my project dependencies: "react-navigation": "^3.6.0", "expo": "^32.0.0" I'm working with a TabNavigator that contains redirections to child components, which are StackNavigators. However, I'm facing an issue where I am unable to hide ...

What is the best way to implement CSS properties on Material UI components?

I've recently started exploring Material UI, but I'm having trouble understanding how the spacing properties function. I'm trying to utilize the "spacing" feature for various elements, but it appears that it only works for "Box" components a ...

Photo positioned on top of the form with Bootstrap 5

I am working on creating a responsive webpage using Bootstrap, where I need to display a large image above a form. To manage the size of the image, I have placed it inside a "peek-view" container which allows scrolling both horizontally and vertically to v ...

Using a string as the key in a setState call in React: A beginner's guide

One challenge I'm facing involves calling a state value in React through a string. For example, if the string is "greeting" and the state value is greeting: "hello world", I encounter difficulties. When trying to call this.state.greeting using the st ...

Strategies for extracting methods and refactoring to a separate file for better reusability

Still relatively new to the JQuery/javascript realm, I've put together a functional jqgrid with a datepicker and custom control (using jquery auto complete) by piecing together code samples I came across online. This code has been added to a T4 templa ...

The fadeOut() function is not functioning properly as the div keeps reappearing even after attempting to

My navigation bar has a unique feature - the subnav expands to fullscreen on hover, while all other subnavs close. However, I encountered an issue with the close button functionality. When clicked, the subnav fades out but then immediately fades back in. ...

React - Incorporating Axios catch errors directly within form components

When a user registers, my backend checks if the email and/or username provided are already in use by another user. The response from Axios catch error is logged into the web console. I want to associate each email and username with their respective fields ...

Troubleshooting: JavaScript code not functioning properly with variable input instead of fixed value

I have encountered an issue with a JS function that I'm using. The function is shown below: // A simple array where we keep track of things that are filed. filed = []; function fileIt(thing) { // Dynamically call the file method of whatever ' ...

Error encountered during sequelize synchronization: SQL syntax issue detected near the specified number

Four Sequelize Models were created using sequelize.define();. Each model is similar but with different table names. To avoid manual creation of tables in MySQL cli, the decision was made to use sequelize.sync() in the main index.js file to allow Sequelize ...

What is the process of transitioning from jQuery to plain JS for converting selectors and event capturing?

Looking for assistance in converting this code to vanilla JavaScript: document.addEventListener("DOMContentLoaded", function() { document.querySelector("textarea").addEventListener("keydown", function(event) { var textarea = this; ...

Utilizing Material-UI components for a seamless navigation button experience

After reviewing the example on https://material-ui.com/guides/composition/#button, I have implemented a button in my main page: <BrowserRouter> <Box m={2}> <Button size="large" variant="cont ...

What is the best way to create a continuous loop of images on a never-ending

Many discussions cover similar topics, but I have not yet found a solution to my specific question. Currently, I am working on creating a model for a website and I am interested in incorporating an infinite rotating gallery with a limited number of images ...

Is there a way to direct Webpack in a Next.JS application to resolve a particular dependency from an external directory?

Is it possible to make all react imports in the given directory structure resolve to react-b? |__node_modules | |__react-a | |__app-a | |__component-a | |__next-app | |__react-b | |__component-b // component-a import { useEffect } from ' ...

Can you explain the distinction between $(document) and $('*') and how can we determine which library $ is referring to?

My interpretation is this: $(document) will contain the entire DOM of the current page just like document, while $('*') also selects the entire DOM. What sets them apart, aren't they essentially the same? Will assigning $ from different lib ...