Issue
I am trying to append a new textarea if the field have "data action", with "new field name". If we uncheck the field the textarea should remove. I want it on multi field if any field have this data action it should add the new text area with name. I am adding the script on codepen.
https://codepen.io/hnpiocyj-the-encoder/pen/vYPYpWz?editors=1111
<style>.active {
border: 1px solid;
}
</style>
<div class="customize">
<span onclick="select(this);">text 1</span>
<span onclick="select(this);" data-action="new-field-1">text 2</span>
<span onclick="select(this);" data-action="new-field-2">other</span>
</div>
function select(currObj) {
const allActiveSpans = document.querySelectorAll('span.active');
allActiveSpans.forEach(span => {
if(span !== currObj){
span.classList.remove('active');
}
});
currObj.classList.toggle('active');
data_action = $(currObj).data('action');
if(!data_action)
{
$('.append').remove();
}
if(data_action) {
$('.customize').append('<textarea class="append" id="'+data_action+'" name="'+data_action+'" rows="3" cols="5"></textarea>');
}
}
The issue is when i am appending text area it is appending but when i clicking that field again it is adding it multi time. For this field if the textarea is appended it should not append it again. If i uncheck the field it should remove it. and if the other fields are check then textarea should be there.
Solution
Looks like there might be an issue with the way the code handles the data-action attribute for custom material. To resolve this, you can make a slight adjustment to ensure that the textarea is properly appended for custom material. Here's an updated version of the code:
$(".dynamic-field").on("input", function (e) {
var dynamic_price = 0;
$(".dynamic-field input:checked").each(function () {
if (!isNaN(parseFloat($(this).val()))) {
dynamic_price += parseFloat($(this).val());
const data_action = $(this).data('action');
if (data_action) {
const existingTextarea = $('#' + data_action);
if (existingTextarea.length === 0) {
$('.customize').append('<textarea class="append" id="' + data_action + '" name="' + data_action + '" rows="3" cols="5"></textarea>');
}
}
}
});
// Remove any existing textarea not associated with the selected material or color
$('.append').each(function () {
const data_action = $(this).attr('id');
if ($(".dynamic-field input[data-action='" + data_action + "']:checked").length === 0) {
$(this).remove();
}
});
e.stopPropagation();
});
This modification checks if there is any checked input with the corresponding data-action before appending a new textarea. Additionally, it removes the existing textarea only if there is no checked input associated with it. This should address the issue you mentioned. Make sure your HTML is properly structured with the correct data-action attributes for custom material and custom color.
Answered By - wolfie00
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.