Dynamically create a class name in Javascript - javascript

I have some code in PHP file that creates a button and the target of that button is a DIV (findOptionsBox).
The button gets repeated multiple times on the page and so the target of each button should be a unique DIV Id.
<button type="button" id="myBtn" class="btn" data-toggle="collapse" data-
target="#findOptionsBox">
......
</button>
<div id="findOptionsBox" class="search-box collapse">
......
<div>
So my question is how to make 'findOptionsBox' a variable that can be supplied to the data-target of each myBtn and the same variable can also be the ID of the corresponding div.
I am looking to end up with something like this:
......
<div id="findOptionsBox_1" class="search-box collapse">
......
<div>
......
<div id="findOptionsBox_2" class="search-box collapse">
......
<div>
I need the btnIds and the DivIds to be unique and each btnId to refer to the corresponding DivId.
I am looking to do this in Javascript and am trying something like:
<script type="application/javascript">
$(function(){
var count = 0;
count++;
});
</script>
Thanks.

https://jsfiddle.net/sudarpochong/0hx4mLaw/1/
Create a div to contain options box (#options-container)
Clone #findOptionsBox and change the id
Insert into #options-container
Code:
var PREFIX_ID = "findOptionsBox_";
$("#myBtn").click(function(e) {
$("#options-container").empty();
var totalOptions = $("#numberOfOptions").val();
for (var i=0; i<totalOptions; i++) {
var newBox = $("#findOptionsBox").clone();
newBox.attr("id", PREFIX_ID + i);
newBox.appendTo("#options-container");
newBox.show();
}
e.preventDefault();
});

Related

Data category - on click modification

I was wondering if there is a way to add new data-category to existing one once click event would happen?
I want to add it since I am using it as a filtering element.
An example below: Click the button and add the category: Delta
<div class="item" data-category="Alfa , Beta , Gamma ">
<p> Object 1<p>
<div>
<button class="my-fav">
You can get attributes of the element and change it then set it again, here is an example:
<div id="data" class="item" data-category="Alfa , Beta , Gamma ">
<p> Object 1<p>
</div>
<button id="myButton" class="my-fav">
<script>
const data = document.getElementById("data");
const button = document.getElementById("myButton");
let data_attribute = data.getAttribute("data-category");
myButton.addEventListener("click", function() {
data_attribute += ", Delta";
data.setAttribute("data-category", data_attribute);
});
</script>

How to capture a click on elements using partial IDs with vanilla Javascript?

I want to run a function anytime one of a series of elements are clicked and want to target these elements using a partial ID. Currently, only the first element responds when clicked upon. What have I done wrong? My code:
HTML:
<div>
<a id="selector-0">Zero</a>
</div>
<div>
<a id="selector-1">One</a>
</div>
<div>
<a id="selector-2">Two</a>
</div>
JS:
document.querySelector('[id^="selector-"]').onclick = function(){
var id_selector = this.getAttribute('id');
alert('ID: ' + id_selector);
}
I have attempted changing the querySelector to include 'a[id^="selector-"]', but only the first element ever wants to respond on click.
Use *= selector with id as attribute and document.querySelectorAll.
Then add the onclick to all the elements of the given array of retrieved elements.
const els = Array.from(document.querySelectorAll('[id*=selector-]'));
console.log(els.length);
els.forEach(el => el.onclick = () => console.log('Clicked el:', el));
<div>
<a id="selector-0">Zero</a>
</div>
<div>
<a id="selector-1">One</a>
</div>
<div>
<a id="selector-2">Two</a>
</div>

Get the table row id on click (HTML+JS)

I have this tag:
<td align="center">
<div class="dropdown">
<button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button>
<div id="#TableRowId" class="dropdown-content">
Show
Edit
</div>
</div>
</td>
and JS function:
function DropdownShow(element) {
var elm = document.getElementById(element.querySelector(".dropdown-content").id);
elm.classList.toggle('show');
}
I want when I click on the image glyphicon at the table, to show the dropdown div tag with the class="dropdown-content". To do that I need the each row ID, and I have it on the variable #TableRowId. How can I do that?
You are passing the reference of clicked button so you need to get the element by getting its parent element where parent node can get from parentNode property.
function DropdownShow(element) {
var elm = element.parentNode.querySelector('.dropdown-content')
elm.classList.toggle('show');
}
FYI: If there is no whitespace after the button then you can use nextSibling property to get the element.
var elm = element.nextSibling;
or use nextElementSibling property to get the element even there is a text node.
var elm = element.nextElementSibling;
Check polyfill option for ie8.
I would pass the #TableRowId to the button as a data attribute like this:
<td align="center">
<div class="dropdown">
<button data-dropdown-content-id="#TableRowId" onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button>
<div id="#TableRowId" class="dropdown-content">
Show
Edit
</div>
</div>
</td>
And then your javascript would simply be:
function DropdownShow(element) {
var dropDownContentId = element.getAttribute("data-dropdown-content-id");
var elm = document.getElementById(dropdownContentId);
elm.classList.toggle('show');
}
This would give you the most robust code, because it doesn't depend on the relationships (sibling/parent/child etc) between the two elements.

Is it bad practice to hold information in the id of an HTML element?

Let's say I have a template and I want to loop and create div's. I want to listen to clicks on the buttons contained in each of these divs:
<div class="repeatedDiv">
<button class="reply-button">
</div>
$('.reply-button').on('click',function(e)...)
I want to make the reply button function specific to the div that it was selected on. Would it be bad to have something like:
<div class="repeatedDiv">
<button class="reply-button" id="reply-{{this.id}}">
</div>
Don't make it more complicated than it really is
$(document).on('click', '.reply-button', function(e){
var divClicked = $(e.target).closest('.repeatedDiv');
// do something with clicked div
// var divClicked is the div elmt that contains the button that was clicked
// doing it this way you might not even need an id at all
console.log(divClicked.attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="repeatedDiv">
<button class="reply-button">div1</button>
</div>
<div id="div2" class="repeatedDiv">
<button class="reply-button">div2</button>
</div>
<div id="div3" class="repeatedDiv">
<button class="reply-button">div3</button>
</div>
And if you do need an id when creating a new div create it dynamically with e.g.
var newID = "id-" + Date.now();
console.log(newID);

Append element using jquery selector

I need to recreate and append my template div to the parent div on button click and this can be done multiple times
<div id = "parent">
<div id = "child_1">
<div><input type = "text"></div>
<div><input type = "text"></div>
//several inputs and divs
</div>
</div>
and my script
//on button click event
var template = $("#parent").children().last();
template.attr("id","child_2"); //just a sample of dynamic id
$("#parent").append(template);
But this doesn't work
You need to clone() a copy of the child before you append it, otherwise you just put the current element back in its original position.
var template = $("#parent").children().last().clone();
Working example
Try with this:
var html = $("#parent").html();
var i = 1;
$("button").on("click",function(){
i++;
$("#parent").append(html.replace('id="child_1"','id="child_' + i + '"'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div id = "child_1">
<div><input type = "text"></div>
<div><input type = "text"></div>
//several inputs and divs
</div>
</div>
<button>Click</button>

Categories