I have about 1000 images and textareas with the same class name and a custom attribute. The classes names are emoticon and emoticonlist respectively. The custom attributes are emo-tag and emo-ascii respectively.
Each image has its partner (a textarea) with the exact same content in its custom attribute.
Example:
emo-tag = "f-x" // for images
emo-ascii = "f-x" // for textareas
where x represents a number from 0 to 999.
My script captures the images attributes and what I need with no problem. The problem starts when I try to get the value of the textarea which have the exact attribute content like the image.
Here is my code:
$(function(){
var json = [];
$('img').each(function(){
var emoimg = $(this).attr("src");
var emoalt = $(this).attr("alt");
var emotag = $(this).attr("emo-tag");
//Does not this supposed to capture the value of this specific textarea?
var emoascii= $('.emoticonlist').attr("emo-ascii",emotag).val();
json.push({
id : emotag,
name : emoalt,
img : emoimg,
content: emoascii
});
});
var s = JSON.stringify(json);
$("#content").after("<div>" + s + "</div>");
});
Like I said, the code works but the textarea captured and pushed into the array is just the first one and all the items of the array. How can I accomplish what I want?
Current Output:
[
{"id":"emo-0","name":"Smiley Face","img":"images/smiley-face.png","content":":)"},
{"id":"emo-1","name":"Big smile","img":"images/big-smile.png","content":":)"},
{"id":"emo-2","name":"Sad face","img":"images/sad-face.png","content":":)"},
...
...
...
]
Desired Output:
[
{"id":"emo-0","name":"Smiley Face","img":"images/smiley-face.png","content":":)"},
{"id":"emo-1","name":"Big smile","img":"images/big-smile.png","content":":D"},
{"id":"emo-2","name":"Sad face","img":"images/sad-face.png","content":":("},
...
...
...
]
Using $('.emoticonlist').attr("emo-ascii",emotag), you're setting the attribute instead of getting the element where the attribute is equal to emotag.(http://api.jquery.com/attr/)
Perhaps try replacing the line
var emoascii= $('.emoticonlist').attr("emo-ascii",emotag).val();
with
var emoascii= $('.emoticonlist[emo-ascii=' + emotag +']').val();
(https://api.jquery.com/attribute-equals-selector/)
Related
I'm quiet new above all on Javascript technology. I want to create various div according to the number of string into an array of checked checkboxes but after my code it only displays one div every time... I must go through a jquery dialog to display it !
My JSP
<div style="overflow: scroll;" id="listCurrentContact"></div>
My listContact.js
varPopup = $('#dialogMultiplesDeleteConfirmation').dialog({
resizable : false,
modal : true,
autoOpen : false,
width : 500,
open: function(){
var SuppressCheckboxItems = [];
// I put into an array the different value of checked checkboxes
$("input:checkbox[id=suppressCheckbox]:checked").each(function() {
SuppressCheckboxItems.push($(this).val());
});
var z = document.createElement('div');
// I suppress the ',' between each element
var test = SuppressCheckboxItems.toString();
var tab = test.split(",");
for(var i = 0; i < tab.length; i++){
z.innerHTML = tab[i];
$('#listCurrentContact').html(z);
}
Have you tried using .append instead of .html while concatenating your checkboxes to #listCurrentContact.
You can refer this document: https://www.w3schools.com/jquery/html_html.asp to see that .html() replaces the previous content with the new content whereas what you are trying to achieve here is appending the entire array of values to the div. Look at how .append() works in this link : https://www.javascripttutorial.net/javascript-dom/javascript-append/. Just to give you a brief overview, when you write a .append() on any element, it doesnot replace the previous content with the new content but instead attaches/concatenates the new content after the previous content.
You should use $('#listCurrentContact').append(z);
Thanks to SaloniMishra Ive found the good answer. It just needed to change the .html() to .append() but with that if the customer just quit the jquery dialog and retry the previous elements stayed in the div so you need to clean every elements before to relaunch the function with the function removeChild()! Thanks all !
open : function() {
var SuppressCheckboxItems = [];
const currentDiv = document.getElementById('listCurrentContact');
while (currentDiv.firstChild) {
currentDiv.removeChild(currentDiv.lastChild);
}
$("input:checkbox[id=suppressCheckbox]:checked").each(function() {
var z = document.createElement('div');
z.innerHTML = $(this).attr("name");
$("#listCurrentContact").append(z);
});
The problem
I have a div that has a list of image paths stored in a data attribute, like so:
<!-- Multiple background images stored in data-attr -->
<div class="banner" data-bg="http://placehold.it/350x150, http://placehold.it/350x250, http://placehold.it/350x350"></div>
I have written some Javascript that retrieves the data attribute and splits the URLs into an array:
function backgroundPhader(){
//get bg el
var bg_el = document.getElementsByClassName('banner')[0];
//make empty bg array
var bg_arr = [];
//console.log(bg_el);
//get data-attr of bgs
var bg_data = bg_el.getAttribute("data-bg");
//console.log(bg_data);
bg_arr = bg_data.split(",");
console.log(bg_arr);
}
backgroundPhader();
Where to next
What I now want to try do if it's not too complex with pure Javascript is to take each item in the array and apply it as an inline background-image - one at a time over a set period of time. I can't work out how to pull out a single item from the array and apply it as an inline style.
Help pointing me in the right direction would be great. I also have a fiddle if it helps.
setInterval will invoke the function after specified interval.
split will split string and return array using mentioned separator. One can use index of array to get the values of the array.
Try this:
function backgroundPhader() {
var bg_el = document.getElementsByClassName('banner')[0];
var bg_data = bg_el.getAttribute("data-bg");
var bg_arr = bg_data.split(",");
var val = 0;
var iterator = function() {
if (val > bg_arr.length - 1) {
val = 0;
}
document.body.style.backgroundImage = 'url(' + bg_arr[val] + ')';
++val;
};
iterator();
setInterval(iterator, 1000);
}
backgroundPhader();
<!-- Multiple background images stored in data-attr -->
<div class="banner" data-bg="http://placehold.it/350x150, http://placehold.it/350x250, http://placehold.it/350x350"></div>
I need to create a function that will add an attribute to elements that have an attribute with specific values.
$index have values 0-10, Code is working to this point: var element = $("a[data-slide-index*='"i"']");
Firebug gives me:
Blockquote
SyntaxError: missing ) after argument list
Rest looks like that:
<script type="text/javascript">
jQuery(document).ready(function($){
for(var i=0; i<parseInt(<?php echo json_encode($index); ?>);i++){
var hoverAtt = "onHover"+i+"()";
var element = $("a[data-slide-index*='"+ i +"']");
element.next().attr("onmouseover", function(){
return hoverAtt;
});
}
})
</script>
There is jFidle example for $index=6:
http://jsfiddle.net/Fuh9P/
Edit: I changed concatenation as Sjoerd suggested but still doesn't work.
The error message is because you concatenate strings the wrong way. You have this:
var element = $("a[data-slide-index*='"i"']");
Within the $() you try to concatenate three parts, like this:
"a"i"b"
Instead, you should use something like this:
"a" + i + "b"
var element = $("a[data-slide-index*='" + i + "']");
I have a string containing html code, something like this: http://jsbin.com/ocoteg/1.
I want to parse this string, make some changes (just for example: change all links to a span), and then get the modified html string back.
Here is a jsbin, where I started this, but I can't make it work: http://jsbin.com/okireb/1/edit.
I get the html string, I parse it with jquery, but I can't replace the links, and get the modified html string back.
UPDATE
Why the downvote? What is the problem with this question?
You can do it in a loop also
dom.each(function(i,v){
if(v.tagName == "A"){
dom[i] = $('<span/>').html($(v).html())[0]; // replace it right away with new span element
}
});
var newString = $('<div>').append(dom.clone()).html(); //<-- to get new string http://stackoverflow.com/a/652771/1385672
console.log(newString);
EDIT:
Here's how you can do it keeping the other tags
var dom = $(text.split('\n'));
$(dom).each(function(i,v){
var ele = $(v)[0];
if($(ele).is('a')){
dom[i] = $('<div>').append($('<span/>').html($(v).html())).html();
}
});
var newString = dom.get().join('\n');
http://jsbin.com/okireb/32/edit
Use find instead of filter :
var dom = $('<div>'+text+'</div>');
dom.find('a').each(function() {
var el = $(this);
var html = el.html();
var span = $('<span/>').html(html);
el.replaceWith(span);
});
console.log(dom.children());
Note that I wrap everything for the case where the initial dom isn't one element.
Demonstration
To get the html back as a string use
var html = dom.html();
This should be what you want (can be improved)
var text = '<!DOCTYPE html><html><head><meta charset=utf-8 /><title>JS Bin</title></head><body>Link 1Link 2Link 3</body></html>';
var body_content = text.substring(text.indexOf('<body>') + 6, text.indexOf('</body>'));
var $dom = $('<div/>').html(body_content);
$('a', $dom).each(function() {
$('<span>' + $(this).html() + '</span>').insertAfter($(this));
$(this).remove();
});
var text_new = text.replace(body_content, $dom.html());
// text_new contains the entire HTML document with the links changed into spans
You could do it with .replace.
Probably not the nicest way of doing it though.
dom = dom.replace(/<a /g,'<span');
dom = dom.replace(/<\/a>/g,'</span>');
Demo: http://jsbin.com/okireb/14/edit
I have an xml document (from a feed), which I'm extracting values from:
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = $(this).find("description").text();
Now inside "description" i need to get the img element, but this is causing me some problems. "descripttion" is a regular string element and it seems i can't call the ".find()" method on this, so what do i do?
I have tried calling .find():
var img = $(this).find("description").find("img");
But it's a no go. The img is wrapped in a span, but I can't get to this either. Any suggestions? I'd prefer to avoid substrings and regex solutions, but I'm at a loss.
I've also tried turning the "description" string into an xml object like so:
var parser = new DOMParser();
var desc = parser.parseFromString(test,'text/xml');
$(desc).find("img").each(function() {
alert("something here");
});
But that doesn't work either. It seems like it would, but I get a "document not well formed" error.
Try enclosing the contents of the description tag in a dummy div, that seemed to work better for me, and allowed jQuery's .find() to work as expected.
e.g.
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = '<div>' + $(this).find("description").text() + '</div>';
var image = $(description).find('img');
Hi and thanks for the prompt replies. I gave GregL the tick, as I'm sure his solution would have worked, as the principle is the same as what I ended up with. My solution looks like this:
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = $(this).find("description").text();
var thumbnail = "";
var temp_container = $("<div></div>");
temp_container.html(description);
thumbnail = temp_container.find("img:first").attr("src");
So wrap the string in a div, and then use "find()" to get the first img element. I now have the image source, which can be used as needed.
maybe you should try to convert the description text to html tag and then try to traverse it via jquery
$('<div/>').html($(this).find("description").text()).find('img')
note: not tested