简体   繁体   中英

Dynamic change of color and text of an element

The script below creates a new line of text boxes and a button. However, when the button is clicked, the new field would like to have new button text and a new design.

 $(function () { var newRow = $(".addRows").clone(); $("#addButton").on("click", function () { let row = newRow.clone().appendTo("#TextBoxesGroup tbody"); $("tr").find("#addButton").css( "border-color", "red" ); }); });
 <table id="TextBoxesGroup"> <tr class="addRows"> <td>Start Date:</td> <td> <input type="text" name="StartDate[]" class="picker" value="" size="6"> </td> <td>End Date:</td> <td> <input type="text" name="EndDate[]" class="picker" value="" size="6"> </td> <td> <input type="button" id="addButton" value="add row" /> </td> </tr> </table> <script type = "text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

For example, the created new button should be with text delete and color red. Thanks for the help or recommendation

I think using templates might make it easier and cleaner to modify the elements. Here is a quick guide for basic templating with vanillajs https://gomakethings.com/html-templates-with-vanilla-javascript/ This allows you to easily pass in IDs for your inputs.

I am not sure if you are just trying to toggle a second row or add multiple rows. If you simply want to toggle the second row and not add more than that then only use the second part of the js, and remove the first template. Likewise if you want to add multiple you can remove the second part (currently commented out) of the js and the second template.

 (function (){ // Interpolate function from https://gomakethings.com/html-templates-with-vanilla-javascript/ //Lets us pass a unique id to the template function interpolate (str, params) { let names = Object.keys(params); let vals = Object.values(params); return new Function(...names, `return \`${str}\`;`)(...vals); } //Using document on click as we are adding new buttons to the DOM and want the event to trigger on them as well $(document).on('click', '.add-button', function () { let id = $('.addRows').length + 1; //Use this for our row ID let newRow = interpolate(row_template.innerHTML, {id}); //Generate our row html from the template $("#TextBoxesGroup tbody").append(newRow); //Add the html to the table }); //Remove button $(document).on('click', '.remove-button', function () { $(this).closest('.addRows').remove(); }); })(); //Use the below INSTEAD of the above for just the single extra toggling row. /*(function (){ //Add new row from simple template $(document).on('click', '.add-button', function () { $("#TextBoxesGroup tbody").append(row_template_single.innerHTML); }); //Remove the row $(document).on('click', '.remove-button', function () { $(this).closest('.addRows').remove(); }); })();*/
 /*Style for red remove button*/ .remove-button { background-color: #f77; color: white; }
 <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <table id="TextBoxesGroup"> <tbody> <tr class="addRows"> <td>Start Date:</td> <td> <input type="text" name="StartDate_1" class="picker" value="" size="6"> </td> <td>End Date:</td> <td> <input type="text" name="EndDate_2" class="picker" value="" size="6"> </td> <td> <input type="button" id="addButton_1" class="add-button" value="Add row" /> </td> </tr> </tbody> </table> <!-- Template allowing to add multiple new rows with unique input names via id passed --> <template id="row_template"> <tr class="addRows"> <td>Start Date:</td> <td> <input type="text" name="StartDate_${id}" class="picker" value="" size="6"> </td> <td>End Date:</td> <td> <input type="text" name="EndDate_${id}" class="picker" value="" size="6"> </td> <td> <input type="button" id="addButton_${id}" class="add-button" value="Add row" /> <input type="button" class="remove-button" value="Remove row" /> </td> </tr> </template> <!-- Template for just 'toggling' a second row --> <!-- <template id="row_template_single"> <tr class="addRows"> <td>Start Date:</td> <td> <input type="text" name="StartDate_2" class="picker" value="" size="6"> </td> <td>End Date:</td> <td> <input type="text" name="EndDate_2" class="picker" value="" size="6"> </td> <td> <input type="button" class="remove-button" value="Remove row" /> </td> </tr> </template> -->

I noticed my previous answer did not properly handle adding items in-between other items, ie not at the end of the list.

The following will better handle adding and removing items, while keeping the ids in order. This instead renders the fields based on the data we keep and manage in JavaScript.

 (function () { $(document).ready(function () { field_data.init() }) let field_data = { data: [], init: function () { this.cacheDom(); this.bindEvents(); this.data.push(this.getItem()); this.renderData(); }, cacheDom: function () { this.$render_container = $('#render_container'); this.row_template_html = $('#row_template').html(); }, bindEvents: function () { $(document).on('click', '.remove-button', this.removeItem); $(document).on('click', '.add-button', this.addItem); this.$render_container.on('change', 'input', this.inputChange); }, //When an item gets added, add new empty item to the data and re-render. addItem: function () { let target = parseInt($(this).attr('data-target')); field_data.data.splice(target+1, 0, field_data.getItem()); field_data.renderData(); }, //When an item gets removed, remove it from the data and re-render. removeItem: function () { let target = parseInt($(this).attr('data-target')); if (field_data.data.length > 1) { //Prevent from removing last item. field_data.data.splice(target, 1); field_data.renderData(); } }, //Get a new/empty item. getItem: function () { return { start_date: '', end_date: '', } }, //Update the data when a value of an input changes inputChange: function () { let $this = $(this); let id = parseInt($this.attr('data-id')); let target = $this.attr('data-target'); field_data.data[id][target] = $this.val(); }, //Render the data according to the template. renderData: function () { let html = ''; for (let i = 0; i < field_data.data.length; i++) { //Generate our row html from the template html += field_data.getRowTemplate( { id: i, start_date: field_data.data[i].start_date, end_date: field_data.data[i].end_date, } ); } field_data.$render_container.html(html); }, //Gets the html for a single row based on our template getRowTemplate: function (params) { let names = Object.keys(params); let values = Object.values(params); return new Function(...names, `return \`${field_data.row_template_html}\`;`)(...values); }, } })();
 .remove-button { background-color: #f77; color: white; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="TextBoxesGroup"> <tbody id="render_container"> </tbody> </table> <template id="row_template"> <tr class="addRows"> <td>Start Date:</td> <td> <input type="text" name="StartDate_${id}" data-id="${id}" data-target="start_date" class="picker" value="${start_date}" size="6"> </td> <td>End Date:</td> <td> <input type="text" name="EndDate_${id}" data-id="${id}" data-target="end_date" class="picker" value="${end_date}" size="6"> </td> <td> <input type="button" class="add-button" data-target="${id}" id="addButton_${id}" value="Add row"/> <input type="button" class="remove-button" data-target="${id}" value="Remove row"/> </td> </tr> </template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM