Get HTML DOM elements inside a javascript function - javascript

I am trying to implement something like this. IF you click the button it would get the HTML of the above elements and insert them in an alert :
<div id="0001">
<h5 class="title">Hello World </h5>
<h4 class="date">2014-07-19 </h4>
<button onclick="addCalendar('#0001. #title','#0001. #date')"> Add to Calendar </button>
</div>
<div id="0002">
<h5 class="title">Bye Bye</h5>
<h4 class="date">2014-07-22 </h4>
<button onclick="addCalendar('#0002. #title','#0002. #date')"> Add to Calendar </button>
</div>
<script>
function addCalendar(title,date){
alert(title + ": " + date);
}
</script>

This code should works..
If you want to get the value of that HTML:
$("button").click(function(){
var value = $(this).siblings("#title").text();
value += $(this).siblings("#date").text();
alert(value);
});
If you want to get the HTML tags too:
$("button").click(function(){
var value = $(this).siblings("#title").html();
value += $(this).siblings("#date").html();
alert(value);
});

Related

Javascript - Retrieving values of a div when a button inside that div is clicked

I'm writing the code to edit a database table.
I have the following HTML:
<div id="1">
<div contenteditable>aaa</div>
<div contenteditable>bbb</div>
<div contenteditable>ccc</div>
<button onClick="a('save')">SAVE</button>
<button onClick="a('delete')">DELETE</button>
</div>
<div id="2">
<div contenteditable>ddd</div>
<div contenteditable>eee</div>
<div contenteditable>fff</div>
<button onClick="a('save')">SAVE</button>
<button onClick="a('delete')">DELETE</button>
</div>
<div id="3">
<div contenteditable>ggg</div>
<div contenteditable>hhh</div>
<div contenteditable>iii</div>
<button onClick="a('save')">SAVE</button>
<button onClick="a('delete')">DELETE</button>
</div>
And so on.
Using the following function, I can get the clicked button:
function a(value) {
console.log(value);
}
When a button (SAVE or DELETE) is clicked, I need to retrieve:
the id of the "parent" div;
the content of each of the three contenteditable divs inside the same "parent" div.
Is it possible using pure Javascript?
Any suggestion will be very appreciated.
Thanks in advance.
What I would do is implement click listeners in JS, that way I can query elements easily.
Here is the example:
// Query all div.div-editable elements
document.querySelectorAll('div.div-editable')
.forEach((div) => {
// The id of the parent
const divId = div.id;
// Each of content editable divs inside the parent div
const editables = div.querySelectorAll('div[contenteditable]');
// The buttons Save and Delete
const saveBtn = div.querySelector('button.button-save');
const deleteBtn = div.querySelector('button.button-delete');
// Add click listeners to buttons
saveBtn.addEventListener('click', function() {
console.log('Saved: ' + divId);
const contentOfEditableDivs = Array.from(editables).map((div) => div.innerText);
console.log('Values of divs:', contentOfEditableDivs);
});
deleteBtn.addEventListener('click', function() {
console.log('Deleted: ' + divId);
const contentOfEditableDivs = Array.from(editables).map((div) => div.innerText);
console.log('Values of divs:', contentOfEditableDivs);
});
});
<div id="1" class="div-editable">
<div contenteditable>aaa</div>
<div contenteditable>bbb</div>
<div contenteditable>ccc</div>
<button class="button-save">SAVE</button>
<button class="button-delete">DELETE</button>
</div>
<div id="2" class="div-editable">
<div contenteditable>ddd</div>
<div contenteditable>eee</div>
<div contenteditable>fff</div>
<button class="button-save">SAVE</button>
<button class="button-delete">DELETE</button>
</div>
<div id="3" class="div-editable">
<div contenteditable>ggg</div>
<div contenteditable>hhh</div>
<div contenteditable>iii</div>
<button class="button-save">SAVE</button>
<button class="button-delete">DELETE</button>
</div>
EDIT 1: Added code snippet
EDIT 2: Simplified explanation
You can send this keyword in the argument of click's event handler and then access the parent div's id.
So your HTML would look something like:
// rest of the code here
<button onClick="a(this, 'save')">SAVE</button>
<button onClick="a(this, 'delete')">DELETE</button>
// rest of the code here
And your JS code would change to:
function a(elem, value) {
console.log(elem.parentNode.id);
}
More details on the following link:
how i get parent id by onclick Child in js

Unable to find the specific items value jQuery

I am facing an easy problem but unable to find a solution the problem is
i am creating a dynamic div with some elements also with some data
$("#divSearchedIssue").append(`
<div class="statistic d-flex align-items-center bg-white has-shadow">
<div class="icon bg-red">
<i class="fa fa-tasks"></i>
</div>
<div class="text">
***//want to get this below id value//**
Mobile Code :
<small id="mbCode">
${ data[0].MobileCode }
</small>
***/want to find/**
<br>
Failed From:
<small>
${ data[0].FailedStation }
</small>
<br>
Issues :
<small>
${ data[0].Issues }
</small>
</div>
<div class="text"><strong> </strong></div>
<div class="text">
<button type="button" id="btn" class="btn btn-warning pull-right">Start</button>
</div>
<div class="text"><br></div>
</div>`);
Here I have a button .On this button click i want to fetch the value of
small text which id is #mbCode as mentioned above inside the code
I am trying this by using the following button click code
$(document).on('click', '#btn', function () {
var data = $(this).closest('small').find('#mbCode').val();
alert(data);
});
but its not working.I mean I cant fetch the value of #mbCode on this button click .So help needed
Thanks for helping
Based on .closest()
Description: For each element in the set, get the first element that
matches the selector by testing the element itself and traversing up
through its ancestors in the DOM tree.
As <small> is not an ancestors to button in hierarchy(while traversing-up),
So You need to first go the parent of <small> through .closest() and then try to find <small> html using .find() and .html()
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').html();
alert(data);
});
Working snippet:-
data = [{'MobileCode':20,'FailedStation':'WATERLOO','Issues':'broken'}];
$("#divSearchedIssue").append('<div class="statistic d-flex align-items- center bg-white has-shadow"><div class="icon bg-red"><i class="fa fa-tasks"></i></div><div class="text">Mobile Code :<small id="mbCode">' + data[0].MobileCode + '</small><br>Failed From: <small> ' + data[0].FailedStation + '</small><br>Issues :<small> '+ data[0].Issues + '</small></div><div class="text"><strong> </strong></div><div class="text"><button type="button" id="btn" class="btn btn-warning pull-right">Start</button></div><div class="text"><br></div></div>');
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').each(function(){
alert($(this).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Note:- .text() will work too
https://jsfiddle.net/tyz4ox50/
As identifiers must be unique, Directly use ID Selector with .text()/.html() method
var data = $('#mbCode').text()
However if you are appending multiple elements I would recommend an alternative to persist Mobile code arbitrary data using custom data-* attribute along with <button> which can be fetched using .data(key) and attach event handler using Class Selector
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + data[0].MobileCode + '" >Start</button>');
var counter = 0;
function append() {
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + ++counter + '" >Start</button>');
}
append();
append();
append();
$(document).on('click', '.btn', function() {
var data = $(this).data('mobilecode');
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Try the following code snippet
var value = $('#mbCode').val();
Make sure the id is unique
Ids shouldn't be duplicate in an web-page.
Also, small is not one of the parent nodes of btns, and use html instead of val.
You need to go two-level higher to statistic Make it
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
Demo
var counter = 0;
function append() {
$("#divSearchedIssue").append(
`<div class="statistic d-flex align-items-
center bg-white has-shadow">
<div class="icon bg-red"><i class="fa fa-tasks">
</i></div>
<div class="text">
Mobile Code :<small id="mbCode">` +
(counter++) +
`</small><br>Failed From: <small> ' +
data[0].FailedStation + '</small><br>Issues :<small> ' + data[0].Issues +
'</small></div>
<div class="text"><strong> </strong>
</div>
<div class="text"><button type="button" id="btn" class="btn btn-
warning pull-right">Start</button></div>
<div class="text"><br></div>
</div>`
);
}
append();
append();
append();
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
If your element already has an ID attribute you should be able to find the element by the ID. $("#mbCode")
Your js code
$(this).closest('small').find('#mbCode').val(); // "$(this)", in your code, represents the "button" that was clicked.
is looking for "small" tag inside "button" element, but it's not there. It would work if your button was like
<button type="button" id="btn" class="btn btn-warning pull-right"><small id="mbCode"></small></button>
This should work:
$(document).on('click', '#btn', function () {
var $mbCode = $('#mbCode');
console.log($mbCode);
});

Dynamically create a class name in 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();
});

Dynamically Updating Controls ASP.Net and Bootstrap

I cannot for the life of me work out how to update bootstrap controls with ASP.Net.
I have the following code:
#{
Layout = null;
}
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title Mark Hub</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<script>
var url = "http://localhost:51520/api/teacher/"
function getTerms(course) {}
//get a reference to the select element
$select = $('#termSelect');
//request the JSON data and parse into the select element
$.ajax({
url: url + "global/currentterms/" + course ,
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.person, function(key, val){
$select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});
</script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Mark Hub", "Index", "Teacher", null, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Teacher", "Index", "Teacher")</li>
<li>#Html.ActionLink("Admin", "Index", "Admin")</li>
</ul>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-1 text-left">
<select class="form-control" id="courseSelect" onclick="getTerms()">
<option>DEC 10</option>
</select>
</div>
<div class="col-md-1 text-left">
<select class="form-control" id="termSelect">
</select>
</div>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<hr />
<footer>
<p>© #DateTime.Now.Year</p>
</footer>
</div>
</div>
</div>
</div>
</body>
</html>
I am trying to take the value the user selects (I only have one for convenience at the moment) from the courseSelect control, pass it to my Javascript function getTerms, call a web api and populate the termSelect control dynamically from the returned JSON.
Selecting a value from my courseSelect combobox is not updating my termSelect combobox.
How would I fix my code?
EDITED WITH UPDATE CODE TO REFLECT UPDATES IN ANSWERS
<script>
var url = "http://localhost:51520/api/teacher/"
$(function(){
$('#courseSelect').on('change',function(){
// This is equal to your getTerms function
var course = $('#courseSelect').val();
//request the JSON data and parse into the select element
$.ajax({
url: url + "global/currentterms/" + course,
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.termID, function(key, val){
$select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
})
})});
</script>
My code still doesn't work and when I add a breakpoint in VS, the function isn't called on me selecting a value from the select box courseSelect.
You are calling this function getTerms() on click of the select tag.. which is wrong.. you must use on change event . Even click will work but then it will get trigerred even if you click the text box which will do a API call , this is unnecessary request .. Also stop using inline event binder it's deprecated and soon will stop working in future, you must bind event using on in Jquery change your code to below.
Remove the onClick in your HTML
<select class="form-control" id="courseSelect">
<option>DEC 10</option>
</select>
Then in Jquery use this
$(function(){
$('#courseSelect').on('change',function(){
// This is equal to your getTerms function
var course = $(this).val();
// rest of your logic goes here
});
});
your javascript' function is getTerms(course), while you are calling it on your click method as getTerms()
so you should change your javascript as following :
function getTerms() {}
//get a reference to the select element
$select = $('#termSelect');
$course= $('#courseSelect').val(); // this is how you get the value of course
//your next code

Get specific data from page and write it to div

I'm building an online store with javascript shopping cart. However, the script doesn't allow printing only one or two values when displaying cart, but I need to do this.
Here's what the cart looks like:
<div class="simpleCart_items">
<div>
<div class="headerRow">
<div class="item-name">Tuote</div>
<div class="item-price">Hinta</div>
<div class="item-decrement">-</div>
<div class="item-quantity">Määrä</div>
<div class="item-increment">+</div>
<div class="item-total">Yhteensä</div>
<div class="item-remove">Poista</div>
</div>
<div class="itemRow row-0 odd" id="cartItem_SCI-1">
<div class="item-name">Teipit</div>
<div class="item-price">€0.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">3</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€0.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
<div class="itemRow row-1 even" id="cartItem_SCI-3">
<div class="item-name">Car Speaker -hajuste</div>
<div class="item-price">€4.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">1</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€4.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
<div class="itemRow row-2 odd" id="cartItem_SCI-5">
<div class="item-name">Teipit (Musta hiilikuitu)</div>
<div class="item-price">€0.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">1</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€0.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
</div>
</div>
NOTE: The cart is written via javascript so it isn't visible in page source, only in inspect mode of the browser.
So how would I gather the item-name, item-priceand item-quantity?
I've tried this:
var name = $('.item-name');
var price = $('.item-price');
var quantity = $('.item-quantity');
var data = name + price + quantity;
$('#items').html(data);
But this won't actually do anything.
When doing this -> $('.item-name');
You are just capturing the element as object but not the value.
Now that you got your element as object, you need to extract the value and, in this case, your element object is a div so you can try .text() or .html() (to get the text or html inside the div).
(For this situation I will use text() cause you are working just with values and there is nothing related to html)
Try this:
var name = $('.item-name');
var price = $('.item-price');
var quantity = $('.item-quantity');
var data = name.text() + price.text() + quantity.text();
$('#items').html(data);
Better solution:
This will make clickable the div in which you have the product and match the cartItem_SCI pattern.
So, when user clicks any of the elements of your cart, you will get the name, price and quantity values that will be attached to the $('#items') div using append() method instead of html() (because using this will replace the product information each time the user clicks a div)
$(document).ready(function() {
$('div[id^="cartItem_SCI-"]').css({ cursor:'pointer' });
$('div[id^="cartItem_SCI-"]').click(function() {
var name = $(this).find('.item-name');
var price = $(this).find('.item-price');
var quantity = $(this).find('.item-quantity');
var data = name.text() + ' - ' + price.text() + ' - ' + quantity.text();
$('#items').append(data + '<br/>');
});
});​
You are just getting a reference to the class, add .html() to get the inner html of the element that the class applied to.
var name = $('.item-name').html();
For one item you can get like this.But since you have multiple items make one object like this .
var item={};
$('.item-name').each(function(){item.name=$(this).html()});
$('.item-price').each(function(){item.price=$(this).html()});
$('.item-quantity').each(function(){item.quantity=$(this).html()});
var data='';
for(var i=0;i<item.length;i++)
{
data+=item[i].name+item[i].price+item[i].quantity;
}
$('#items').html(data);

Categories