Getting String Value Of JavaScript Button - javascript

I have a list of buttons that is created by the DOM which references an array. When a button in the list is clicked, I want to retrieve the String that is displayed on the Button.
I have tried the following code to reference the string value, but get undefined:
this.String; inside the function when the button is clicked to retreive the string.
How can I properly retrieve the string.
The click handling function is:
$('.timeButtons').click(function() {
confirmation.push(this.textContent);
})
This is how the list of buttons is created:
var populateList=function(array){
var list = document.createElement('ul');
list.className="delete";
for(var i = 0; i < array.length;- i++) {
var item = document.createElement('li');
var itemButton=document.createElement('button');
itemButton.style.cssText='background:#f85a5a; border:none; width:200px; height:50px; margin-bottom:50px; align:center; border-radius:25px; color:#ffffff;'
itemButton.appendChild(document.createTextNode(array[i]));
item.appendChild(itemButton);
list.appendChild(item);
}
return list;
}

Assuming that this is a reference to the button element in question, you can use this.textContent to get the button's text. (Or .innerHTML.)
Demo: http://jsfiddle.net/w0ntsrLx/
Or since in your edited question you seem to be using jQuery, use the .text() method. In a comment you say that the containing div has the "timeButtons" class, so bind a delegated handler to that div as follows:
$(".timeButtons").on("click", "button", function(e) {
confirmation.push($(this).text());
});
Demo: http://jsfiddle.net/w0ntsrLx/1/
That way the function will only be called if the click is on a button element within the .timeButtons div, and this will be the clicked button. The click handler that you show in your question with $(".timeButtons").click(...) is bound to the div and doesn't in any way test for the buttons, so within the handler this will be the div, not the clicked button.

Check this out
Assuming you want pure javascript code,
Whenever an event is triggered, an object is passed back in callback (generally being named as 'event'). this object has many properties including source element, position of click and many more.
get the element using event.srcElement
You can use element.innerHTML or element.innerText to find out the content of the Button.
There is a difference between using innerText and innerHTML, but in your case, both can be used.
Also, you can use jquery too to easily append child, create elements and binding events.

Related

JavaScript focus a particular element with div class, not div id declaration

The following function can focus on an element with an id declaration:
function setFocus() {
document.getElementById("focus").focus();
}
But how can one focus on an element with a classname declaration. Use case would be previously in the code where the element we want to focus on is already stored from the dom (i.e., const element = document.querySelectorAll('.a-class-name')[0]) type of scenario?
Does the element have a tab index? You cannot focus a non input element unless it has a tab index. Use tabindex="-1" for elements like divs and spans. Then call the .focus() method on the element. -1 will allow you to focus with the focus method but wont get focus when move the focus around with the keyboard and pressing tab.
document.getElementById('btn').addEventListener('click', function() {
document.querySelectorAll('.focus_me')[0].focus();
});
<span class="focus_me" tabindex="-1">Focus me</span><br>
<button id="btn">Click to focus</button>
element.scrollIntoView(true) will do what you are needing.
document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array returned, as you did.
var elements = document.getElementsByClassName('className');
var requiredElement = elements[0];
OR
var requiredElement = document.querySelector('.className');
Then as #j08691 mentioned in the comments use
function setFocus() {
requiredElement.focus();
}
If the one with getElementById works, then there is no reason for this to not.
Happy coding. :)

How can I check which element has been clicked, if the elements have no id? Using only Javascript

I have a form with two inputs. When submit is clicked, the following happens:
An object with two properties (one for each input) is created.
Each object is pushed into an array.
A div is created, the object's values are put into the inner HTML of the div.
A span is created, and is appended into the div.
When a div's span is clicked, I want that specific div to no longer appear, meaning the object whose values are in the innerHTML of that div should be removed from the array.
How can I know which span was clicked?
In your event listener you can check it with target property in event you get.
event.target
You can use document.getElementsByTagName('span') returns a NodeList of DOM Elements. So for starters, you will have to iterate over them and attach a handler to each like this :
var spans = document.getElementsByTagName('span');
for (var i = spans.length - 1; i >= 0; --i)
{
spans = spans[i];
// do something to span
// forexample: spans.onclick = clickHandler;
}
Hope that helps!!
Attach 'onClick' event on div (point number 3).
then use this.event.currentTarget (in this case you will get the clicked span tag/div tag).
Then remove the span tag or the parent element using this.remove() method.

Can someone please explain my function deleteButton(this)?

Here is the link to my codepen to see all my code: http://codepen.io/stevengangano/full/LGvRdq/
My question has to do with my deleteButton function. I have trouble grasping this concept.
I created a function for the delete button called deleteButton(item). I just want to know what does "item" and "parentNode" represent in the variable remove? Which one is the <ul> and which one is the <li>?
An explanation would be appreciated. Thanks!
deleteButton(item) is attached to the removeButton. this represents the current node which is button itself.
item.parentNode will be nothing but parent of the button which is li element. remove variable holds this li element.
Again remove.parentNode will return parent node of the li element which is ul element.
paretNode.removeChild removes a child node from the DOM
So in this case, UL_ELEMENT.removeChild(LI_ELEMENT);
function deleteButton(item) {
var remove = item.parentNode;
remove.parentNode.removeChild(remove);
}
in your code (posted offsite) is long for
function deleteButton(item) {
item.parentNode.parentNode.removeChild(item.parentNode);
}
which removes the parent node of the clicked item from its grandparent node's list of children. The parent node of the delete button is listItem in code, which means an LI item will be deleted.
Elsewhere in code posted offsite (bad practice™) the delete function is defined as
removeButton.setAttribute('onclick', 'deleteButton(this);');
which is seriously really very, interesting. It suggests that setting an onclick attribute with text, after HTML parsing has been completed, causes the text to be parsed as source for a javascript function which becomes the attribute value. Okay, so a setter can do this - but onEvent setters doing this is news to me. And testing indicates it being true.
So an answer is that setting the onclick attribute of a node with text compiles the text to a function object, attaches the function object as the onclick attribute value, which when called by clicking supplies the node being clicked on as the this object for the onclick handler. If the function called removes the parent node of the clicked object, in this case an LI element gets removed.

how to select a div from multiple div on jquery click event if all div have same class?

I have a div with a class .display_noti and inside it I have append another div with class .palnotific by jquery.I have fetched data from database and i converted that fetched data into json_encode.I used that json format data and made some information which were append on that div with class .palnotific.
my first jquery code which append data inside that div with class .display_noti looks like :-
$.getJSON("notification.php",function(data){
// you can do checking here
if ( data.result && data.result.length > 0 ) {
$(".display_noti").empty(); // Clear out the div
$.each(data.result,function(){
$(".display_noti").append("<div class='palnotific'>You got a pal requet from <strong>"+this['from_user']+"</strong><br><span class='date'>"+this['notification_date']+"<form method='post'><input type='text' class='palid' value='"+this['pals_id']+"'></form></div>");
});
done();
}
else {
$(".display_noti").append("<div class='palnotific' style='background-color:white;'>You have no notification to view.</div>");
}
Above I first get the json format data and I did some validation and then at last I append that second div with class .palnotific inside that first div with a class .display_noti.I have a form inside that append div which I use to take value from a input for use.
As we know .palnotific is an appended div.I wanted to use some Onclick event function on it so, I used below code :-
$('body').on('click','.palnotific',function(){
var x = $(this).closest('.display_noti').find('.palid');
var pid=x.val();
$.ajax({
url:'notifipro.php',
type:'post',
data:"palid="+pid,
success: function(data){
if(data==1)
{
$(window).load('oldpage.php');
}
if(data==2)
{
$(window).load('newpage.php');
}
}
});
});
Above code takes the input value from that form which was inside that .palnotific div which was appended from jquery at previous.As you know those appended div carry data from database via json_encode.It will take value as much as available in database which mean if there's 2 data in database json_encode will also have 2 data and those append div class which takes data from json_encode will append 2 time that div with a class palnotific.Now my problem is that if i have two div with class palnotifi origin from that append my click function work for first div only and when i click on second div onclick function doesn't work.No matter I have 2 or more then two div if I click any one div first div click function takes action.How can I make work onclick function to those div only which have been clicked?
The easiest way to have jquery react on an element that is dynamically created, is to attach the event to that element itself. Another way would be using on on a the container div with a subfilter, but since you are already creating the html, you can encapsulate it in $('yourhtml') and attach the click directly to that created element. In combination with appendTo instead of append, you can also chain the append and click:
//mock data:
var data={result: [
{from_user: 'A', notification_date: new Date(), pals_id: 1},
{from_user: 'B', notification_date: new Date(), pals_id: 2},
{from_user: 'C', notification_date: new Date(), pals_id: 3}
]};
$.each(data.result,function(){
var id = this.pals_id;
$("<div class='palnotific'>You got a pal request from <strong>"+this['from_user']+"</strong><br><span class='date'>"+this['notification_date']+"<form method='post'><input type='text' class='palid' value='"+ id +"'></form></div>")
.appendTo(".display_noti")
.click(function(){
//attach pre existing function or assign your logic here
alert('You clicked ' + id);
})
});
Example fiddle
In this example, the id was also stored before hand and reused inside the attached click. If you need to use the raw value, you can use $(this).find('.palid').val() (as done in this fiddle )
From the code you paste, the problem should be this line:
var pid=x.val();
as you can find in jQuery docs (http://api.jquery.com/val/)
.val() Get the current value of the first element in the set of matched elements or set the value of every matched element.
You can use a more specific CSS3 Selector in the on() function. I'm not entirely sure this is going to solve your overall problem, but it might lead you in the right direction.
$(".display_noti").on("click", ".palnotific:first", function(event) {
console.log("You Clicked: ", event.target.id);
});
Here is an example JSFiddle;

Why create loops to get elements for events?

The textbook I'm using to learn JavaScript uses the following code to display an alert dialogue whenever a user clicks on a paragraph:
var paras = document.getElementsByTagName("p");
for (var i=0; i<paras.length; i++) {
paras[i].onclick = function() {
alert("You clicked on a paragraph.");
}
}
I don't see the reason to loop through all the p elements, but instead identify them and simply attach the onclick event handler to it. Like this:
var paras = document.getElementByTagName('p');
paras.onclick = alert("You clicked on a paragraph.");
Doesn't that do the same thing? Why is it necessary to loop through the p elements?
No, that absolutely does not do the same thing:
You simply cannot attach event handlers to an HTML node list (well, you can, but nothing will happen);
You're trying to set the "onclick" to the result of the alert() statement, not a function as in your example. (Doesn't really matter because it won't work anyway.)
Now there is a way to handle the clicks with just one event handler, but I'll let you keep reading your book :-)
edit — To elaborate on point 2, this:
alert("hi");
is a function call. Its value will be whatever is returned from calling that function. Thus,
paras.onclick = alert("You clicked on a paragraph.");
sets the "onclick" property of the object that "paras" refers to, and it sets it to the value returned from alert() (which is probably always undefined).
As in the sample code from your book, things like "onclick" handlers need to be functions. That's what's going on in the middle of your sample code: the "onclick" property of each individual <p> DOM element is being set to a function. Inside that function is the call to alert().
Suppose you have
​<p>​First Paragraph</p>
<p>Second Paragraph</p>
<p>Third Paragraph</p>
So var paras = document.getElementsByTagName("p"); will return a collection of p like
[<p>​First Paragraph​</p>​, <p>​Second Paragraph​</p>​, <p>​Third Paragraph​</p>​]
If you write paras.onclick = alert("You clicked on a paragraph."); then it won't work because paras is an array of some p elements not the p element itself and only an html element has an event, so you have to loop through the collection and add event handler for each p element individually.
Even if you have only one p then it will return an array with one p element inside it, i.e.
​<p>​First Paragraph</p>
And var paras=document.getElementsByTagName("p"); will return[<p>​First Paragraph​</p>​]
So to add an event handler you can simply write
paras[0].onclick = function() { // 0 is the first element in the collection
alert(this.innerHTML);
}
Here is an example, I hope it'll help you to understand the process.
No, that will not work.
The function document.getElementsByTagName will return you an array of nodes because several nodes can have the same name (hence the plural for "Elements") : you can have several paragraph in you page, and this function will return them all. Even if you have only one paragraph, you will get an array containing one single element.
On the other hand, you could select the node with its ID by using the document.getElementById function. In this case, the result will be a single node, because IDs are supposed to be unique within a document.
var para = document.getElementByTagId('myParagraph');
paras.onclick = function(){ alert("You clicked on a paragraph.") };

Categories

Resources