Confirming the authenticity of a newly added user input with the help of jQuery

Within my current project, I have implemented validation features for text boxes. When a user clicks on a text box, the border is highlighted. If they click elsewhere without entering any value, the border turns red and an alert pop-up appears.

In addition, there is a button that allows users to add new input boxes by using jQuery. I am interested in finding a way to apply the same validation to these newly added inputs, highlighting the border and displaying a pop-up alert when they are created using the button.

EDIT


$(function() {
     $(".options").focus(function(){
          $(this).addClass("focused");
        });
        });

     $(function() {
        $(".options").blur(function(){
          $(this).removeClass("focused");
        });
        });

     $(function() {
     $(".options").focusout(function () {
         $(this).addClass("unfocused");
            if (!$(this).val()) {
                alert("Please ensure you have answered the question.");
            }
        });
        });

     $(function() {
            $(".options").blur(function(){
              $(this).removeClass("unfocused");
            });
            });

I have provided the jQuery code above that I used for validating the existing text boxes. The "focused" class turns the border green, while the "unfocused" class turns it red with an alert message.

<div class="addtextbox"><input type="submit" class="AddOption" value="Click To Add New Option"></div>

$(function() {
     $(".addtextbox").click(function() {
         $(".addtextbox").before("<input class='options'><br>");
     });
 });

The code snippet above demonstrates how the textbox can be added through a button click event.

Answer №1

$(document).ready(function(){
  
  $(document).on("focus", ".options", function(){
    
    $(this).addClass("focused");
    $(this).removeClass("unfocused");
    
  });
  
  
  $(document).on("blur", ".options", function(){
    
    $(this).removeClass("focused");
    $(this).addClass("unfocused");
    
    if (!$(this).val()) {
       alert("Don't forget to provide your answer.");
    }
    
 });
  
  
  })

Answer №2

One option is to utilize the latest jQuery extensions that take advantage of HTML5 elements like required. By delegating the validation event, you can ensure it functions properly even during AJAX requests. When your AJAX call returns a response, consider creating input fields like:

<input type="email" required="required" pattern="{e}" />

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

Issue encountered when attempting to remove an element from an array using the delete method

Whenever I attempt to remove an input that has been added, an error message saying "Value is NULL" pops up. I'm looking for a solution where only the selected inputs are deleted when I click on DELETE, instead of all inputs being removed. The myFuncti ...

Can the HTML attributes produced by AngularJS be concealed from view?

Is there a way to hide the Angular-generated attributes such as ng-app and ng-init in the HTML code that is output? I want to present a cleaner version of the HTML to the user. Currently, I am using ng-init to populate data received from the server, but ...

Attempting to extract content from a specific span element

I've been struggling to extract the text within a <span> element from a webpage. Every attempt I've made that doesn't result in an error has come back empty, with no output whatsoever. Here is the code I'm using: import time imp ...

Developing a HTML button through Javascript that triggers a method with a single parameter when clicked

My current project involves creating HTML buttons through JavaScript using AJAX. Each time I click one of these buttons, it triggers an AJAX function. If the AJAX request is successful, it retrieves a number that will be utilized in a for loop. As the loop ...

javascriptJQuery validation function triggers JSF ajax request

I am currently experiencing a challenge with JSF ajax requests and jQuery events. I am using a jQuery event to validate a section of a form like this: jQuery(".btnNextStep").live("click", function(e) { var error = !validate(id); ... ...

Set a maximum height for an image without changing its width dimension

I am facing an issue with an image displayed in a table. The image is a graph of profiling information that can be quite tall (one vertical pixel represents data from one source, while one horizontal pixel equals one unit of time). I would like to set a ma ...

Set each item to its original position on the draggable container

I am working on a project where I have categories with lists of contacts. Each contact has user details displayed in a table with input elements. I have made the contacts draggable and the categories droppable. When moving a contact from one category to an ...

Merge the xAxis functionality with Highcharts

My issue involves a chart generated by highcharts.js. The problem arises with a line chart consisting of 5 values (5 points), each displayed on the xAxis as follows: from value 1 to value 2: 0, 0.25, 0.5, 0.75, 1. I am looking to modify this display and re ...

Is it possible to delay the loading of a page using location.href?

Trying to determine when a page has finished loading using location.href. Currently, my code is set up like this and I want certain events to occur once the page is fully loaded. I attempted using $.get but encountered issues with my existing implementatio ...

The module cannot be located due to an error: Package path ./dist/style.css is not being exported from the package

I am facing an issue with importing CSS from a public library built with Vite. When I try to import the CSS using: import 'rd-component/dist/style.css'; I encounter an error during the project build process: ERROR in ./src/page/photo/gen/GenPhot ...

Pandoc has removed all the line breaks in this text

I am currently utilizing pandoc for converting HTML to Markdown format. However, I have noticed that Pandoc tends to remove line breaks in the final output. Below is the command I am executing: pandoc -f html -t markdown_phpextra myfile.html Does anyo ...

What is the best way to position the label above the input text in a Material UI TextField component with a Start Adornment?

Struggling to figure out the right Material UI CSS class to style a reusable TextField component? You're not alone. Despite tinkering with InputLabelProps (specifically the shrink class), I can't seem to get it right. Here's the code snippet ...

Confirming whether the digit entered in jQuery is a number

My website has a user input field where numbers are expected to be entered. I wanted to find a convenient way to validate the input using jQuery. After some research, I discovered jQuery's built-in function called isDigit. This handy function allows ...

Steps for generating an observable that mirrors the structure of an observable array

I am in the process of creating an observable array using JSON data retrieved from the server. var ViewModel = function (data) { var self = this; self.list = ko.observableArray(data); self.selected = ko.observable(); } ...

Struggling to retrieve Ajax data and assign it to a PHP variable?

My Code Snippet is: <script> $(document).ready(function(){ $(".states").on('click','option',function(){ var selectedValue = $("select[id='stateId'] option:selected").val(); $.post('<?p ...

What is the best way to keep calling an AJAX function until it receives a response from a previous AJAX call

I am looking to continuously call my ajax function until the previous ajax call receives a response. Currently, the page is loading every second and triggering the ajax function, but I want it to keep calling the ajax function until the previous one has c ...

Share the hyperlink to a webpage with someone else

In my SQL command, I have a unique feature that retrieves the complete URL value of the current page: [##cms.request.rawurl##]. This code returns the entire URL. I need to send this address to another page and load it into a special div called "load-fac". ...

Emphasize specific letters in a word by making them bold, according to the user

In my app, there is a search feature that filters data based on user input and displays a list of matching results. I am trying to make the text that was searched by the user appear bold in the filtered data. For example, if the user searches 'Jo&apos ...

Accordion nested within iframe

I am facing a situation where my iframe is loaded dynamically through an onclick function. Despite trying to incorporate an accordion within the iframe, the accordion() function does not seem to be functioning as expected. Here is the jQuery code I have ...

Initially, the 'display none' CSS command may not take effect the first time it is used

I am currently working on a slideshow application using jquery.transit. My goal is to hide a photo after its display animation by setting the properties of display, transform, and translate to 'none' value. Although the slideshow application work ...