An easy way to display an error status after clicking the next button using javascript

Whenever I input an email address, it displays an error status.

I want the error status to appear after clicking the next button. In addition, I've included a "more view friends" link that, when clicked, will display one more textbox at each link.

Currently, the error status only shows up for the first 5 textboxes and does not work for other textboxes obtained by clicking the link.

However, in my jsfiddle link, the "invite more friends" link doesn't work, but on the webpage, it functions correctly.

Javascript:

$(document).ready(function() {
    var container = $(document.createElement('div')).css({
        padding: '5px',
        margin: '0'
    });

    for (i = 0; i < 4; i++) {
        $(container)
            .append('<div><input type="text" class="input" id="tb' + i + '" placeholder="Email" /></div>');
    }
    $('#main').before(container);

    $("input", container).keyup(function() {
        validateEmail($(this));
    });
    var iCnt = 4;

    function validateEmail(el) {
        if (!isValidEmail($(el).val())) {
            $(el).parent().addClass('invalid');
            return false;
        } else {
            $(el).parent().removeClass('invalid');
            return true;
        }
    }

});

var divValue, values = '';
function GetTextValue() {

    $(divValue).empty();
    $(divValue).remove(); 
    values = '';
    
    $('.input').each(function() {
        divValue = $(document.createElement('div')).css({
            padding:'5px', 
            width:'200px'
        });

        values += this.value.trim();
        
    });

    document.all.contact_list.value = values;            
}

Can anyone help me identify my mistake and suggest how to fix it? Thank you in advance.

Answer №1

Vinod provided the correct answer, however, there is an alternative approach:

$("#main").on('keyup', 'input', function() {
    validateEmail($(this));
});

The issue here is that you are generating elements that do not exist on the page yet, hence the event is not being attached.

To learn more about this, visit the jQuery on event

In addition, the following code snippet is inaccurate:

$(container).append('<input type=text class="input" id=tb' + iCnt + '  placeholder="Email" />');

You must use double quotes:

var id = 'tb' + iCnt;
$(container).append('<input type="text" class="input" id="' + id + '" placeholder="Email" />');

Answer №2

The mistake that was made is in how the keyup event is registered:

    $("input", container).keyup(function() {
            validateEmail($(this));
        });

While this method is acceptable, the issue lies in the fact that it only affects elements that already exist. To address this, you should use .on instead:

$(outerSelector).on('keyup', innerSelector, function(ev){
    // do something
});

The key difference here is that outerSelector should target element(s) that currently exist, and the elements within them specified by innerSelector don't need to be present when the event is registered.

EDIT: Specifically addressing the problem at hand

Since there are bugs in your fiddle, I can't fully test it, but it seems like you should make this adjustment:

container.on('keyup', "input", function(ev){
    validateEmail($(this));
});

Answer №3

It appears that your issue is with the validation only working for the first 5 input boxes and not for any dynamically added ones.

If this is the case, It seems like you are only attaching the event handler initially.

$("input", container).keyup(function() {
    validateEmail($(this));
});

What you need to do is,

...
$('#btAdd').click(function() {
if (iCnt <= 19) {
    iCnt = iCnt + 1;
    // ADD TEXTBOX.
    var newTextbox = $('<input type=text class="input" id=tb' + iCnt + '  placeholder="Email" />');
    $(container).append(newTextbox);
    newTextbox.keyup(function() { //<<<< Bind keyUp for newly created textboxes also.
        validateEmail($(this));
    });
...

I hope this solution proves helpful to you.

Edit

Alternatively, you could simplify things by using the $(selector).on(); method. [answered by @Lajos Arpad]

For more information, please visit this link.

Answer №4

When the next button is clicked, you need to validate by replacing:

$("input", container).keyup(function() {
     validateEmail($(this));
});

with:

$("#form").submit(function() {
    var inputs=$('.input');
    for(i=0;i<inputs.length;i++)validateEmail(inputs[i]);
    if($('.invalid').length!==0)return false;
});

To enable the 'invite more friends' link to work, add an event handler.

$('#btAdd').click(function(){
    $(container).append('<div><input type="text" class="input" id="tb'+($('.input').length+i)+'" placeholder="Email" /> <label>This email is invalid</label></div>');
});

Answer №5

Make sure you are validating the input box with every key up event, as this is a common mistake made.

Instead, consider validating on input when the next button is clicked.

Refer to the code snippet below at line number 11

$("#nextbutton").click(function() {    
   var inputs=$('.input');
for(i=0;i<inputs.length;i++)
   validateEmail(inputs[i]);
});

This approach should work correctly

Sample

Answer №6

Check out this code snippet:

        function validateInput() {
            var input = document.login.user.value;
            if (input == "" || input == null) {
                alert("Please enter a value");
                return false;
            }
        }

Here is a live demo

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

The AngularJS Navbar is Bootstrapped

I'm currently working on a project where I need to make a bootstrap navbar show and hide html elements based on data retrieved from an angular controller. Below is the jade code snippet: div.navbar.navbar-fixed-top div.navbar-inner div.c ...

Begin the ul element from the left-hand side

Check out my latest JSFiddle creation: http://jsfiddle.net/alonshmiel/Ht6Ym/2409/ I'm attempting to align the ul element on the left side of the page: I've experimented with the following CSS rules: margin-left:0px; float: left; Unfortunatel ...

Tips for toggling the visibility of a revolution slider based on current time using JavaScript

Currently, I am integrating the revolution slider into my WordPress website. My goal is to have the slider change according to the standard time of day. For instance, I want slider1 to display in the morning, slider2 at noon, slider3 in the evening, and sl ...

I am experiencing difficulty getting my component to properly implement the bootstrap NavBar and NavIcon styles

I am new to using bootstrap with react and I am facing an issue where the dimensions are not being applied to my Navbar and Navbar Icon. I have already installed dependencies and used className instead of class, but still no changes are visible. import Re ...

Issues with width transitions in Edge when using the ::after pseudo-element

My CSS transitions on the ::after pseudo-element work perfectly in Chrome and Firefox, but not as expected in Edge. While the background color transition is functioning correctly, the width isn't. You can view my current code here: http://codepen.io/ ...

Sending data via req.body from middleware

One middleware function is defined as follows: app.use('api/', authenticate, bar); In the authenticate function, a variable is being attached to req.body like so: req.body.user = foo; However, when trying to access req.body.user inside the ba ...

Preventing window resize from affecting print screen content in Angular 8

I'm struggling with a print button feature in my Angular 8 project. When the window is resized, the content within the print window also resizes, which is not the behavior I want. I've tried a couple of solutions, but nothing has worked so far: 1 ...

Encountering an error while attempting to run bcrypt on Meteor and Nodejs - "Undefined property '_handle'."

Having trouble integrating the bcryptjs package into my Meteor app. Successfully installed bcrypt using meteor npm install --save bcrypt. Trying to implement bcrypt functions with import bcrypt from 'bcrypt';. Encountering an error in the cons ...

Are you feeling lost when it comes to Javascript? How is it possible for a boolean function to function as a

Preparing for an upcoming interview, I'm diving back into the world of JavaScript. Recently, I came across an interesting blog post that mentioned: "The delete operator returns true if the delete was successful." The blog then provided an example ...

When the nav-element is clicked, it will load the new content/file.php into the div with the id of "include."

Seeking the most efficient method to load content from a php file into a designated div on my webpage, prioritizing speed, minimal performance requirements, and ease of implementation. Unsure whether it's preferable to utilize php or javascript for t ...

Issue with the final transition of the last image in the Bootstrap carousel

I'm currently in the process of creating my own portfolio website. I've integrated a Carousel feature inspired by Bootstrap's example. However, I've noticed some glitches in the transitions between the first or second slides and the thi ...

I prefer the jumbotron to be uninterrupted by the navbar

I'm facing an issue where my jumbotron is ending up under the navbar, but I want to position it just below with some padding in between. Here's the code snippet: Take a look at the current appearance here: This is how it looks like ...

How can one update transitive dependencies to a specific newer version in npm to address CVE vulnerabilities?

Here are the packages that require upgrading. I attempted to update the version and signature of the packages listed in package-lock.json. However, whenever I run npm i after modifying package-lock.json, the changes made to package-lock.json disappear. ...

Ways to resolve the issue of setAttribute value not appearing on the UI

When using the setAttribute method to set a value in the DOM, why is it not being displayed in the user interface? https://i.sstatic.net/hZRgX.png ...

"Enhance your website with the powerful combination of SweetAlert

I'm having trouble getting my ajax delete function to work with SweetAlert. I can't seem to find the error in my code. Can someone help me figure out how to fix it? function deletei(){ swal({ title: 'Are you sure?', ...

Optimize your bootstrap carousel for mobile viewing by ensuring that the image and text are

My bootstrap carousel is displaying perfectly on desktop screens with images sized at 1200x400. However, when viewed on mobile devices, the images shrink so much that the text on them becomes unreadable. Additionally, the navigation dots at the bottom of t ...

When I'm working on iPhone css hover effects, I find that I need to include a

Why do I have to add a touch event to my element in order for it to trigger hover styles? Is this typical behavior? It seems a bit unconventional. This is the code I need to include to make :hover work; without it, no hover style is applied. Apologies f ...

Guide to incorporating rate-limiter-flexible into your current node.js express configuration

I am currently using node.js, passport, and JWT bearer token for securing my routes. However, I have yet to implement rate limiting and IP/user blocking for too many false login attempts. What is the recommended approach to integrate this into my existing ...

What could be causing the background image on my Jumbotron to fail to load?

Having some trouble with setting my image as the background of the Jumbotron. I've tried a few different approaches, but none seem to be working. It's not an issue with static loading because using img src directly into the Jumbotron section does ...

Utilize Angular2's input type number without the option for decimal values

Is there a way to prevent decimals from being entered in number inputs for Angular 2? Instead of using patterns or constraints that only invalidate the field but still allow typing, what is the proper approach? Would manually checking keystrokes with the ...