How to get text value of same class in jquery - javascript

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);
});

Related

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().

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

jquery - adding new element attribute

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', '...');

Add multiple items to text-area with duplicate items

Add multiple items to text-area with duplicate items.
I have one text-area which store data after clicked add data link.
How can i prevent add duplicate items to text-area?
JavaScript call DOM event:
var Dom = {
get: function(el) {
if (typeof el === 'string') {
return document.getElementById(el);
} else {
return el;
}
},
add: function(el, dest) {
var el = this.get(el);
var dest = this.get(dest);
dest.appendChild(el);
},
remove: function(el) {
var el = this.get(el);
el.parentNode.removeChild(el);
}
};
var Event = {
add: function() {
if (window.addEventListener) {
return function(el, type, fn) {
Dom.get(el).addEventListener(type, fn, false);
};
} else if (window.attachEvent) {
return function(el, type, fn) {
var f = function() {
fn.call(Dom.get(el), window.event);
};
Dom.get(el).attachEvent('on' + type, f);
};
}
}()
};
JQuery add data to textarea:
$("#lkaddlanguage").click(function(){
var totalstring;
var checkconstring = $("#contentlng").text();
var strLen = checkconstring.length;
myStr = checkconstring.slice(0,strLen-1);
//alert(myStr);
var checkedItemsArray = myStr.split(";");
var j = 0;
var checkdup=0;
totalstring=escape($("#textval").val()) ;
var i = 0;
var el = document.createElement('b');
el.innerHTML = totalstring +";";
Dom.add(el, 'txtdisplayval');
Event.add(el, 'click', function(e) {
Dom.remove(this);
});
});
HTML Display data
<input type="textbox" id="textval">
<a href="#lnk" id="lkaddlanguage" >Add Data</a>
<textarea readonly id="txtdisplayval" ></textarea>
This seems a very straightforward requirement to me, so I'm not quite clear where you're getting stuck. I have not tried too hard to figure out your existing code given that you are referencing elements not shown in your html ("contentlng"). Also, mixing your own DOM code with jQuery seems a bit pointless. You don't need jQuery at all, but having chosen to include it why then deliberate not use it?
Anyway, the following short function will keep a list of current items (using a JS object) and check each new item against that list. Double-clicking an item will remove it. I've put this in a document ready, but you can manage that as you see fit:
<script>
$(document).ready(function() {
var items = {};
$("#lkaddlanguage").click(function(){
var currentItem = $("#textval").val();
if (currentItem === "") {
alert("Please enter a value.");
} else if (items[currentItem]) {
alert("Value already exists.");
} else {
items[currentItem] = true;
$("#txtdisplayval").append("<span>" + currentItem + "; </span>");
}
// optionally set up for entry of next value:
$("#textval").val("").focus();
return false;
});
$("#txtdisplayval").on("dblclick", "span", function() {
delete items[this.innerHTML.split(";")[0]];
$(this).remove();
});
});
</script>
<input type="textbox" id="textval">
<a href="#lnk" id="lkaddlanguage" >Add Data</a><br>
<div id="txtdisplayval" ></div>
<style>
#txtdisplayval {
margin-top: 5px;
width : 200px;
height : 100px;
overflow-y : auto;
border : 1px solid black;
}
</style>
Note I'm using a div (styled to have a border and allow vertical scrolling) instead of a textarea.
As you can see I've coded it to display an alert for duplicate or empty items, but obviously you could remove that and just ignore duplicates (or substitute your own error handling). Also I thought it might be handy to clear the entry field and set focus back to it ready for entry of the next value, but of course you can remove that too.
Working demo: http://jsfiddle.net/LTsBR/1/
I'm confused.
The only variable that might have duplicates comes from:
var checkedItemsArray = myStr.split(";");
However, checkedItemsArray is not used for anything.
Incidentally, the escape method is deprecated in favour of encodeURIComopnent.
When setting the value of the textarea, do just that: assign to its value property, not to its innerHTML (it can't have markup inside it or any elements, only text nodes).
If you want to check that the members of checkedItemsArray are unique, and you don't mind if they are sorted, you can use a simple function like:
function unique(arr) {
arr.sort();
var i = arr.length;
while (i--) {
if (arr[i] == arr[i - 1]) {
arr.splice(i, 1);
}
}
return arr;
}
Orignal order can be maintained, but it's a bit more code.

jQuery events not firing

I'm creating a simple jQuery editor, nothing complicated, and just can't seem to find out why the events do not work. See code below.
var $editor = $('<div>').addClass('editor')
.insertBefore(this.$element)
.append(this.$element);
var $b = $('<div>').addClass('button-wrapper')
.appendTo($editor);
this.$element.css({height:this.opts.height,width:this.opts.width});
//Load up each button.
$.each(this.opts.buttons.split(' '), function(i, button)
{
//If its an empty string keep going.
if(button == '')return true;
//Generate a button.
$('<div>').data('buttonName', button)
.addClass(button.toLowerCase())
.click(clicked)
.hover(hover, hover)
.appendTo($b);
});
To go over it, simply, $element represents the textarea that I am using as the base element, $b represents the button wrapper, and $editor is the div to wrap around all of these things. When I append the buttons to $editor none of the events fire, however, when I append to document.body it works perfectly fine. For the record, the event clicked and hover are nothing special, just testers to see if the events are working.
I guess the issue is actually at all places you are using <div> but it should be just div
like below -
var $editor = $('div').addClass('editor')
.insertBefore(this.$element)
.append(this.$element);
I've rewritten your code a little bit, just to figure out what you're doing. This seems to work for me, unless I didn't understand what the problem is that you're describing. The buttons react to hover as well as click events. Aside from writing the things you're doing differently, there's no substantial change in the code.
I suppose there's a chance that Val was right in that there may be other elements overlaying your buttons. You haven't shown us your CSS, so it's hard to tell what's going on on your side.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
.bold, .italic, .underline{ width: 50px; height: 20px; background: green; margin: 10px; }
</style>
</head>
<body>
<textarea class="demo">
</textarea>
<script type="text/javascript">
jQuery(
function($)
{
(function($){
//Constructor to make a new editor.
function TEditor(element, opts)
{
//Load in the element.
this.$element = $(element);
this.opts = opts;
//Let the browser know the object is ready.
this.enabled = true;
}
//The actual editor class.
TEditor.prototype = {
display: function()
{
var
$editor = this.$element.wrap('<div class="editor" />').parent(),
$b = $('<div class="button-wrapper" />').appendTo($editor);
this.$element.css({height:this.opts.height,width:this.opts.width});
//Load up each button.
$.each(this.opts.buttons.split(' '), function(i, button)
{
//If its an empty string keep going.
if(button == '') return true;
//Generate a button.
$('<div class="' + button.toLowerCase() + '" />')
.data('buttonName', button)
.appendTo($b)
.click(clicked)
.hover(hover, hover);
});
},
enable: function()
{
this.enabled = true;
},
disable: function()
{
this.enabled = false;
},
validate: function()
{
if(!this.$element[0].parentNode)
{
this.destroy();
this.$element = null;
this.options = null;
}
}
}
//JQuery function extension.
$.fn.teditor = function(options)
{
options = $.extend({}, $.fn.teditor.defaults, options);
//On load create a new editor.
function get(ele)
{
var editor = $.data(ele, 'editor');
if(!editor)
{
editor = new TEditor(ele, options);
editor.display();
$.data(ele, 'editor', editor);
}
return editor;
}
//Initialize.
this.each(function(){get(this);})
return this;
};
$.fn.teditor.defaults = {
buttons: 'Bold Italic Underline',
height: '150px',
width: '500px'
};
function clicked(e)
{
alert(e);
}
function hover(e)
{
console.log('hover');
}
})(jQuery);
$('.demo').teditor();
}
);
</script>
</body>
</html>

Categories

Resources