Multidimensional input : update index when clone existing item - javascript

Is it possible to change the index of the last item of a multidimensional input when my new item is created ?
Let me explain.
I have a button that is clone an item from my list, into my list. Each item contains several properties (date, category...)
This is an example of what I have when I display my form :
validation_form[classe][0][matieres][11][ressources][XXXXX][hasBeenRenewed]
What I do is that I clone all my item, but for now, the index XXXX is not updated.
How can I update the XXXX directly when I clone my item ? I thought I could count the number of items, and then change the index, but this would be painful and time consuming...

Use a regex in match() to create array of them then update the one you want and join() back together
const el = document.querySelector('input');
const prefix = el.name.split('[')[0],
ind = el.name.match(/\[(.*?)\]/g);
ind[5]= `[AAA]`;
el.name = `${prefix}${ind.join('')}`
console.log(el)
<input name='validation_form[classe][0][matieres][11][ressources][XXXXX][hasBeenRenewed]'/>

With a little bit of change, the #charlietfl answer works (had to change to fit into my case)
let inputs = new_ressource_clone.find('input');
let new_index = parseInt(count_ressource) + 1;
inputs.each(function() {
let input = $(this)
const prefix = input.attr('name').split('[')[0],
ind = input.attr('name').match(/\[(.*?)\]/g);
ind[5]= '['+new_index+']';
matiere_zone.attr('data-matiere-count-ressources', new_index);
let new_name = `${prefix}${ind.join('')}`;
input.attr('name', new_name);
})
new_ressource_clone.appendTo(liste_zone);

Related

How do i add a click event to the names in the dropdown list to display the grade of the student clicked on in an alert. It has been a pain , pls thax

This is the Main HTML page and the task was to create a dropdown list with student names and on click it should display their grade in an alert box. This is a project I'm giving a second look to improvr my grade and even after learning more, I'm still struggeling to get the final code.
//HTML
Task2
JavaScript
This is the creation of the map
let avrGrades = new Map()
avrGrades.set("Jade", 90)
avrGrades.set("Vel", 88)
avrGrades.set("Sky", 60)
avrGrades.set("Rian", 70)
avrGrades.set("Lizz", 90)
I ran a test loop here to see if the key vale pairs are being read.
for(let [key, value] of avrGrades){
console.log(key + " " + value)
}
Creating the Drop-down list with was quite simple to be honest.
for(let key of avrGrades.keys()){
let classList = document.getElementById("classList")
//Creating an id attribute
let att =document.createAttribute("id")
att.value = "option"
//Creating the option Element
let listItem = document.createElement("option")
//Adding the attribute to the option element
listItem.setAttributeNode(att)
listItem.innerHTML = key
classList.appendChild(listItem)
}
This sows the grade on click and here is were I am struggeling, i tried a few things but nothing works.
let show = document.getElementById("option")
show.addEventListener("click", function(){
for(let value of avrGrades.values()){
alert(value)
}
})
I adjust your code like that:
const avrGrades = new Map();
const classList = document.getElementById("classList");
avrGrades.set("Jade", 90)
avrGrades.set("Vel", 88)
avrGrades.set("Sky", 60)
avrGrades.set("Rian", 70)
avrGrades.set("Lizz", 90)
for (const key of avrGrades.keys()) {
const listItem = document.createElement("option")
listItem.innerHTML = key
classList.appendChild(listItem)
}
classList.addEventListener("change", function() {
alert(avrGrades.get(classList.options[classList.selectedIndex].text))
})
<select id='classList'></select>
You try to use multiple same id, but the ids must be unique, i simple use text of selected option for use .get and alert the value of grade
Reference:
Map
HTMLSelectElement.selectedIndex
Your initial code should work if you specify a unique ID for each one of the option. At the moment you have
let att =document.createAttribute("id")
att.value = "option"
so each option has the same ID option. Try using something unique like option-{key} for each one, and set the click for each ID.
You can also remove this ID issue by targeting the elements using a class name instead of an ID
let shows = document.getElementsByClassName("option")
for (var i = 0; i < shows.length; i++) {
shows[i].addEventListener('click', [your function]);
}
assuming you give these elements a class with name option

How to add an item to a list by replacing the earlier one. In Javascript

I have a list will a list but it only has one item I need to be able to replace that with a new one. But there should one be one.
Because there is a condition involve I need to be able to create an variable if something there or not but I found the list to be easier so how can I replace an item in a list with a new one
let subject_reply = [];
if (email.subject.startsWith("Re:") == true) {
subject_reply.push(email.subject);
}else{
subject_reply.push(`Re: ${email.subject}`);
}
Maybe this helps you, to replace an item of an array you can use splice method, this code says: replace item at index 1, delete that item and insert 'Boxer'.
var dogs = ['Bulldog', 'Beagle', 'Labrador'];
dogs.splice(1, 1, 'Boxer');
console.log(dogs);
I'm not sure if that is what you asked for, it's an array that holds one item only, by clearing the array when we click on the button and it takes the value of the input and then pushing it to the array by making it the only value.
If the `value` starts with *Re:*{
Push as it is.
} else {
Push: "Re: value"
}
var myInput = document.getElementById('myInput');
var myBtn = document.getElementById('myBtn');
let subject_reply = [];
myBtn.addEventListener('click', () => {
subject_reply = [];
var textValue = myInput.value;
if (textValue.startsWith("Re:") == true) {
subject_reply.push(textValue);
} else{
subject_reply.push(`Re: ${textValue}`);
}
console.log(subject_reply);
});
<input type='text' id='myInput'>
<button id='myBtn'>Click</button>
It's difficult to answer a poorly-worded question. As I understand it, one of these is the answer you seek:
subject_reply.push("Re: " + email.subject.replace(/^Re:\s?/, ""));
OR
subject_reply[0] = "Re: " + email.subject.replace(/^Re:\s?/, "");
I understand you want to replace a string value in an array.
For this, Function "Replace()" will help. In this problem specific to you, "EmailREAdder()" will help you adding "RE:" at the start of a string which does not contain "RE:".
/* Function for replacing an item */
const Replace = (arr,oldValue, newValue) => arr.splice(arr.indexOf(oldValue), 1, newValue);
/* Setting all without "RE:" to RE*/
const EmailREAdder = arr => {
arr.map(item => {
if(!item.match(/RE:/)){
Replace(arr, item, `RE: ${item}`);
}
});
}
/* code */
let users = [
"RE: Farman Ali",
"Usman",
"Fraz"
];
console.log(users);
EmailREAdder(users);
console.log(users);

jQuery pop removes the item from end

I have this question in reference to
jQuery convert checkbox selections to array.
This works fine. I have modified it to match my requirements. My javascript is like below .
when a checkbox is checked I want to be added to the corresponding ID(which works fine) but when it is unchecked I want it to be removed..so I used pop. That works but it removed the last item ID rater than the unchecked item ID
` var arrayPgggoData = pgggoThisElem.parents('.elementor-widget-container').find('.pgggo-sort-container').attr('data-ajax-container');
var arrayPgggoData = JSON.parse(arrayPgggoData);
if ($(this).is(':checked')) {
const [_, taxonomy, __, attr] = $(this).attr('name').split('-');
arrayPgggoData[taxonomy] = arrayPgggoData[taxonomy] || [];
arrayPgggoData[taxonomy].push(attr.split('[')[0]);
} else {
const [_, taxonomy, __, attr] = $(this).attr('name').split('-');
arrayPgggoData[taxonomy] = arrayPgggoData[taxonomy] || [];
arrayPgggoData[taxonomy].pop(attr.split('[')[0]);
}`
Can someone help me out? :|
The pop function does as it is supposed which is basically removing the last element you have.
What you need here is splice(start, positions) but in this case you'd need to find the position in which the element appears. For this you would need to use indexOf(element).
You'd need something like this:
var index = indexOf(element);
arrayPgggoData.splice(index, 1);
You can check this article for more information on different ways to remove elements from arrays in JavaScript.

Change start and end index inside filter

I'm trying to create a filter which will help me filter out the results from an array based on certain index.
const newArr = oldArr.filter((item, index) => for(index === selectedIndex; index < selectedIndex + 2; index ++) {
return this.createOptions(item, index, selectedItem))
};
I get selectedIndex from an event handler in my code. How do I write such a case?
It is not clear from your (pseudo) code what are you trying to do. My best guess is that you want to get an item from an array at specified index:
// get item at position `selectedIndex` in array
const item = oldArr[selectedIndex]
// do whatever you need with the item
this.createOptions(item, index, selectedItem)

How to remove duplicates from text using regex, match and exec in javascript

My javascript knowledge is limited.
I use this code :
var myString = $("#builder-area-center-frame-content").html();
var pattern = /{{(.*?)}}/g;
var match;
while ((match = pattern.exec(myString)) !== null ){
$("#sim-edit-variable-replace").show();
$("#sim-edit-variable-replace select[name=variable_element]").append('<option value="'+ match[0] +'">'+ match[1] +'</option>');
}
'myString' is the container of my div #builder-area-center-frame-content,
and in my div there are elements like that {{FOO}} or {{TOTO}}, etc...
I have a form with a select and in my loop i create option attribut for each {{XXX}} found.
But if there are, for example, 2 {{FOO}}, the option attribut will be repeat twice. Like this example :
<select class="form-control" name="variable_element"><option value="{{FOO}}">FOO</option><option value="{{FOO}}">FOO</option><option value="{{toto}}">toto</option></select>
How can i remove duplicate {{FOO}} to keep only one ?
Sorry for my bad english, i hope you will understand what i want to do ?
EDIT : I tried your code but i have a lot of error of rendering about 'let'. I'm using NetBeans.
function variable_replace() {
let str = $("#builder-area-center-frame-content").html();
let collection = str.match(/{{[aA-zZ]+}}/g).filter((item, index, self) => index === self.indexOf(item));
if (collection.length > 0) {
$('#sim-edit-variable-replace').show();
let elem = $('#sim-edit-variable-replace select[name=variable_element]');
for (let item of collection) {
elem.append('<option value="${item.replace(/[{}]/g, '')}">${item}</option>');
}
}
}
variable_replace();
If you can get the string value of the content of your element, you can use a regex to match for the input and use Array#filter to check if there are any duplicates.
let str = '{{TODO}}{{FOO}}{{FOO}} {{TODO}}';
let collection = str.match(/{{[aA-zZ]+}}/g).filter((item, index, self) => index === self.indexOf(item));
console.log(collection);
EDIT:
You can replace the while loop with an for loop and iterate over all items in the array to append new options to the selection element.
if (collection.length > 0) {
$('#sim-edit-variable-replace').show();
let elem = $('#sim-edit-variable-replace select[name=variable_element]');
for (let item of collection) {
elem.append(`<option value="${item.replace(/[{}]/g, '')}">${item}</option>`);
}
}

Categories

Resources