jquery - adding new element attribute - javascript

I set a new property on a table element (each table should have the property selectedRow, which is a pointer to the tr element that is selected), but actually between calls of my click handler, that property becomes null:
$("table.grid").each(function () {
this.selectedRow = null;
});
var selectRow = function (tr) {
var table = tr.parents("table").get();
if (table.selectedRow == tr.get()) return;
// table.selectedRow still NULL!!!!!!!!!!!
if (table.selectedRow) {
var unselect = $(table.selectedRow);
unselect.removeClass('selectedChilds');
unselect.prev('tr').removeClass('siblingUpChilds');
unselect.next('tr').removeClass('siblingDownChilds');
}
table.selectedRow = tr.get();
tr.addClass('selectedChilds');
tr.prev('tr').addClass('siblingUpChilds');
tr.next('tr').addClass('siblingDownChilds');
}
$('table.grid tr').click(function (e) {
selectRow($(e.delegateTarget));
});

Use data(key[, value]) to set/get properties:
$('#my-elem').data('selected_row', '...');

Related

How do I add event listener to dynamic element Id?

I am using firebase DB to dynamically generate some html using the function below.
function Inventorytable(data) {
var container = document.getElementById('iteminfo');
container.innerHTML = '';
data.forEach(function(InventSnap) { // loop over all jobs
var key = InventSnap.key;
var Items = InventSnap.val();
var jobCard = `
<td class="text-left" id="${key}"><a href>${key}</a href></td>
<td class="text-left" >${Items.PartNumber}</td>
`;
container.innerHTML += jobCard;
})
}
I want to add an event listener to the first td class with id="${key}". I know with a normal id I can use document.getElementById("xxxx").addEventListener but since this is dynamic and the id is the firebase key. How do I add an event listener using the element id?
You could change your logic to create the td elements and add the event handler to them at that point. This avoids the issue of deleting the existing HTML within the container, along with all the existing event handlers. Try this:
data.forEach(function(InventSnap) { // loop over all jobs
var key = InventSnap.key;
var Items = InventSnap.val();
var td0 = document.createElement('td');
td0.id = key;
td0.classList.add('text-left');
container.appendChild(td0);
td0.addEventListener('click', function() {
console.log('clicked!');
});
var a = document.createElement('a');
a.href = '#';
a.innerText = key;
td0.appendChild(a);
var td1 = document.createElement('td');
td1.innerText = Items.PartNumber;
td1.classList.add('text-left');
container.appendChild(td1);
});
Or the equivalent of this in jQuery would be:
data.forEach(function(inventSnap) {
var key = inventSnap.key;
var items = inventSnap.val();
var $td = $(`<td class="text-left" id="${key}">${key}</td>`).on('click', function() {
console.log('clicked!');
}).appendTo(container);
container.append(`<td class="text-left">${items.PartNumber}</td>`);
});
Create a function to call when all append data is finished !! I tested with add() ,also for more easy to handle ,add one distinct class name to td !!!
var data = [
{key:0,val:"Zero"},
{key:1,val:"One"}
]
Inventorytable(data);
function Inventorytable(data) {
var container = document.getElementById('iteminfo');
container.innerHTML = '';
data.forEach(function(InventSnap) { // loop over all jobs
var key = InventSnap.key;
var Items = InventSnap.val;
var jobCard = `
<td class="text-left first" id="${key}"><a href="#!">${key}</a href></td>
<td class="text-left" >${Items}</td>
`;
container.innerHTML += jobCard;
});
add();
}
function add() {
var container = document.querySelectorAll(".first");
[].map.call(container, function(elem) {
elem.addEventListener("click",function(){
console.log(this.id);
}, false);
});
}
<table>
<tr id="iteminfo"></tr>
</table>
I would suggest adding a click handler to the #iteminfo as otherwise you would have stall event listeners around when you reorganize your table.
var container = document.getElementById('iteminfo');
container.addEventListener( 'click', ( e ) => {
const id = e.target.id;
console.log( id );
} );
var data = [
{ key: 1 },
{ key: 2 },
{ key: 3 },
{ key: 'some-other-key' },
]
function Inventorytable(data) {
container.innerHTML = '';
data.forEach(function(InventSnap) { // loop over all jobs
var key = InventSnap.key;
var jobCard = `<button id="${key}">${ key }</button>`;
container.innerHTML += jobCard;
})
}
Inventorytable( data );
<div id="iteminfo"></div>
Normally: Exactly the same way.
You have the ID in a variable. You can get the element. document.getElementById(key).
… but there's a problem.
container.innerHTML += jobCard;
You keep taking the DOM (with any element listeners bound to it), converting it to HTML (which doesn't carry the event listeners across), appending to it, then converting the HTML back to DOM (giving you a new set of elements without the event listeners).
Rather than destroying the elements each time, you should create them using standard DOM. You can then call addEventListener after creating the element.
data.forEach(function(InventSnap) { // loop over all jobs
var key = InventSnap.key;
var Items = InventSnap.val();
var td = document.createElement("td");
td.setAttribute("class", "text-left");
td.setAttribute("id", key);
td.addEventListener("click", your_event_listener_function);
var a = document.createElement("a");
a.setAttribute("href", "");
a.appendChild(document.createTextNode(key));
td.appendChild(a);
container.appendChild(td);
td = document.createElement("td");
td.setAttribute("class", "text-left");
td.appendChild(document.createTextNode(Items.PartNumber));
container.appendChild(td);
})
You could (either with your original approach or in combination with the above) use delegated events instead:
container.addEventListener("click", delegated_event_listener);
function delegated_event_listener(event) {
if (test_what_element_was_clicked_on(this)) {
do_something_with(this.id);
}
}
You can use event delegation for this:
document.addEventListener('click',function(e) {
if(e.target && e.target.id === "yourID") {
//do something
}
});

javascript ~ turn a div into a button

I am trying to get my code onto a page where I am not allowed a lot of changes; the person hosting the page allows me a <script> tag & a <div>, that's it.
--- page ---
<head>
<script type='text/javascript' src='https://example.com/myJSfile.js'>
</head>
<body>
<div id='mydiv'></div>
</body>
------------
When the page loads, how do I turn mydiv into a button, when I can only customize myJSfile.js?
I cannot promise any typical libraries such as jQuery will be loaded for me,
the host's site does load CSS, but I don't know the structure of their styles. Maybe I will have to learn some of it at some point.
If my code needs to load jQuery, I first have to check that it isn't already loaded. How would you do that specifically that check?
If I need to load my own css then I will have to do so dynamically using myJSfile.js
myJSfile.js js file can be anything I need it to be. I have full control over it.
How would you go about this?
Please remember that, besides myJSfile.js, I am pretty much locked out of anything on the page except the script & div tags.
Use insertbefore() function to add the new element, then the remove() function, to remove the existing <div> element:
// Create a <li> node:
var newItemDocument.createElement("LI");
// Create a text node
var textnode = document.createTextNode("Water");
// Append the text to <li>:
newItemDocument.appendChild(textnode);
// Get the <ul> element to insert a new node:
var list = document.getElementById("myList");
// Insert <li> before the first child of <ul>:
list.insertBefore(newItemDocument, list.childNodes[0]);
While you've already accepted an answer, I thought I'd take a moment to try and offer an answer that might anticipate your future requirements of adding event-listeners to the element(s) you want to insert, and perhaps replacing multiple elements with a common element:
// using a named, rather than an anonymous, function in
// order that the same function can be reused multiple
// times:
function replaceElementWith(opts) {
// these are the default settings:
let settings = {
'replaceWhat': '#mydiv',
'replaceWith': 'button',
'text': 'this is a button',
'eventHandlers': null
};
// here we iterate over all the keys in the
// (user-supplied) opts Object to override
// the defaults; we do this by first retrieving
// the keys of the opts Object, which returns
// an Array of those keys, and iterating over
// that Array using Array.prototype.forEach():
Object.keys(opts).forEach(
// here we use an arrow function syntax, since
// don't need to work with an updated 'this'
// within the function.
// key : the current key of the Array of keys,
// here we update the current key of the
// settings Object (or add a new key to that
// Object) to the same value as held in the
// opts Object:
key => settings[key] = opts[key]
);
// in order to allow you to perform the same replacement
// on multiple elements, we use document.querySelectorAll()
// to retrieve all elements matching the supplied CSS
// selector, and then pass that Array-like NodeList to
// Array.from(), which converts an Array-like structure to
// an Array:
let targets = Array.from(
document.querySelectorAll(
// this is the CSS selector passed via the
// opts.replaceWhat value (here '#mydiv'):
settings.replaceWhat
)
),
// here we create a new element according to the value
// passed via the settings.replaceWith value:
newElem = document.createElement(
settings.replaceWith
),
// an empty, uninitialised variable to hold the cloned
// newElem element within the loop (later):
clone;
// we set the textContent of the created Element to be
// equal to the passed-in text, via the opts.text property:
newElem.textContent = settings.text;
// here we iterate over the Array of found elements that
// are to be replaced:
targets.forEach(
// again, using an Arrow function expression:
target => {
// here we clone the created-element, along with
// any child nodes:
clone = newElem.cloneNode(true);
// unfortunately Node.cloneNode() doesn't clone
// event-listeners, so we have to perform this
// step on every iteration, we first test to
// see if settings.eventHandlers is a truthy
// value (so not the default null):
if (settings.eventHandlers) {
// if there are eventHandlers, then we retrieve
// the keys of the settings.eventHandlers
// Object as above:
Object.keys(settings.eventHandlers).forEach(
// using Arrow function again;
// the keys of this object are the event-types
// we're listening for and the values are the
// functions to handle that event, so here
// we add the 'eventType' as the event,
// and the 'settings.eventHandlers[eventType]
// (which retrieves the function) as the handler:
eventType => clone.addEventListener(eventType, settings.eventHandlers[eventType])
)
}
// here we find the parentNode of the element to be
// replaced, and use Node.replaceChild() to add the
// new element ('clone') in place of the target element:
target.parentNode.replaceChild(clone, target)
})
}
// calling the function, passing in values:
replaceElementWith({
// CSS selector to identify the element(s) to be removed:
'replaceWhat': '#mydiv',
// the eventHandlers Object to define the
// created element's event-handling:
'eventHandlers': {
// in the form of:
// 'eventName' : eventHandler
'click': function(e) {
e.preventDefault();
document.location.hash = 'buttonClicked';
this.style.opacity = this.style.opacity == 0.5 ? 1 : 0.5;
},
'mouseenter': function(e) {
this.style.borderColor = '#f90';
},
'mouseleave': function(e) {
this.style.borderColor = 'limegreen';
}
}
});
function replaceElementWith(opts) {
let settings = {
'replaceWhat': '#mydiv',
'replaceWith': 'button',
'text': 'this is a button',
'eventHandlers': null
};
Object.keys(opts).forEach(
key => settings[key] = opts[key]
);
let targets = Array.from(document.querySelectorAll(settings.replaceWhat)),
newElem = document.createElement(settings.replaceWith),
clone;
newElem.textContent = settings.text;
targets.forEach(
target => {
clone = newElem.cloneNode(true, true);
if (settings.eventHandlers) {
Object.keys(settings.eventHandlers).forEach(
eventType => clone.addEventListener(eventType, settings.eventHandlers[eventType]);
)
}
target.parentNode.replaceChild(clone, target)
})
}
replaceElementWith({
'replaceWhat': '#mydiv',
'eventHandlers': {
'click': function(e) {
e.preventDefault();
document.location.hash = 'buttonClicked';
this.style.opacity = this.style.opacity == 0.5 ? 1 : 0.5;
},
'mouseenter': function(e) {
this.style.borderColor = '#f90';
},
'mouseleave': function(e) {
this.style.borderColor = 'limegreen';
}
}
});
div {
border: 2px solid #f90;
}
button {
border: 2px solid limegreen;
}
<div id='mydiv'></div>
JS Fiddle demo.
The below demo does exactly the same as above, but does so working with multiple elements to be replaced, and the only change made is to the function call:
replaceElementWith({
// changed this selector to select by class,
// rather than id (and added multiple elements
// to the HTML):
'replaceWhat': '.mydiv',
'eventHandlers': {
'click': function(e) {
e.preventDefault();
document.location.hash = 'buttonClicked';
this.style.opacity = this.style.opacity == 0.5 ? 1 : 0.5;
},
'mouseenter': function(e) {
this.style.borderColor = '#f90';
},
'mouseleave': function(e) {
this.style.borderColor = 'limegreen';
}
}
});
function replaceElementWith(opts) {
let settings = {
'replaceWhat': '#mydiv',
'replaceWith': 'button',
'text': 'this is a button',
'eventHandlers': null
};
Object.keys(opts).forEach(
key => settings[key] = opts[key]
);
let targets = Array.from(document.querySelectorAll(settings.replaceWhat)),
newElem = document.createElement(settings.replaceWith),
clone;
newElem.textContent = settings.text;
targets.forEach(
target => {
clone = newElem.cloneNode(true, true);
if (settings.eventHandlers) {
Object.keys(settings.eventHandlers).forEach(
eventType => clone.addEventListener(eventType, settings.eventHandlers[eventType]);
)
}
target.parentNode.replaceChild(clone, target)
})
}
replaceElementWith({
'replaceWhat': '.mydiv',
'eventHandlers': {
'click': function(e) {
e.preventDefault();
document.location.hash = 'buttonClicked';
this.style.opacity = this.style.opacity == 0.5 ? 1 : 0.5;
},
'mouseenter': function(e) {
this.style.borderColor = '#f90';
},
'mouseleave': function(e) {
this.style.borderColor = 'limegreen';
}
}
});
div {
border: 2px solid #f90;
}
button {
border: 2px solid limegreen;
}
<div id='mydiv'></div>
JS Fiddle demo.
References:
Array.from().
Array.prototype.forEach().
Arrow Functions.
document.querySelectorAll().
EventTarget.addEventListener().
Node.cloneNode().
Node.replaceChild().
Object.keys().

How to get text value of same class in jquery

I have 10 records in my table. Each record having same class name. How can I alert the table data value(text) using jquery this.value while hover the data text.
Here is my code
<td>email1#domain.com</td>
<td>email2#domain.com</td>
<td>email3#domain.com</td>
<td>email4#domain.com</td>
<td>email5#domain.com</td>
<td>email6#domain.com</td>
<td>email7#domain.com</td>
<td>email8#domain.com</td>
<td>email9#domain.com</td>
<td>email10#domain.com</td>
Here is my script. I'm using webui api for iframe popover. For tables I have used datatables.
(function(){
var settings = {
trigger:'hover',
title:'Send Mail To User',
content:'',
multi:true,
closeable:false,
style:'',
cache:false,
delay:300,
padding:true,
backdrop:false,
};
$('a.show-pop-iframe').on('mouseenter',function () {
alert($(this).text());
settings.url='emailtype.php?id='+$(this).text();
function initPopover(){
var iframeSettings = {
placement:'auto', //values: auto,top,right,bottom,left,top-right,top-left,bottom-right,bottom-left,auto-top,auto-right,auto-bottom,auto-left,horizontal,vertical
container: document.body, // The container in which the popover will be added (i.e. The parent scrolling area). May be a jquery object, a selector string or a HTML element. See https://jsfiddle.net/1x21rj9e/1/
width:'auto', //can be set with number
height:'auto', //can be set with number
closeable:true,
padding:false,
type:'iframe',
url:settings.url
};
$('a.show-pop-iframe').webuiPopover('destroy').webuiPopover($.extend({},settings,iframeSettings));
}
initPopover();
});
})();
If you have class 'hover-cust' then
$('.hover-cust').on("mouseenter", function() {
alert($(this).text());
});
If you want to alert on td then
$('td').on("mouseenter", function() {
var link = $(this).find(".hover-cust");
if(link && link.length > 0) {
alert($(link).text());
}
});
$(".hover-cust").hover(function(){
alert($(this).text());
});
table, tr, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>email1#domain.com</td>
<td>email2#domain.com</td>
<td>email3#domain.com</td>
<td>email4#domain.com</td>
<td>email5#domain.com</td>
<td>email6#domain.com</td>
<td>email7#domain.com</td>
<td>email8#domain.com</td>
<td>email9#domain.com</td>
<td>email10#domain.com</td>
</tr>
</table>
Adding many event listeners on a group of similar nodes is considered a bad practice.
const table = document.querySelector('#your_table_id');
table.addEventListener('mouseover', function(event) {
const target = event.target;
const tag = target.tagName;
const parentTag = target.parentNode.tagName;
if(tag !== 'a' || parentTag !== 'td') {
return; // not my target, leave the function
}
alert(target.textContent);
});

jQuery Tree issue - add first child li

I have 2 columns, on the left side a team with users, on the right column, will be displayed the users i have selected. so everything its working but i'm trying to implement a new feature as follow:
I have 2 list level like a tree (only 2 levels). When i click on a user, i'm able to select it sending to the right column. Also, when i click (single click) on the first level (team name), the second level (users) appear as toggle jquery function. i need so, when i double click on a team (level 1) all users on that tree turns selected and go to column on the right side.
Also, when i click on the team (first level) on the right side, all the users get removed back.
My code to add the users jquery current is:
$(document).ready(function () {
var maxAllowed = 10000;
var $selectTable = $("#mytable");
var $selectList = $("#selected_users ul")
$("#max-count").html(maxAllowed);
var getActivated = function () {
var activated = new Array();
$selectTable.find('input[type="checkbox"]:checked').closest("li").each(function () {
var $obj = new Object;
var currentBox = $(this).find('input[type="checkbox"]');
$obj.id = currentBox.val();
$obj.boxid = currentBox.attr("id");
$obj.name = $(this).find("label").text();
activated.push($obj);
});
return activated;
}
var updateActiveList = function () {
// Truncate list
$selectList.html("");
$(getActivated()).each(function () {
$selectList.append("<li><a href='#' class='remove' data-id='" + this.id + "' data-box-id='" + this.boxid + "'>" + this.name + "</li></a>");
});
}
var countActivated = function () {
return getActivated().length;
}
$('#view').click(function () {
allIds = new Array();
getActivated().each(function () {
allIds.push($(this).attr("id"));
});
alert(allIds);
});
$selectList.on("click", "a.remove", function () {
$('#' + $(this).data("box-id")).prop("checked", false);
updateActiveList();
});
$selectTable.on("change", 'input[type="checkbox"]', function (event) {
if ($(this).is(":checked") && countActivated() > maxAllowed) {
event.preventDefault();
console.log("max reached!");
$(this).prop("checked", false);
}
updateActiveList();
});
});
Here's a jsFiddle with working example:
http://jsfiddle.net/muzkle/LMbV3/7/
Thanks all!
EDIT
Hi, i just added a code to separate single click from double click. So when the user single click, will open the tree. now i need when the user double click on the first level, add both (first level and they're childrens to the right side.
Follow code for single and double clicks:
alreadyclicked=false;
$(document).ready(function () {
$('#mytable').on('click', '.toggle', function (ul) {
//Gets all <tr>'s of greater depth
//below element in the table
var findChildren = function (ul) {
var depth = ul.data('depth');
return ul.nextUntil($('ul').filter(function () {
return $(this).data('depth') <= depth;
}));
};
var el = $(this);
var ul = el.closest('ul'); //Get <tr> parent of toggle button
var children = findChildren(ul);
var el=$(this);
if (alreadyclicked){
alreadyclicked=false; // reset
clearTimeout(alreadyclickedTimeout); // prevent this from happening
}else{
alreadyclicked=true;
alreadyclickedTimeout=setTimeout(function(){
alreadyclicked=false; // reset when it happens
//Remove already collapsed nodes from children so that we don't
//make them visible.
//(Confused? Remove this code and close Item 2, close Item 1
//then open Item 1 again, then you will understand)
var subnodes = children.filter('.expand');
subnodes.each(function () {
var subnode = $(this);
var subnodeChildren = findChildren(subnode);
children = children.not(subnodeChildren);
});
//Change icon and hide/show children
if (ul.hasClass('collapse')) {
ul.removeClass('collapse').addClass('expand');
children.hide();
} else {
ul.removeClass('expand').addClass('collapse');
children.show();
}
return children;
// do what needs to happen on single click.
// use el instead of $(this) because $(this) is
// no longer the element
},300); // <-- dblclick tolerance here
}
return false;
});
});
And new jsFiddle is: http://jsfiddle.net/muzkle/LMbV3/8/
To distinguish different groups I am wrapping each group/section in a wrapper div with class .wrapper
<div class="wrapper">
.
.
</div>
Also I attached a double click event to .wrapper and currently I have made it to alert its inner labels.Just write some additional code to add these labels to the right side like you are currently adding one element on click.Below is the code with jQuery .dblclick() function which attaches a double-click event to .wrapper.
$('.wrapper').dblclick(function(){
$(this).find('label').each(function(){
alert($(this).text());
});
});
Check this fiddle

Drop down box selectedIndex property

$.fn.fillSelect = function (data) {
return this.clearSelect().each(function () {
if (this.tagName == 'SELECT') {
var dropdownList = this;
$.each(data, function (index, optionData) {
var option = new Option(optionData.Text, optionData.Value);
if ($.browser.msie) {
dropdownList.add(option);
} else {
dropdownList.add(option, null);
}
});
// code for access "selectedindex"
}
});
};
Above is the code snippet for dynamically generating a drop down using jQuery.
I need to set selectedIndex property value dynamically for the purpose of showing the saved value earlier. I am going to insert that code into // code for access "selectedindex" place inside above code. So how can I set selectedIndex property for the dropdownList?
You should be able to set the selectedIndex property the same as any other.
Assuming that dropdownList is a HTMLSelectElement, dropdownList.selectedIndex = 5;, should work.
I'd do this in this bit of the code:
$.each(data, function (index, optionData) {
var option = new Option(optionData.Text, optionData.Value);
if (/* code to determine if this is the chosen one */) {
option.setAttribute("selected", "selected");
}
if ($.browser.msie) { /* etc */
You're setting the selected attribute on the relevant option.

Categories

Resources