The amount of text fields matches the quantity chosen from the dropdown selection

Click here to view the jsfiddle

HTML

<table>
<tr>
    <td>
        <select class="form-control mySelectBoxClass childage" name="noofchilds[]">
            <option selected>0</option>
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
        </select>
    </td>
</tr>
</table>

<a class="repeat">ADD MORE</a>
<a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'" class="add" style="display:none">Add Age</a>

<div id="light" class="white_content">
<div class="textboxDiv"></div><a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>

</div>
<div id="fade" class="black_overlay"></div>

CSS

.black_overlay {
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border-radius:7px;
background-color: rgba(255, 255, 255, 1);
z-index:1002;
overflow: auto;
}
.form-control {
display: block;
width: 100%;
height: 26px;
padding: 2px 0px 2px 12px;
font-size: 14px;
line-height: 1.428571429;
color: #010F2B;
vertical-align: middle;
background-color: #E6E8E9;
border: 2px solid #ebebeb;
border-radius: 4px;
-webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out  0.15s;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
   }

Javascript

$(function () {
$(".repeat").on('click', function (e) {
    e.preventDefault();
    var $self = $(this);
    $self.before($self.prev('table').clone());
});
});

$(document).ready(function () {
$(".childage").change(function () {
    var selVal = $(this).val();
    $(".textboxDiv").html('');
    if (selVal > 0) {
        $(".add").css("display", "block");
        for (var i = 1; i <= selVal; i++) {
            $(".textboxDiv").append('<input type="text" class="form-control" /><br>');
        }
    } else {
        $(".add").css("display", "none");
    }
});
});

The main goal of this code is to create a popup that displays a number of text fields equal to the value selected. While the functionality works fine in this code, there is an issue with duplicating the select box and applying the same functionality to all created select boxes. Please review the fiddle provided and suggest any potential solutions.

Answer №1

Check out the code snippet below:

HTML

<div class="repeatElement">
<table>
    <tr>
        <td>
            <select class="form-control mySelectBoxClass childage" name="noofchilds[]">
                <option selected>0</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>
        </td>
    </tr>
</table>
<a href="javascript:void(0)" class="add" style="display:none">Add Age</a>
</div>

<a class="repeat">ADD MORE</a>

<div id="light" class="white_content">
    <div class="textboxDiv"></div><a href="javascript:void(0)" id="close">Close</a>

</div>
<div id="fade" class="black_overlay"></div>

jQuery:

$(function () {
    $(".repeat").on('click', function (e) {
        e.preventDefault();
        var $self = $(this);
        $self.before($self.prev('.repeatElement').clone());
    });

    $(document).on('change','.childage',function(){
       var selectVal = parseInt($(this).val()) || 0;
        if(selectVal > 0)
            $(this).closest('table').next('.add').show();
        else
            $(this).closest('table').next('.add').hide();
    });

    $(document).on('click','.add',function(){
        var selVal = $(this).prev().find('.childage').val();
        $(".textboxDiv").empty();
        for (var i = 1; i <= selVal; i++) {
                $(".textboxDiv").append('<input type="text" class="form-control" /><br>');
        }
        $('#light').show();
        $('#fade').show();
    });

    $('#close').click(function(){
       $('#light').hide();
        $('#fade').hide();
    });
});

JSFiddle Demo

Answer №2

If you want to dynamically update the total number of textboxes based on input values using jQuery, you can utilize the .live() method like this:

$(document).ready(function () {
    var sum = 0;
    $(".childage").on('change', function () {
        var selectedValue = $(this).val();
        sum = parseInt(sum) + parseInt(selectedValue);
        $(".textboxDiv").html('');
        if (selectedValue > 0) {
            $(".add").css("display", "block");
            for (var i = 1; i <= sum; i++) {
                $(".textboxDiv").append('<input type="text" class="form-control" /><br>');
            }
        } else {
            $(".add").css("display", "none");
        }
    });
});

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 are the best practices for correctly implementing Angularjs ng-repeat?

As a newcomer to angularjs, I am in the process of building an app where the output is already set up correctly. However, I am looking to achieve the same without relying on jQuery, and instead want to utilize the angularjs method using "ng-repeat". Below ...

Creating a new attribute within a JavaScript object by utilizing the properties of its sibling elements

Imagine a scenario where you have a complex array of objects structured like this: [ { "title": "Fundamentals", "order": 1, "lessonRef": "fundamentals", "children": [ { "title": "History", "order": 1, "lesso ...

What is the best way to store textarea information into a session using the jQuery AJAX post method in Codeigniter?

I am having trouble saving the text from a textarea to the Controller session using jQuery AJAX post method in Codeigniter Smarty. I am unable to save the data to the session. Can someone please provide me with guidance and a detailed example of how to ach ...

Having trouble locating the name 'div' when starting a new React project?

After creating a new React application using the command: "npx create-react-app poi-search --template typescript", ESLint prompted me for permission and then displayed several errors. You can view the screenshot here. I am currently using the latest versi ...

Adjusting the width of a <div> element based on window size changes

So I have this Vuejs application that has three divs using CSS grid: a sidebar, a config panel, and a preview. I want to dynamically set the width of the preview div in pixels based on the current screen size and when the screen is resized. To give a bett ...

Using AJAX to retrieve a specific JSON object from an array of JSON data

Data retrieved in JSON array from the API: [{"id":"001", "name":"john", "age":"40"}, {"id":"002", "name":"jane", "age":"30"}] Using Ajax: $.ajax({ url: 'interface_API.php', ...

Can SCSS be used in conjunction with Less in a backwards compatible manner?

Can scss be considered backwards compatible with less? Personally, I have my doubts. One key difference is that while less uses '@' to prefix variables, scss opts for '$'. Changing the variable prefix might not be enough, as there are l ...

What is the best way to create a CSS flexbox row that does not span the full width of the screen?

Looking to display 4 images in a grid layout of 2 by 2, I'm trying to avoid having each image take up 50% of the screen for aesthetic reasons. Any suggestions on how to achieve this? I've attempted setting the flex-direction to column, but it re ...

What steps should I take to create an in-site product filtering system with multiple dropdowns by utilizing a JSON file?

I have created an in-site redirect tool for our E-Commerce platform by utilizing resources from this website. I am looking to enhance the functionality of these in-site redirects by implementing a JSON file that contains options tailored to our existing li ...

Verifying the presence of an object in an array based on its value using TypeScript

Having the following dataset: roles = [ {roleId: "69801", role: "ADMIN"} {roleId: "69806", role: "SUPER_ADMIN"} {roleId: "69805", role: "RB"} {roleId: "69804", role: "PILOTE"} {roleId: "69808", role: "VENDEUR"} {roleId: "69807", role: "SUPER_RB"} ] The o ...

What makes fastify-plugin better than simply calling a regular function?

I recently came across a detailed explanation of how fastify-plugin operates and its functionality. Despite understanding the concept, I am left with a lingering question; what sets it apart from a standard function call without using the .register() metho ...

The custom CSS cursor appears to be displaying in a pixelated manner

Trying to experiment with custom cursors, but every attempt ends up pixelated. I created a ring asset to demonstrate the issue. Here is the cursor image file. cursor: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/272259/circle.png), auto; Although it ...

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...

Sending an ID from an array within a *ngFor loop to a different component in Angular: a step-by-step guide

I have a collection of items that I loop through using ngFor. My goal is to pass all its attributes to another component. I attempted to accomplish this with the following code: *ngFor='let item of postList [routerLink]="['/detailed-post&ap ...

Issues with Css custom properties on certain webhosting platforms

Seeking assistance with a CSS custom properties issue. Recently purchased a web hosting service from Hostinger and using the default Wordpress template. Our web designer created a website in teleporthq.io, exported the files as HTML and CSS. Deleted the ...

Is it possible to use Bootstrap's Accordion or Alert styles with HTML elements <details> and <summary>?

For my projects, I typically utilize Bootstrap for styling and usually do not include any Javascript as it is unnecessary. However, I am now working on a project that requires a feature similar to Bootstrap's Accordion, which does require Javascript t ...

Localization in ASP.NET MVC using unobtrusive jQuery

Is there a way to translate error messages in models without using DataAnnotations? For example, I only want to translate part of the message "The field XX is required" with jQuery globalization, without using [Required(ErrorMessageResourceName="----")] at ...

Issue with Custom CSS Class Not Displaying Correctly

I have implemented some unique CSS styles on a group of posts. You can view the site here. Upon inspecting the CSS classes of the posts, you will notice that the last two classes are .floats and .colThree. .colThree is being applied correctly with no issu ...

jQuery enables the toggling of child elements with a specific class (handlers) upon clicking

My goal is to change the style of a specific child element when I click on its parent. I was able to achieve this using event handlers: $(".p1").on({ mouseenter: mouseEnter, mouseleave: mouseLeave }); function mouseEnter() { $(this).css(&apos ...

How to Create Smooth Transitions for Text Arrays using jQuery's Fade In and Fade Out Features

I need to loop through an array of text and apply jQuery's fadeIn and fadeOut functions to each element. var greetings = ["hi, I'm", "bonjour, je m'appelle", "hallo, ich heiße"] The HTML structure I want is as follows: <h2><span ...