Doesn't seem like jQuery's .blur() is responsive on dynamically created fields

I am currently designing a login form that includes a registration form as well. Using jQuery, the email field is generated dynamically.

The labels are positioned below the fields so that they can be placed inside the field. As the field gains focus or has content in it, the label moves above the field.

However, this functionality seems to work fine for the username and password fields but not for the email field. The reason behind this issue is unknown.

For reference, here's the link to the codepen:

http://codepen.io/andornagy/pen/waoyZB

$(document).ready(function(){

    var inp = $('#emailhere');
    var i = 0;
    var emailField = $('<section class="emailc"><input type="email" name="email" id="email" class="field"><label for="email" class="email">E-mail</label></section');

    // Do stuff when you click to show register form
    $('ul.tabs li.register').click(function(){

        $('#do').val('register');

        $('.button').val('Register');

        if ( i < 1 ) {

            $('#emailhere').after(emailField);

        };

    });

    // Do stuff when you click to show login form
    $('ul.tabs li.login').click(function(){

        $('.emailc').remove();

        var i = 0;

        $('#do').val('login');

        $('.button').val('Login');

    }); 

    // Moving the input labels correctly.
    $('#login').on("blur", "input",function() {

        // Make the label stay above if the field is not empty.
        if( this.value ) {
            $(this).next().addClass('notEmpty');
        }

        // Make the label go back on the field if the field is empty.
        if( !this.value ) {
            $(this).next().removeClass('notEmpty');
        }

    });

});
@import url(http://fonts.googleapis.com/css?family=Roboto+Slab);

body {
    margin: 0;
    padding: 0;
    background-color: #4A5043;
    font-family: 'Roboto Slab', serif;
}

.clear:after {
    display: block;
    content:" ";
    clear: both;
}

/* The Base container styles
===================================*/

.tabs {
    display: block;
    margin: -25px -25px 40px -25px;
    padding: 0;
    border-bottom: 3px solid #FFFFFF;
}

.tabs li {
    display: block;
    list-style: none;
    float: left;
    width: 125px;
    margin: 0;
    padding: 15px 25px 19px 25px;
    font-size: 22px;
    color: #FFFFFF;
    text-align: center;
}

.tabs .login {
    border-right: 1px solid #FFFFF;
}

#form {
    width: 300px;
    margin: 150px auto;
    background-color: #5C505A;
    padding: 25px;
}

#form .field {
    display: block;
    padding: 10px;
    font-size: 22px;
    margin-top: 14px;
    border: 3px solid #FFFFFF;
}

#form .button:focus,
#form .field:focus {
    outline: none;
    border-color:; #000000;
}

#form .field + label {
    position: relative;
    bottom:42px;
    padding: 10px;
    font-size: 22px;
    color: #5C505A;
    z-index: 999;
}

#form .field + .notEmpty,
#form .field:focus + label {
    bottom: 88px;
    color: #FFFFFF;
}

#form label:focus + label {
    bottom: 0;
    color: #5C505A;
}

#form .button,
#form .button:hover,
#form .field + label,
#form .field:focus + label {
    transition: 0.5s bottom,
                0.5s color,
                0.5s border-color,
                0.5s background-color;
}

#form .button {
    display: block;
    width: 294px;
    padding: 10px;
    font-size: 22px;
    border: 3px solid #FFFFFF;
    background:none;
    color: #FFFFFF;
}

#form .button:hover {
    color: #5C505A;
    background:#FFFFFF;
}
<!-- #form container -->
<section id="form">

    <ul class="tabs clear">
        <li class="login">Login</li>
        <li class="register">Register</li>
    </ul>
    <!-- #login container -->
    <section id="login">

        <!-- Login form -->
        <form name="login" action="#">

            <!-- Username field -->
            <p>
            <input type="text" name="username" id="username" class="field">
            <label for="username">Username</label>
</p>
            <div id="emailhere"></div>

            <!-- Password field -->
            <input type="password" name="password"id="password" class="field">
            <label for="password">Password</label>

            <!-- hidden value for validation -->
            <input type="hidden" id="do" name="do" value="login">       

            <!-- submit button -->
            <input type="submit" class="button" name="submit" value="Login">

        </form><!-- /ends Login form -->

    </section><!-- #login ends -->

    <!-- #register container -->
    <section id="register">

    </section><!-- #register ends -->

</section><!-- #form ends -->

Answer №1

After reviewing your code, consider trying this approach...

$('#login').on("blur", "input", function() {

...instead of using...

$('#login input').blur(function() {

The issue you are encountering is likely due to the dynamic field not being present at the time your code initializes the blur event. By using #login, the input can be located when it is added dynamically.

By utilizing the on method, it applies the event handler to #login, which is static, and then targets any input elements regardless of when they were created. Essentially, it functions similar to jQuery's find method for locating input elements.

This way, your code is effectively "attached" to #login while monitoring all input tags, whether they existed prior or were added later on.

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

When using multiple select tags with *ngFor in Angular, modifying the value of the first select tag will have an

<table id="DataTable" border="1" ALIGN="center"> <tr ALIGN="center"> <th>name</th> <th>address</th> <th>number</th> <th>type</th> </tr> <tr class="tcat" *ngFor ...

When using JSON.Stringify in a React App, it only displays the first item and the length of the object instead of all the other items

Working on a React App, I encountered an issue while trying to convert an array to JSON and send it to the server. My approach was like this: console.log(JSON.stringify(mainArray)) I anticipated seeing output like this during testing: "breakfast": { ...

The functionality of OnPress for React Native Google Places Autocomplete is hindered by its surrounding parent components

I'm currently implementing the react-native-google-places-autocomplete library in my React Native application. However, I've encountered an issue when trying to select an address from the suggested list provided by Google. Whenever I click on a s ...

Guide to locating and substituting two integer values within a string using JavaScript

Given a string such as: "Total duration: 5 days and 10 hours", where there are always two integers in the order of days and then hours. If I need to update the old string based on calculations using fields and other values, what is the most efficient meth ...

Definitions that are displayed dynamically when hovering over a particular element

I am seeking a way to implement popup definitions that appear when a div is hovered over. My website showcases detailed camera specifications, and I want users to see a brief definition when they hover over the megapixel class called '.mp'. One o ...

how to dynamically update a button's text using Vue.js

I have a challenge where I need to dynamically change the text of a button based on whether a value is true or false. Below is the code snippet that I have been working on: <button class="btn btn-primary table-button" type="button&quo ...

Could you advise on the best placement for my upcoming JQuery animation?

Here is the code I am currently working with: $(function() { $("button").click(function() { $("#box1").animate({ left: $(window).width() - 800 }, { complete: function() { $("#box1").hide(); } }); $("#box2").a ...

Ways to incorporate a smooth transition between the opened and closed fab functionality

I am currently utilizing VueJS and Vuetify in my project. I have successfully implemented Vuetify's FAB component, which displays a list of fab buttons as demonstrated in the documentation: <div id="fab-button"> <v-speed-dial v-mo ...

update confirmed data from a record

I am facing a unique challenge, where I have an edit form that updates a record in a table. One of the fields, let's say username, needs to be unique. To validate this, I am using the jQuery validation plugin along with the remote method as shown belo ...

Tips for getting JavaScript to identify a context_dict object from views.py in Django

Recently, I inherited a Django project from a former colleague and now I need to make some changes to the code in order to add a new line to a Google Viz line chart. As the line chart already exists, my approach is to closely follow the logic used by my p ...

What is the best way to implement Angular 2 slash routes in conjunction with Node Express?

I have defined some routes in my App component: @routeConfig([ { path:'login', name: 'Login', component: Login }} Additionally, I have a basic node express loader set up: var express = require('express'); var ...

Loading pages asynchronously using Ajax with added interactivity through custom JavaScript scripts

Using jQuery Masonry in conjunction with another JavaScript for voting, here is the code: <div id="contain"> <?php $result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20"); while($row = mysqli_fetch_array($result ...

Using CSS files in the web directory in CakePHP and connecting them to HTML

Could someone offer some help with cakephp? I'm experiencing an issue related to routes that I can't seem to resolve. I've organized all my css files in webroot/css within my app. In my default layout, I included a html link <link href=" ...

Creating a default option of "please select" on an Angular select element with a null value for validation

Within my Angular application, I am using a select element with an ngFor loop: <select formControlName="type" required> <option *ngFor="let type of typeList" [ngValue]="type.value">{{ type.caption }}</option> </select> When view ...

What is causing the issue of subdomains not functioning properly in express.js?

Currently, I am conducting some local experiments and have made changes to my hosts file. Here are the entries: 127.0.0.1 example.dev 127.0.0.1 www.example.dev 127.0.0.1 api.example.dev Below is the code I am using: var subdomain = req ...

Is it necessary to mark all checkboxes in the initial column of the gridview?

I have encountered an issue with my code that checks all checkboxes in the first column of a gridview. It seems to work only for Internet Explorer versions 5.0 to 8.0, but gives a Javascript error when running on IE 9 and above stating "Function Expected ...

Using Javascript, delete all chosen HTML elements containing innerText

Looking to extract certain HTML tags from a block of code in TextArea1 and display the modified output in TextArea2 upon clicking a button. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8&quo ...

The UTF-8 encoded string in Node.js displays a mysterious black question mark

I am facing an issue with a CSV file that I receive from my supplier. They have encoded a string using UTF-8, resulting in black question marks appearing. Despite several attempts, I am unable to convert it back successfully. var common = req ...

Updating an added row with jeditable and the on() method in jQuery version 1.7 triggered by a button click

I am facing an issue with my data table. I have the ability to add rows from a button at the top of the table and select rows as well. However, I want to be able to edit those selected rows, even if they are newly added. Currently, I am able to use a code ...

jQuery event.preventDefault not functioning as expected

I am attempting to use jQuery's preventDefault() method, but when I submit the form, it still displays the default behavior and reloads the page. Here is the code from index.html: <body> <script src="/socket.io/socket.io.js"></script& ...