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

What is the method to activate sequential selection through JSON response?

I just started exploring angularjs and I'm interested in selecting values step by step. But first... Here's the JSON response I received: [ { "countryname": "India", "states": [ { "statename": "Karnataka", ...

Resolving problems with PHP source and JSON in jQuery autocomplete feature

My goal is to implement a jquery autocomplete feature with PHP, but I am facing an issue with the data structure required for each record in the autocomplete. Currently, I have successfully achieved this without PHP using the following code: $(function() ...

Transform the date into the specified ISO format of YYYY-MM-DDThh:mm:ss.sTZD

I am looking to transform a date into the ISO format YYYY-MM-DDThh:mm:ss.sTZD using JavaScript. Currently, I am able to convert the current date string into the format yyyy-MM-dd'T'HH:mm:ss.SSSZ. For example: 2016-01-11T02:40:33.117Z. However, I ...

Getting rid of an Ajax loader graphic after a period of time

After a button is clicked, I have an ajax loader that appears and here is the code snippet: jQuery(document).ready(function($) { $('#form').on('submit', function() { $('#submit').css('display', 'bl ...

Utilize a custom function on dynamically generated elements

I am utilizing the following jQuery function: $("#agenda_image_1,#agenda_image_2,#agenda_image_3").PictureCut({ InputOfImageDirectory : "image", PluginFolderOnServer : "../xxx/modules/xxx/assets/js/jQuery-Picture-Cut-master/", Fol ...

Trouble achieving center alignment of navigation bar using @media query in Firefox and IE

Looking for help with creating a video hub that includes a navigation bar? Instead of using an accordion nav collapse, I prefer the menu to carry onto the next line and be centered. Here is the code snippet I used to achieve this effect: @media screen and ...

What could be causing my image not to show up on ReactJS?

I'm new to ReactJS and I am trying to display a simple image on my practice web app, but it's not showing up. I thought my code was correct, but apparently not. Below is the content of my index.html file: <!DOCTYPE html> <html> & ...

What is the process for developing multiple screens or views in PhoneGap?

Currently working on a reading app and decided to give phoneGap a shot for the first time. I'm pretty proficient in HTML, CSS, and JS, but not very familiar with xCode. In this app, I plan to have a button on the home screen that redirects users to an ...

Interactive website information

Currently, my website features a jQuery UI navigation system and utilizes ajax to dynamically update content by swapping div ids from one html file to another. However, this method still involves multiple HTML files which can become cumbersome. I am curiou ...

Adjust the size of images using jQuery to perfectly fit the container dimensions

I am currently working on a script to automatically resize images that are too large for the container: $('img').each(function(i){ var parent_width = parseInt($(this).parent().width()), image_width = parseInt($(this).width()); ...

Is there a maximum size restriction for submitting forms using jQuery's AJAX method?

I am searching for a way to submit a form without having to load a new PHP page. The form I need to submit contains both file upload and textarea fields, which means it may contain large data that needs to be submitted. While looking through various tutor ...

Is nesting possible with the &:extend function in LessCss?

I've recently been exploring the Less &:extend feature. My goal is to nest multiple extends - essentially extending a class that itself extends another class. However, after testing it out, I'm not sure if it's working as expected. It ...

How can I loop through elements and add their ID attributes to an array using jQuery?

I need help identifying a group of <label> elements within a form using an array of element IDs. For example, given the array: [ input#country , input#other-country ], I want to match <label for="country">, <label for="other-country">, a ...

Implementing a function when a grid's action column is clicked

I am facing an issue with a yii grid that includes an action column with custom buttons. I want to call a function when one of the buttons is clicked, but I keep getting an error. Here is the code snippet: [ 'class' => 'kartik&b ...

Using HTML input checkboxes in conjunction with a JavaScript function

After creating a basic payment form using HTML/CSS/JS, I wanted to implement checks on user inputs using HTML patterns. In addition, I aimed to display a pop-up alert using JS to confirm the form submission only after all necessary inputs are correctly fil ...

The print preview is unable to display all of the barcode images

Currently, I am utilizing the Jqprint plugin for printing purposes. Here is the code snippet for printing a barcode: HTML Code: <div class="wrapper_template" id="print_template"> <div class="imageOutput" > // Insert Barcode Printing Code ...

Using jQuery, stop any click or touchstart events on child elements of the target element

Below is my current jQuery code: $(document).on('click touchstart', function (e) { if ( (!$(e.target).hasClass('sb')) ) { $('#features .sb .screen').animate({ top: '6.438em' }, 150); } } I want to twea ...

Troubleshooting issue with AJAX asynchronous call to PHP function for updating MYSQL database records

Having an issue with the following script: $(function (){ $('.press_me').click(function(){ var request = $.ajax({ type: "POST", url: "counter.php" ...

I am looking to transmit information from flask to React and dynamically generate HTML content based on it

index.py @app.route('/visuals', methods=["GET", "POST"]) def visuals(): global visclass return render_template('visframe.html', images=visclass.get_visuals()) visframe.html <div id='gallery'></div> { ...

Select the correct nested div with the same name by clicking on it

My problem involves nested div elements with the same class. For example, I have a Panel inside another Panel. However, when I click on the inner panel, it is actually the outer panel that triggers the $(".panel").click function. What I need is for the ...