Get the all button's id in an array in javascript - javascript

In my view file i have two div, in div1 there is some buttons, when i click a button in div1 it goes to div2 and in div2 it does same thing, this time it goes to div1.
Now my question is when there is several buttons in div2, how can i take all the button's id in an array. I want to pass this array in a hidden field of another model.
i tried in following way but it does not working.This is my scripting code.
function movebutton(elem){
var teamMember=[];
if( $(elem).parent().attr("id") == "officers_list" ){
$(elem).detach().appendTo('#add_member');
teamMember.push($(elem).attr("id"));
}
else{
$(elem).detach().appendTo('#officers_list');
teamMember.pop($(elem).attr("id"));
}
$("#TeamTeamMember").val(teamMember);
//console.debug('teamMember=>',teamMember);
}

You can use map function. Code below will return an array of ids.
$("#divId input[type='button']").map(function(index,element) { return element.id; });

Here scope of teamMember is local .so whenever you invoke your function it will create new empty array
Make it global
var teamMember=[];
function movebutton(elem){
if( $(elem).parent().attr("id") == "officers_list" ){
$(elem).detach().appendTo('#add_member');
teamMember.push($(elem).attr("id"));
}
else{
$(elem).detach().appendTo('#officers_list');
teamMember.pop($(elem).attr("id"));
}
$("#TeamTeamMember").val(teamMember);
//console.debug('teamMember=>',teamMember);
}
or You could use $.map() function
var teamMember = $("#add_member").find("button").map(function(){
return this.id;
}).get();

Assuming your 2nd div's id is div2 and your buttons marked up with the input tag, the following should create an array containing all buttons' ids that are in the desired div:
var btns = [];
$('#div2 input[type="button"]').each(function() {//if you are using the <button> markup just use $('div2 button').each(..)
btns.push($(this).attr('id'));
});
Hope this helps.

Related

onclick inside forEach, value parameter only refers to last element

I have a list of anchor in my html, I want to make their href editable.
Everything fine, but the validation step (last onclick) refers to the last anchor instead of the current one
var anchors = document.querySelectorAll('.home-content a');
var col = document.querySelectorAll('.home-content > article');
anchors.forEach((k)=> {
let linkpanel = document.getElementById('link-edit-panel'); //This element is a single div in my html
let linkpanelvalidate = document.getElementById('validate-link'); //the button inside the said div
let editinput = linkpanel.querySelector('input'); //the input inside this div
//For each anchors, I add a button that will let user show the "linkpanel" div to edit the href of this anchor
let editbut = document.createElement('div');
let linktxt = k.href;
editbut.classList.add('edit-but','toremove');
editbut.innerHTML = "<i class='fas fa-link'></i>";
//I put this new element to the current anchor
k.appendChild(editbut);
console.log(k); // this to show me the full list of anchors
/* PROBLEM START HERE */
//click on the "edit" button
editbut.onclick = ()=>{
console.log(k); //Here, it shows the good anchor!
}
//click on the "validate" button
linkpanelvalidate.onclick = ()=>{
console.log(k); //Here, it shows the very last anchor...
}
});
I tried to put the element inside a constant
const ttt = k;
It does not change a thing.
Thank you for your help
We are facing here a classical forEach bubbling misunderstand (and I was blind not to see it)
When the click on the validate button occures, the call is made from the "main" bubble (outside the loop function if you need to picture it) so naturaly, it returns the last occurrence of the loop when we print the value in the console for example.
Solution
There is many solutions, you can store these values in an array to use each of them later
var arr = [];
node.forEach((v)=>{
arr.push(v);
});
Or, you don't want to deal with an array and want to keep it simple, like me, and you create your button during the forEach loop event, like this
node.forEach((v)=>{
let btn = document.createElement('button');
document.body.appendChild(btn);
btn.onclick = ()=> {
console.log(v); //it is the current value, not the last one
//you can create another button here and put his onclick here, the value will still remains etc
}
});

JavaScript - Hide multiple elements(with same id) with one checkbox

So i am trying to hide multiple html elements with one checkbox.
hiding one element works like a charm, but as soon as i have two it hides only the fist one what matches.
Fast demo what i am trying to do :
Checkbox :
<input type="checkbox" id="kaartCheck" onclick="kliendikaartF()">
Element what i am able to show:
<p id="kliendi_kaart_olemas_p" style="display:none">Kliendikaart on olemas!</p>
and element what i am not able to show : (Basicly the same what is first
<p id="kliendi_kaart_olemas_p" style="display:none">Second element shoult apear</p>
and js what i am using for that :
function kliendikaartF() {
var checkBox = document.getElementById("kaartCheck");
var text = document.getElementById("kliendi_kaart_olemas_p");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
So long story short, i have multiple elements what i would like to hide with one click, i would give them all the same ID : kliendi_kaart_olemas_p and show / hide them with one checkbox.
I think you have to use querySelectorAll() method for select all element by attribute. This will returns array of all element which is matched by attribute and its value. then you have to iterate all one by one in for loop.
function kliendikaartF() {
var checkBox = document.getElementById("kaartCheck");
var allElements= document.querySelectorAll('[id="kliendi_kaart_olemas_p"]');
var new_display_value="none";
if (checkBox.checked == true){
new_display_value = "block";
}
for(i=0;i<allElements.length;i++){
allElements[i].style.display=new_display_value;
}
}
document.getElementById will only return the first element matching that id.
If you want to select all IDs or classes, use document.querySelector('#idhere')
Use a classs name as kliendi_kaart_olemas_p beacuse here You have created id and id is the unique name of an item in the whole page. If you take the id and modify that element It will only update the element which found first.
<p class="kliendi_kaart_olemas_p" style="display:none">Kliendikaart on olemas!/p>
and
<p class="kliendi_kaart_olemas_p" style="display:none">Kliendikaart on olemas!/p>
then initailize you varibale like
var text = document.getElementsByClassName("kliendi_kaart_olemas_p");
Your problem will be solved

Changing a dynamically created label's text with keyup() issue

I am creating a form dynamically and therefore edit the form elements’ properties. When attempting to change the label, assigning an auto-generated id works fine but when changing this label using the generated id, the function or keyup() from jQuery keeps calling all the previously created label id(s). this means when i want to edit one label, it ends up editing every label.
HTML
<input type="text" id="change-label"><br><br>
<button id="add-button">add label</button>
<div id="add-label"></div>
JavaScript/jQuery
$('#add-button').click(function(){
var div = document.createElement('div');
var textLabel = document.createElement('label');
var labelNode = document.createTextNode('untitled');
textLabel.appendChild(labelNode);
textLabel.id = autoIdClosure();
$('#change-label').val('untitled');
div.appendChild(textLabel);
$('#add-label').append(div);
});
var autoIdClosure = (function(){
var counter = 0;
var labelId = "textInputLabel";
return function(){
counter += 1;
var id = labelId + counter;
editLabelWrapper(id)
return id;
}
})();
function editLabelWrapper(id){
function editLabel(){
var value = $(this).val();
$("#"+id).text(value);
}
$("#change-label").keyup(editLabel).keyup();
}
I’ve already found an alternative using onkeyup="$('#'+globaID).text($(this).val());", but I need to understand what I was doing wrong so I can learn from it.
JSFiddle
I think you are overthinking the matter...
Instead of using an unique id, rather use classes, makes it easier to handle.
So change <div id="add-label"></div> to <div class="add-label"></div>
Then what you want to do is, when a value is given in #change-label you want it in the last div.add-label.
So the function will become this:
$("#change-label").on('keyup', function() {
$('.add-label:last').text( $(this).val() );
});
Next what you want to do is bind a function to #add-button. Once it gets clicked, we want to add a new div.add-label after the last one. And empty the #change-label. You can do that by using this function:
$('#add-button').on('click', function() {
$('.add-label:last').after('<div class="add-label"></div>');
$('#change-label').val('');
});
Updated Fiddle

Duplicate the value from the group of radio

I want to duplicate the text value of the active radio buttom before other div. Radios are divided into groups. In each group is always active, only one. Therefore, a new value from each group should always be one, too. I will add a text value, but I cant to make the removal of the previous value of the group.
$('.views-exposed-widget').find('.form-type-radio').on('click', function(){
var a = $(this).closest('.form-type-radio').find('label[class="option"]').text();
$('.views-widget-sort-by').before('<span>'+a+'</span>');
});
My example: http://jsfiddle.net/e59ogp8a/
You could name them (and thus create a mapping between the radio group and the spans) so you can find them easily
$('.views-exposed-widget').on('change', 'input', function () {
var self = $(this),
name = this.name,
text = self.closest('.form-type-radio').find('label[class="option"]').text(),
target = $('.views-widget-sort-by').find('[data-for="'+ name +'"]'); // find the related span
// check if we found a related span, and if not create it
if (target.length == 0){
target = $('<span data-for="'+name+'"></span>').appendTo('.views-widget-sort-by');
}
// set the text of the span
target.text( text );
});
Demo at http://jsfiddle.net/gaby/5nutt42g/1/
You also had a wrong id on the the first radio (it should be edit-tid-1-4 and not edit-tid-1-2)
You have to remove all the prev siblings of your div element.
$('.views-exposed-widget').find('.form-type-radio').on('click', function(){
var a = $(this).closest('.form-type-radio').find('label[class="option"]').text();
$('.views-widget-sort-by').prevAll().remove();
$('.views-widget-sort-by').before('<span>'+a+'</span>');
});
You can use the group name as span's class name to clear the values of the group after group's button clicked.
Take a look here: http://jsfiddle.net/e59ogp8a/3/
$('.views-exposed-widget').find('.form-type-radio').on('click', function(){
var a = $(this).closest('.form-type-radio').find('label[class="option"]').text();
var groupName= $(this).find('.dls-radio').attr("name");
console.log($('.views-widget-sort-by').prev('.'+groupName).text(''));
$('.views-widget-sort-by').before('<span class="'+groupName+'">'+a+'</span>');
});

Nesting DIV using JavaScript

I am trying to load DIV on button click inside another DIV and on another click it should create a new DIV inside the newly created DIV. Here is my fiddle:http://jsfiddle.net/LzCW5/4/ and my code:
HTML:
Generate
<div id='x0'>
0
</div>
JavaScript:
int level=1;
function nestDiv()
{
document.getElementById('x'+(level-1)).innerHTML="<div id='x"+level+"'>"+level+"</div>";
level++;
if(level==5)
//do somthing
}
I also want to perform some special operation when nesting level reaches 5. I am not so pro at JavaScript. So please tell me how can I achieve this?
In your code you only have to change int to var and call the function as a variable:
var level=1;
nestDiv = function()
{
document.getElementById('x'+(level-1)).innerHTML="<div id='x"+level+"'>"+level+"</div>";
level++;
}
You can see this working here
Here's how to append a div in jQuery:
var newDiv = $("<div id='x"+level+"'>"+level+"</div>");
$('#x'+(level-1)).append(newDiv);
This should replace your document.getElementById... line
My understanding as per your question:
When you click a button, add a div to another div.
Now when the user clicks another button, new div must be added in the previously created new div.
so let's break it down:
$("button").click(function() {
if($("#referenceDivId").children().length == 0) {
// if there are no children initially
$("#referenceDivId").append("<div>New div</div>");
} else if($("#referenceDivId").children().length == 5) {
// do your magic when children divs are 5
}
else {
// if it already had children
$("#referenceDivId").find("div:last").append("<div>New div</div>");
}
});
DEMO

Categories

Resources