I am trying to get the text and URL of a div when a user clicks in it. I am going to pass off the data to a PHP so that I can create a page that shows some other information.
<div class="superman">
<h3>Text</h3>
<h2>Info</h2>
<h4 class="partnum">PN123456</h4>
<h4 class="model">Product 456</h4>
<img src="http://company.com/456.jpg" id="thumb">
</div>
<div class="superman">
<h3>Text</h3>
<h2>Info</h2>
<h4 class="partnum">PN234567</h4>
<h4 class="model">Product 123</h4>
<img src="http://company.com/123.jpg" id="thumb">
</div>
I need to grab the part number, model, and the image URL for each div (class=superman). I have been successful at getting the part number and model, but things fall apart when I try to grab the image URL within the same function. When I can get the image URL, I am not able to retrieve the part number and/or model.
As an example, I've used this to grab the URL (I append as sort of an alert).
$('img').click(function() {
$(this).parent().append($(this).attr('src'));
});
I've also tried the getElementById constructions, but those only grab the info in the very first div; if someone clicks on a div further down the page, it still only grabs the first one. I am working on about 5,000 divs, so I don't know if assigning an ID to each div makes sense. I also tried some sort of the (this) construction, but I am too much of a rookie to get things going.
I've seen some questions with answers that approach what I want to do, but, like I said, it's either the part number and/or model, or the URL, but never both. Thanks in advance for the help.
If you're having a hard time getting the partnum or model associated with an image, you can retrieve the sibling elements with jQuery's siblings() method.
Then, for example, you can concatenate the values and display them.
$('img').click(function() {
var img = $(this);
var partnum = img.siblings('.partnum').text();
var model = img.siblings('.partnum').text();
var url = img.attr('src');
var text = 'partnum: ' + partnum + '<br>' +
'model: ' + model + '<br>' +
'url: ' + url + '<br>';
img.closest('.superman').append(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="superman">
<h3>Text</h3>
<h2>Info</h2>
<h4 class="partnum">PN123456</h4>
<h4 class="model">Product 456</h4>
<img src="http://company.com/456.jpg" id="thumb">
</div>
<div class="superman">
<h3>Text</h3>
<h2>Info</h2>
<h4 class="partnum">PN234567</h4>
<h4 class="model">Product 123</h4>
<img src="http://company.com/123.jpg" id="thumb">
</div>
To make the entire div clickable, just change the event handler's selector and use the div as the context of all of the selectors within its function:
$(function() {
$('.superman').click(function() {
var superman = $(this);
var partnum = $('.partnum', superman).text();
var model = $('.model', superman).text();
var url = $('img', superman).attr('src');
var text = 'partnum: ' + partnum + '<br>' +
'model: ' + model + '<br>' +
'url: ' + url + '<br>';
superman.append(text);
});
});
Related
So basically I have some elements with some data-values in a file . I want to dynamically create links to them using those data-values to type the text, href etc.
For example, I have two divs, id'ed firstand second. They have importance values, respectively "most important" and "least important".
I want to create two links to them, with the phrase "This is a link to the most/least important div" using JavaScript/jQuery. Below is a non-working example.
File a.html (ommiting headings and such, ofc):
<div id='first' data-importance='most important'>This is the first div.</div>
<div id='second' data-importance='least important'>This is the second div.</div>
File b.html:
<p><a class='makelink' data-linkto='first'></a></p>
<p><a class='makelink' data-linkto='second'></a></p>
$(`.makelink`).each( function(){
var target = $(this).data('linkto');
$(this).attr('href','b.html#' + target);
var imp = $('b.html #' + target).data('importance');
$(this).html('Link to the ' + imp + ' div');
});
However nothing happens. Any help is appreciated.
Your code seems correct except the selector should be inside quote and the string generated in the html() is not properly formatted:
$('.makelink').each( function(){ // Enclosed the selector with single/double qoute
var target = $(this).data('linkto');
$(this).attr('href','#' + target);
var imp = $('#' + target).data('importance');
$(this).html('Link to the '+ imp + ' div'); // concatenate the string with the variable using +
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='first' data-importance='most important'>This is the first div.</div>
<div id='second' data-importance='least important'>This is the second div.</div>
<p><a class='makelink' data-linkto='first'></a></p>
<p><a class='makelink' data-linkto='second'></a></p>
I am trying to edit the div's text, but when i use my function to update the rowcount, everytime the text vanihes completely. Would by nice if you could also explain why.
Thanks in advance.
My update function:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + String(rowCountF) + ")";
var vtext = "Teilnehmer (" + String(rowCountV) + ")";
$("#divf").html(ftext);
$("#divv").html(vtext);
My div layer:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
Code for divf:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
You are actually replacing the contents of the div itself with your text. This means the heading disappears and there is only plain text.
Probably you wanted to replace the heading contents:
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
This will select the h2 elements inside the divs and hence will update only the text inside the headings.
The result will look like the following:
<div id="divf"class="tableheader"> <h2>Teilnehmer (987)</h2> </div>
<div id="divf"class="tableheader"> <h2>Teilnehmer (123)</h2> </div>
.html() sets the HTML, meaning it replaces anything that's currently there. If you want to add to the HTML, you'll need to set the HTML to what's already there plus what you're adding, like so:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + rowCountF + ")";
var vtext = "Teilnehmer (" + rowCountV + ")";
//Get already-existing HTML
var divfHtml = $("#divf").html();
var divvHtml = $("#divv").html();
//Set the new HTML to the existing + the new text
$("#divf").html(divfHtml + ftext);
$("#divv").html(divvHtml + vtext);
If you only want to replace the heading, then just target the <h2> as Martin Zikmund suggested in his answer.
You need to reference the h2 for the div. using .html() will replace ALL of the html inside the #divf which in this case means it will replace the h2
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
Example: https://jsfiddle.net/qhef0toc/3/
I have an array of objects(each that are made up of image link and link). As I access each of them I would like to make a new div each time and add a different image link and link.
<div class="igo_product"
<a href>
link1
<img class="igo_product_image" src="imglink1">
</div>
<div class="igo_product"
<a href>
link2
<img class="igo_product_image" src="imglink2">
</div>
<div class="igo_product"
<a href>
link3
<img class="igo_product_image" src="imglink3">
</div>
Currently the only way I can place different images and links is by creating different class names by concatenating indexes at the end each time.
$.each(items, function (index, value) {
$(".igo_boxbody").append('<div class="igo_product' + index + '"<a><img class="igo_product_image' + index + '"></a></div>')
$(".igo_product" + index + "a").attr('href', value["link"].toString());
$(".igo_product_image" + index).attr('src', value["image_link"] );
});
However, $(".igo_product" + index + "a").attr('href', value["link"].toString()); does not correctly set my href...I'm assuming it's my way I'm concatenating the class, index, and a but I'm slightly stuck on what else I can do. Also, is there a better way to do this? I would rather keep the class name the same so that I can apply styles to all these classes easier.
How about this:
$.each(items, function (index, value) {
$(".igo_boxbody").append('<div class="igo_product"<a href="'+value["link"].toString()+'"><img class="igo_product_image" src="'+value["image_link"]+'"></div>');
});
There is an error:
$(".igo_boxbody").append('<div class="igo_product' + index + '"<a><img class="igo_product_image' + index + '"></a></div>')
//-----------------------------------------------------------^---no closing of div >
so change to this:
$(".igo_boxbody").append('<div class="igo_product' + index + '"><a><img class="igo_product_image' + index + '"></a></div>')
Should go for this:
$.each(items, function (index, value) {
var el = '<div class="igo_product"' + index
+ '><a href="'+value["link"]
+'"><img class="igo_product_image' + index
+ '" src="'+value["image_link"]+'"></a></div>'
$(".igo_boxbody").append(el);
});
By no means I intend to imply the following is better, but just to mention the option: you can use jquery to create html objects outside the DOM (e.g. $('<div>') creates a new div) and set their properties/attributes/classes/etc through those objects (also before adding them to the DOM).
The advantage is that you don't have to delve into the strings to catch those closing tags:
$('.igo_boxbody').append(items.map(function(value, index){
return $('<div>').addClass('igo_product').append(
$('<a>').attr('href', value.link).append(
$('<img>').attr('src', value.image_link).addClass('igo_product_image' + index)
)
);
}));
Fiddle
I have the following xml file with the controls information to render into HTML page.
The contents are like:
<control type="panel">
<panel id="p1">
<button id="b1">
<value>TEST</value>
</button>
<textbox id="t1">
<text>HELLO</text>
</textbox>
</panel>
<control>
This has to rendered on the fly into a div with a panel containing one button and one textbox.The contents of xml are known only at runtime.It can be anything like only a button or a dropdown list information.How would one go about approaching this problem.A generic algorithm(probably using jquery) would be really helpful.
For something generic, your XML would need to be generic or conformant to a convention along the lines of "XML to HTML form convention". I know of no such thing. :)
It seems easy enough to handle. Here's an example of how I'm handling your XML example.
$(function() {
// Data setup (I assume you'd be getting this from AJAX)
var xml = '<control type="panel">' +
'<panel id="p1">' +
'<button id="b1">' +
'<value>TEST</value>' +
'</button>' +
'<textbox id="t1">' +
'<text>HELLO</text>' +
'</textbox>' +
'</panel>' +
'</control>';
// Convert to jQuery XML object
var xml = $($.parseXML(xml));
// Set parent
var parent = $('#control');
// Handle elements
xml.find('panel').children().each(function() {
var tag = $(this)[0].tagName;
switch (tag) {
case 'button':
parent.append('<button id="' +
$(this).attr('id') + '">' +
$(this).find('value').text() +
'</button>');
break;
case 'textbox':
parent.append('<input type="text" id="' +
$(this).attr('id') +
'" value="' +
$(this).find('text').text() +
'" />');
break;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="control"></div>
Of course, you could modify this as necessary, add new element handling, change the way it's added to the parent, etc. etc. I hope it helps.
I need that the below code persist to exist in page reload, Ok.
<br/>
<div style="font-size: 8pt;float: left;width:100%;margin-left: 15px;margin-top:5px;">
some text here
</div>
<div style="width: 100%; height: 40px;">
<div class="flechaDestinatario"/>
<div class="textoDestinatario">
more text here
</div>
</div>
I need to add dynamically in javascript some more elements, but you can consider it as example.
I put the elements of code above in a parent div, the div parent id is 'chatUsuario' and the javascript var name is 'mensagem', anyway,
var mensagem = document.getElementById('chatUsuario');
if (mensagem != null) {
$(mensagem)
.append(
'<br/> <div style="font-size: 8pt;float: left;width:100%;margin- left: 15px;margin-top:5px;">'
+ args.dataHora
+ '</div>'
+ '<div style="width: 100%; height: 40px;">'
+ '<div class="flechaDestinatario"/>'
+ '<div class="textoDestinatario">'
+ args.mensagemRetorno
+ '</div>'
+ '</div>');
}
I try many things, but nothing with success, for example:
localStorage.setItem('mensagensBackup',JSON.stringify(mensagem));
$(window).load(function() {
var mensagensBackup = localStorage.getItem('mensagensBackup');
if(mensagensBackup!=null)
{
var retrievedObject = JSON.parse(mensagensBackup);
document.getElementById('chatUsuarioContainer').innerHTML=retrievedObject;
}
});
I try too jStorage.js, without success again.
Both cases I have the same error: "converting circular structure to json"
I really try, but I can't solve this error
Any another solution? have a workaround solution? something that I can do?
Thanks so much ;)
PS: I using JSF 2.2 and Prime 5
You can't stringify a DOM element object directly because it contains a circular reference to itself (as the error message says). On the other hand you don't even want to do that because you're interested only in its HTML content anyway. So change the code to
localStorage.setItem( 'mensagensBackup', mensagem.innerHTML );
and later remove the JSON.parse() line which is unnecessary now.
(As a side note, most of the time it's more reasonable to save some sort of abstraction of the data instead of the entire HTML, but that's another discussion.)
you can store html sub tree in localStorage and restore in after reload
localStorage.setItem('mensagensBackup',mensagem.innerHTML));
$(function() {
var mensagensBackup = localStorage.getItem('mensagensBackup');
if(mensagensBackup)
document.getElementById('chatUsuarioContainer').innerHTML = mensagensBackup;
}
});