Incorporate a checkbox that dynamically changes with the input type number

I'm trying to figure out how to dynamically add checkboxes when the input type number is changed.

Currently, I have the following HTML code:

HTML CODE

<label for checkbox_number>Number of checkboxes :</label>
<input id="checkbox_number" name="checkbox_number" type="number" size="1" maxlength="1" value="1" onkeydown="change_cb()"/>

<input id="checkbox1" type="checkbox" name="checkbox[]" value="cb1">

If I change the checkbox number to 2, I want JavaScript/AJAX to add:

<input id="checkbox2" type="checkbox" name="checkbox[]" value="cb2">

Similarly, if I change the checkbox number back to 1, I want it to remove one checkbox.

I previously achieved a similar functionality with tables (adding/removing rows) but in this case, I'm not sure how to add new elements (I only added new rows in my first script)...

I need assistance in writing my JS function change_cb()


EDIT TO PROVIDE MY SOLUTION

I managed to solve this issue with some help from DADE (thank you DADE):

HTML CODE (same)

<label for="cb_number">How many checkboxes ?</label>
<input id="cb_number" name="cb_number" type="number" size="1" maxlength="1" value="1">
<div class="my_cb_result"></div>

jQuery CODE

$(window).ready(function() {
    $('#cb_number').on('keyup mouseup', function() {
        var number = parseInt($(this).val());
        $('input[type="checkbox"]').remove();
        $('label[class="to_del"]').remove();
        for (var i=1;i<=number;i++) {
            var data = '<label for="checkbox" class="to_del">Label of my checkbox</label><input id="checkbox'+i+'" type="checkbox" name="checkbox[]" value="'+i+'">';
        }
        $('.my_cb_result').append(data);
    });
});

JSFiddle with comments

Answer №1

Give this a shot:

let newElement = '<input id="checkbox2" type="checkbox" name="checkbox[]" value="cb2">';
document.getElementById("yourElementID").appendChild(newElement);

Answer №2

Here is an example of HTML code:

<label for checkbox_number>Enter the number of checkboxes :</label>
<input id="checkbox_number" name="checkbox_number" type="number" size="1" maxlength="1" value="0">
<div class="inputs"></div>

And here is the corresponding JavaScript code:

$('#checkbox_number').on('keyup mouseup', function() {
    var number = parseInt($(this).val());
    $('input[type="checkbox"]').remove();
    for (var i=1;i<=number;i++) {
        var data = '<input id="checkbox'+i+'" type="checkbox" name="checkbox[]" value="cb'+i+'">';
        $('.inputs').append(data);
    }
});

You can also check out the JSFiddle link with comments for more information.

Answer №3

Are you asking whether the second checkbox should be rendered if the value of checkbox_number is set to "2"?

If that's the case, you can use an event like onblur on checkbox_number to trigger a function that will create and display the new checkbox using getElementById and appendChild.

For example:

<script type="text/javascript">
function change_cb() {
var secondCheckbox = '<input id="checkbox_number2" name="checkbox_number" type="number" size="1" maxlength="1" value="1" />';
document.getElementById("yourForm").appendChild(secondCheckBox);
}
</script>

<div id="yourForm">

<label for checkbox_number>Number of checkboxes :</label>
<input id="checkbox_number" name="checkbox_number" type="number" size="1" maxlength="1" value="1" onblur="change_cb()"/>

<input id="checkbox1" type="checkbox" name="checkbox[]" value="cb1">

</div>

Just so you know, based on your description, it seems like Ajax may not be necessary in this scenario.

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

Leveraging the async library in Node.js to execute multiple tasks in parallel by passing an array

In the code snippet below, there is a function that fetches data in parallel. After the data is fetched, the result can be accessed through the 'results' variable in the callback function. Instead of hard coding 'products', 'images ...

New issue with installing npm cra

Recently updated to npm version 6.14.4 and encountered an issue while trying to create a new app with cra-template. How can I resolve this problem? npx create-react-app sphinx.ui.react Error Log 50 timing stage:runTopLevelLifecycles Completed in 5234ms ...

"The HTML5 feature that triggers an event when a selection is changed is known as

Is there a universal HTML5 event that functions similarly to the IE legacy onselectionchange, triggering when the current selection is altered? UPDATED, I am interested in monitoring changes to the Selection object. ...

Deleting an element from an array in JavaScript

I am working with a JavaScript array that I need to store in local storage. var myArray; myArray = [1,2,3,4,5]; localStorage.setItem('myArray', JSON.stringify(myArray)); The above code snippet sets the values of the 'myArray' ...

Tips for storing a single document in two separate collections within the same MongoDB database

I am currently exploring nestjs and I am faced with a challenge. My goal is to retrieve a document from collection_1 and then store the same document into collection_2. I have tried using the $out aggregation, but found that I am only able to save one docu ...

Tips for retrieving the identifier of a row in a mui datagrid when an onClick event occurs

I'm attempting to integrate a material-ui datagrid with a sql database for the purpose of enabling edits to be made via a form rather than editing individual rows and cells one by one. My goal is to pass the row's id as a parameter to a function ...

CSS - font with dashed color styling

I need to display text on a webpage that has the following appearance: https://i.sstatic.net/vFA2A.png The font should have two alternating colors. Can this be achieved? The solution needs to be compatible with all web browsers. ...

"Preventing the default behavior with e.preventDefault is causing issues with the functionality of my

I'm struggling with getting a form to send its contents via email using ajax to display a thank you message without reloading the page. When I remove preventDefault() from the JS, the form sends correctly but redirects to the PHP file, which is not id ...

Developing a map-based search feature with live results using PHP, PGAdmin, and HTML

I am working on setting up a search feature that is integrated with my database in pgAdmin, and I want the search results to be displayed on a map. Here is my search.php file (with details about user, database, schema, table, and column) : <?php $key= ...

Utilize AJAX in JavaScript file

I am encountering an issue with the following code: function inicioConsultar(){ $(function(){ $('#serviciosU').change(function(){ if ($('#serviciosU').val()!= "-1") { $.ajax({ url: "@Url. ...

Is it possible to assign a class or id to a dynamically inserted link using JavaScript?

Currently, I have code that effectively inserts a link to the selected text: document.execCommand('CreateLink', false, 'link.com') Although this method works well, I am eager to include a class/id for the link to simplify styling it w ...

Having trouble with $addToSet and $push not working in updates using Mongoose with MongoDB in Node.js?

My issue involves Mongoose as I am attempting to update a document in MongoDB using the mongoose module. Below is my schema: var User = new mongoose.Schema({ name: String, email: String, list_houses: [{ id_house: S ...

How can I send a current variable through PHP?

I have a pressing deadline and I need some guidance before moving forward. Can someone please advise if what I'm attempting is feasible or if there's a quicker solution? I encountered some problems with an accordion menu, so as a temporary fix, ...

Using node.js with express to send data stored in a variable to the browser instead of displaying it in the

I'm currently getting the hang of node.js. It's pretty straightforward to use res.send and output some basic "hello world" text, but how can I pass variables to the browser instead of just to the console? Here is a snippet of code: var Tester = ...

Refresh the current AngularJS page while preserving the stateParams

I am currently working on a function that toggles the display of a button based on data retrieved from an external API. When loading a record, I pass in an 'id' parameter ($stateParams.id) If the value of this parameter is 1, a button will be s ...

The initial rendering of the connected component is unsuccessful due to the fact that the Redux state has not been fully

Currently, I am utilizing Redux thunk and axios to handle server requests and update the state based on the response. An issue arises when trying to render a connected component with an initial state that relies on data from the server. In this scenario, ...

Perform an action upon a successful completion of an AJAX request using Axios by utilizing the `then()` method for chaining

I'd like to trigger a specific action when an ajax call is successful in axios save() { this.isUpdateTask ? this.updateProduct() : this.storeProduct() this.endTask() } When the ajax call to update or store the product succeed ...

Automatic page switch upon dropdown selection

I'm not very proficient in JavaScript and I want to modify a form so that it automatically updates when a dropdown option is selected, without needing to click a separate "Go" button. How can I adjust the code below? It contains three different dropd ...

Is there a way for rainyday.js to utilize a CSS background image as its background?

I have a simple website with a fixed, full-sized background set using CSS. I am trying to incorporate rainyday.js to create a rain effect over the entire site, including the text. Currently, I am only able to get rainyday.js to display rain over a small s ...

Navigate forward to the next available input in a grid by using the tab key

My goal is to improve form entry efficiency by using the tab key to focus on the next empty input field within a grid component. If an input field already has a value, it will be skipped. For example, if the cursor is in input field 2 and field 3 is filled ...