Jquery each function target children of div - javascript

I am trying to target all buttons, that are children of a div with the class 'actions'.
I want my function to take the values from onclick, filter out letters and special chars, and add the numbers to an array.
The function works, when i try to target the buttons OUTSIDE the div, but not when i try to target .actions button.
Anyone have any ideas?
Fiddle: http://jsfiddle.net/Teilmann/wN79n/5/
html:
<div class="actions">
<button onclick="addToCart(1337, 'something');" />
</div>
<div class="actions">
<button onclick="addToCart(1338, 'something');" />
</div>
<div class="actions">
<button onclick="addToCart(1339, 'something');" />
</div>
js:
var products = new Array();
jQuery('.actions button').each(function(){
var id = jQuery(this).getAttribute('onclick');
products.push(id.replace(/[^0-9]/g, ''));
});
alert(products);

Your html is incorrect <button/> it needs to be <button></button> and getAttribute has to be .attr()
HTML
<button onclick="str1" ></button> <!--changed html here from <button/>-->
<button onclick="2" ></button> <!--changed html here from <button/>-->
<button onclick="addToCart(1234, 'something');" ></button> <!--changed html here from <button/>-->
<div class="actions">
<button onclick="addToCart(1337, 'something');" />
</div>
<div class="actions">
<button onclick="addToCart(1338, 'something');" />
</div>
<div class="actions">
<button onclick="addToCart(1339, 'something');" />
</div>
jQuery
var products = new Array();
jQuery('.actions button').each(function(){
var id = jQuery(this).attr('onclick');
products.push(id.replace(/[^0-9]/g, ''));
});
alert(products);
DEMO
If you don't close the button with </button> the html will automatically generate this markup
<button onclick="str1"></button>
<button onclick="2"></button>
<button onclick="addToCart(1234, 'something');">
<div class="actions"></div>
</button>
<button onclick="addToCart(1337, 'something');">
<div class="actions"></div>
</button>
<button onclick="addToCart(1338, 'something');">
<div class="actions"></div>
</button>
<button onclick="addToCart(1339, 'something');"></button>

Related

Only first button works, but they are all set to do the same [duplicate]

This question already has answers here:
JavaScript and getElementById for multiple elements with the same ID
(13 answers)
Get multiple elements by Id
(14 answers)
Closed 1 year ago.
I am making a menu and I am currently implementing a feature where you can close the menu. I have three different menus inside of an overlay. When you close the menu I want the overlay to be display: none;. I have three buttons that do this (one for each menu). However, only the button at the top of the HTML code works. I know it is only the one at the top, because I tried deleting the one that was on the top, and then the second button would work since that is now the top button. I also tried giving different IDs, but that didn't make a difference.
Here is a shortened version of the parts of my code that I am talking about:
var overlay = document.getElementById("overlay");
var closeMenu = document.getElementById("closeMenu");
closeMenu.addEventListener('click', function() {
overlay.style = "display: none;";
});
<div class="overlay" id="overlay">
<div class="selectMenu" id="selectMenu">
<div class="h2Wrapper">
<h2>Create Canvas</h2>
<button type="button" name="button" class="closeMenu fas fa-times" id="closeMenu"></button>
</div>
</div>
<div class="selectMenu2" id="selectMenu2">
<div class="h2Wrapper">
<h2>Upload Image</h2>
<button type="button" name="button" class="closeMenu fas fa-times" id="closeMenu"></button>
</div>
</div>
<div class="selectMenu3" id="selectMenu3">
<div class="h2Wrapper">
<h2>Create Blank</h2>
<button type="button" name="button" class="closeMenu fas fa-times" id="closeMenu"></button>
</div>
</div>
</div>
First of all, the attribute id must be unique in a document, use class instead. Then you can target all the element with the class to loop through them and attach the event individually:
var overlay = document.getElementById("overlay");
var closeMenu = document.querySelectorAll(".closeMenu");
closeMenu.forEach(function(cm){
cm.addEventListener('click', function() {
overlay.style = "display: none;";
});
});
<div class="overlay" id="overlay">
<div class="selectMenu" id="selectMenu">
<div class="h2Wrapper">
<h2>Create Canvas</h2>
<button type="button" name="button" class="closeMenu fas fa-times" class="closeMenu"></button>
</div>
</div>
<div class="selectMenu2" id="selectMenu2">
<div class="h2Wrapper">
<h2>Upload Image</h2>
<button type="button" name="button" class="closeMenu fas fa-times" class="closeMenu"></button>
</div>
</div>
<div class="selectMenu3" id="selectMenu3">
<div class="h2Wrapper">
<h2>Create Blank</h2>
<button type="button" name="button" class="closeMenu fas fa-times" class="closeMenu"></button>
</div>
</div>
</div>

JavaScript How to Print A Label in a DIV?

I have 4 boxes labeled a1, a2, a3, a4 as an example. And when someone clicks on 2 boxes, I want the label (a1, a2 as an example) to print on html output. I just spent over an hour and the best I can come up was printing undefined and null.
Sorry, here is my code
HTML
<div class="container">
<div class="row">
<div class="col-md-3" label="a1">
<a class="btn btn-primary" href="#" role="button">Button 01</a>
<div class="output"></div>
</div>
<div class="col-md-3" label="a2">
<a class="btn btn-primary" href="#" role="button">Button 02</a>
<div class="output"></div>
</div>
<div class="col-md-3" label="a3">
<a class="btn btn-primary" href="#" role="button">Button 03</a>
<div class="output"></div>
</div>
<div class="col-md-3" label="a4">
<a class="btn btn-primary" href="#" role="button">Button 04</a>
<div class="output"></div>
</div>
</div>
</div>
const button = document.querySelector('.btn');
button.addEventListener('click', printLabel);
function printLabel(){
const name = document.querySelector('label');
const print = document.querySelector('.output');
print.innerText = name;
}
label isn't really a standard attribute of the <div> tag. You could try id if you're just looking for a quick solution. Also, you're accessing everything in a pretty strange way.
You should change label to id. The id attribute is pretty much universal to all HTML elements (that I know of) and will allow you to uniquely identify that element.
<div class="container">
<div class="row">
<div class="col-md-3" id="a1">
<a class="btn btn-primary" href="#" role="button">Button 01</a>
<div class="output"></div>
</div>
<div class="col-md-3" id="a2">
<a class="btn btn-primary" href="#" role="button">Button 02</a>
<div class="output"></div>
</div>
<div class="col-md-3" id="a3">
<a class="btn btn-primary" href="#" role="button">Button 03</a>
<div class="output"></div>
</div>
<div class="col-md-3" id="a4">
<a class="btn btn-primary" href="#" role="button">Button 04</a>
<div class="output"></div>
</div>
</div>
</div>
Add a unique id to all of the div elements that are meant to be your "output". This will allow your code to direct the "output" to the right element.
<div class="container">
<div class="row">
<div class="col-md-3" id="a1">
<a class="btn btn-primary" href="#" role="button">Button 01</a>
<div class="output" id="a1-output"></div>
</div>
<div class="col-md-3" id="a2">
<a class="btn btn-primary" href="#" role="button">Button 02</a>
<div class="output" id="a2-output"></div>
</div>
<div class="col-md-3" id="a3">
<a class="btn btn-primary" href="#" role="button">Button 03</a>
<div class="output" id="a3-output"></div>
</div>
<div class="col-md-3" id="a4">
<a class="btn btn-primary" href="#" role="button">Button 04</a>
<div class="output" id="a4-output"></div>
</div>
</div>
</div>
Finally, a couple of changes to your JavaScript. The first change you'll see is that I changed document.querySelector('.btn') to document.querySelectorAll('.btn'). The difference between these methods is that the first one selects ONLY the first element it finds that matches the selector, but the second one selects all elements that match the selector and creates an array.
Next, we loop through that array to add an event listener for each element.
After that, we add a parameter e (for event) to the printLabel() function because addEventListener() passes an event object in the callback function (printLabel). This object gives information about the target element related to the event.
Next, we get the target element of the event and that's your button. Then we get the parentElement of your button because your id or "label" is on the parent element. Then, you can get the name from the id of the parent element.
As a note, remember that id attributes CANNOT have spaces or . or # or really most special characters besides _.
Finally, we need to select your "output" element, and we'll use the id to do that.
document.querySelector('#' + name + '-output'); will get the element that has an id with the given name + -output. For example, if you click button a1 this will get the element with the id of a1-output. The # signifies that you're searching for an id.
Now that we stored this element in a variable print, we can place the text in it using the innerHTML property.
const button = document.querySelectorAll('.btn');
for(var i=0; i < button.length; i++) {
button[i].addEventListener('click', printLabel);
}
function printLabel(e) {
var target = e.target;
var parent = target.parentElement;
const name = parent.id;
const print = document.querySelector('#' + name + '-output');
print.innerHTML = name;
}
I created a JSFiddle to help you.
If you have any questions, please let me know.
<script>
function printDiv(divName){
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
<h1> do not print this </h1>
<div id='printMe'>
Print this only
</div>
<button onclick="printDiv('printMe')">Print only the above div</button>
We can use event bubbling and data attributes to our advantage here. Replace your label attribute which is non-standard with a data attribute. Also, don't use a if it is not a navigation element, use button instead.
//Get the divs
let divs = document.querySelectorAll("[data-label]")
for(var i = 0; i < divs.length; i++){
//Add the event listener to the DIVs, yes the divs
divs[i].addEventListener("click", function(event){
//Did a button fire the event?
if(event.target.tagName === "BUTTON"){
//update the output div in the clicked div
this.querySelector(".output").innerText = this.dataset.label;
}
});
}
<div class="container">
<div class="row">
<div class="col-md-3" data-label="a1">
<button class="btn btn-primary" role="button">Button 01</button>
<div class="output"></div>
</div>
<div class="col-md-3" data-label="a2">
<button class="btn btn-primary"role="button">Button 02</button>
<div class="output"></div>
</div>
<div class="col-md-3" data-label="a3">
<button class="btn btn-primary" role="button">Button 03</button>
<div class="output"></div>
</div>
<div class="col-md-3" data-label="a4">
<button class="btn btn-primary" role="button">Button 04</button>
<div class="output"></div>
</div>
</div>
</div>
just change your script part to the following to make it work without changing HTML
<script>
//getting all buttons
var buttons = document.getElementsByClassName("btn");
//adding event listner to all buttons
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", printLabel, false);
}
function printLabel() {
const outputDiv = this.parentElement.querySelector(".output"); // this will select only closet div with given class
outputDiv.innerText = this.parentElement.getAttribute("label");
}
</script>

Adding smooth scrolling to function onclick getelementbyid

I use this function part to show hidden div, it is working properly, but it appears suddenly, not nice, I want it to scroll down gently, what can I add to the code?
function show() {
document.getElementById("show").style.display = 'block';
}
<div>
<button type="button" class="btn btn-primary" onclick="show();">Show</button>
</div>
<div id="show" style="background-color:#ccc;display:none;">
<p>Hello!</p>
</div>
There are several ways to do this... using your existing code (and vanilla js) I would use a combination of max-height and transition to get the text to "scroll down":
function show() {
document.getElementById("show").style.maxHeight = '50px';
}
<div>
<button type="button" class="btn btn-primary" onclick="show();">Show</button>
</div>
<div id="show" style="background-color:#ccc;max-height:0;transition:all 0.5s;overflow:hidden">
<p>Hello!</p>
</div>
If you are using jQuery, you can use .slideDown("slow");
https://www.w3schools.com/jquery/jquery_slide.asp
$(document).ready(function(){
$("#thebtn").click(function(){
$("#show").slideDown("slow");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button type="button" class="btn btn-primary" id="thebtn">Show</button>
</div>
<div id="show" style="background-color:#ccc;display:none;">
<p>Hello!</p>
</div>
You can use Jquery. I use this:
$("#show").fadeIn(1000);
$("#show").fadeOut(1000);
$(document).ready(function(){
$("#thebtn").click(function(){
$("#show").fadeIn(1000);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button type="button" class="btn btn-primary" id="thebtn">Show</button>
</div>
<div id="show" style="background-color:#ccc;display:none;">
<p>Hello!</p>
</div>

Passing id as a parameter

I have a page that contains of multiple divs, each div has an ID that comes from the database, in each div there is a like button, what i want to do is when i click on the like button to pass the ID as a parameter in my function, here is what i have tried so far:
function addLike
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>
<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>
<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>
<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>
<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>
<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>
The IDs must be unique.
Whenever you define an inline click event handler you may consider to pass the following two variables:
this: current element
event: the event object
function addLike(ele, e) {
console.log('ID: ' + ele.id);
}
<div id="myID1" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>
<div id="myID2" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>
<div id="myID3" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>
<div id="myID4" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>
<div id="myID5" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>
<div id="myID6" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>
I suggest you to remove onClick from your divs:
<div id="myID">
and insert onclick in every button:
<button onclick="addLike(this.parent.id)">
First of all, you can only have one ID in a page. So I would first advise you use class instead of IDs. Now if you prefer to use IDs then each of the IDs should be unique. You should then have
<div id="id1" onClick="addLike(this.id)"></div>
<div id="id2" onClick="addLike(this.id)"></div>
Okay as far as i can see you are trying to make a like button.
For that i would suggest that instead of giving id to a <button> as its value.
And for the button action you have to create a form whose action will be on some other PHP or any other server side language. So for your problem here is the solution.
<form action="like.php" method="POST">
<div id="myid1">
<button value="myid1" name="button1">LIKE</button>
</div>
<div id="myid2">
<button value="myid2" name="button2">LIKE</button>
</div>
</form>
Now when you want to pass the value to a function then you can use the value of the button by its respective name attribute. You need to have different name for each button.

Disable entire DIV using Javascript/JQuery

I have following DIV which shows some controls:
<div id="buttonrow" class="buttonrow">
<div class="Add" title="Add">
<div class="AddButton">
<input id="images" name="images" title="Add Photos" multiple="multiple" type="file">
</div>
<div class="AddText">
Add
</div>
</div>
<div class="Upload" title="Upload">
<div class="UploadButton">
<button id="start" type="submit" title="Upload Photos">
</button>
</div>
<div class="UploadText">
Upload
</div>
</div>
<div class="Clear" title="Clear">
<div class="ClearButton">
<button id="reset" type="reset" title="Clear Photos">
</button>
</div>
<div class="ClearText">
Clear
</div>
</div>
<div class="Delete" title="Delete">
<div class="DeleteButton">
<button id="delete" type="button" title="Delete Photos">
</button>
</div>
<div class="DeleteText">
Delete
</div>
</div>
<div id="SelectAll">
<input title="Select All Images" id="selectAllCB" type="checkbox">
</div>
<div id="dragandrophandler">
Drag & Drop Your Photos Here
</div>
<div id="ImagesCount">
</div>
<div id="Loading" class="Loading">
<img alt="loading" src="../customcontrol/progress.gif">
<div>
Loading...</div>
</div>
</div>
I need to know how can I disable this entire DIV using Javascript/JQuery function?
EDIT: To disable DIV means user should not be able to interact with DIV controls. They must be in read-only state (non-clickable). I dont want to hide DIV!
in Javascript, you can use:
<script lnaguage="javascript">
document.getElementById('buttonrow').style.display='none';
</script>
use:
$("#buttonrow *").attr("disabled", "disabled").off('click');
Try this with .prop():
$("#buttonrow :input").prop("disabled", true);
:input will select all input elems including text, textarea, button, select etc.
$("button, input",$("#buttonrow")).attr("disabled", "disabled");
Can you please try this:
$("#buttonrow").each(function()
{
$(this).prop('disbaled',true);
});
Hope this helps..
$('#buttonrow').on('click', function(){
$(this).css({ 'opacity': 0.7 });
return false;
})

Categories

Resources