Get data-value from element in another file with jQuery - javascript

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>

Related

Javascript - Getting the first character of my string - error

can you tell me why the console says that it is not a function?
var firstAuthorName = document.getElementById("firstAuthorName");
var firstCharacter = console.log(firstAuthorName.slice(0,1));
then I get the text by this:
div.innerHTML += firstCharacter.value + ", " + firstAuthorInitials.value + ", " + firstAuthorSurname.value + ". ";
So the console says: "Uncaught TypeError: firstAuthorName.slice is not a function"
You need to access the contents of the HTML element and get the first character of that. You are attempting to get the first letter from the HTML DOM object itself, not the content of the object.
There are 3 standard ways to extract content of an element and which
you use depends on the kind of element you have and the kind of
content it contains:
1a. value : If the element is a form-field (radio button, checkbox,
text box, etc.) value is always used to get the value being held
in form-field.
1b. value is also used to obtain the value of an HTML element's attribute as in:
var src = document.querySelector("img").attributes[0].value;
console.log("The value of the \"src\" attribute of the image is: " + src);
<img src="images/someImage.jpg">
For non-form field elements, you can use textContent or innerHTML.
textContent just gets the characters that are the contents of an element (minus any HTML). If the element only contains
human consumable text, this is most-likely what you'll want.
innerHTML gets the content of the element, including any HTML CONTENT. Use this when the element in question contains HTML content
that you want as HTML, rather than text. While using innerHTML
instead of textContent works, it is a slightly more expensive
operation to perform because you are asking the HTML parser to parse
the contents, so don't use innerHTML on non-HTML content.
Here's a sample of all 3 of the above used correctly:
window.addEventListener("DOMContentLoaded", function(){
document.querySelector("button").addEventListener("click", function(){
var input = document.getElementById("txtTest");
var parent = document.getElementById("parent");
// textContent will get the text characters as they are:
var textOnly = console.log("textContent of parent div is: " + parent.textContent);
// innerHTML will get the content of the element but will parse its HTML:
var htmlContent = console.log("innerHTML of parent div is: " + parent.innerHTML);
// value is ONLY for form-field elements:
console.log("The value of the div is: " + parent.value); // undefined
console.log("The value of the textbox is: " + input.value);
});
});
<input id="txtTest" type="text" placeholder="type in me and then click the button">
<div id="parent">
<p>Nested child HTML</p>
</div>
<button>Click me to get results</button>
So, if your scenario is that the content is in, say a textbox, your solution would be to use value, like this:
var firstAuthorName = document.getElementById("firstAuthorName");
var button = document.querySelector("button");
button.addEventListener("click", function(){
console.log("The first character in the textbox is: " + firstAuthorName.value.slice(0,1));
});
<input id="firstAuthorName" type="text" placeholder="type in me and then click the button">
<button>Click Me</button>

jQuery .html() function removing text

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/

Get text/URL inside a DIV

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

Select the Element based on dynamicID using JQuery

I am a newbie to Jquery and trying to do the following.
I have an ID of an element which is generated by concatenation of a variable string. I need to select that element with this generated ID using JQuery. Please see below for more info..
Lets say I have elements with IDs as follows in a html Page
ID1=Test_A_element
ID2=Test_B_element
ID3=Test_C_element
ID4=Test_D_element
I have a string variable (x) that contains A or B or C or D. I will generate the ID of this element by simple concatenation as follows
ID="Test_"+x+"_element";
I need to select the correct Element using Jquery.
Using jQuery:
var jQuerySet = $("#" + ID);
Using the DOM:
var elem = document.getElementById(ID);
Live Example:
var ID =
"Test_" +
String.fromCharCode(65 + Math.floor((Math.random() * 4))) +
"_Element";
$("<p>").html("The ID is " + ID).appendTo(document.body);
$("#" + ID).css("color", "blue");
<div id="Test_A_Element">Test A</div>
<div id="Test_B_Element">Test B</div>
<div id="Test_C_Element">Test C</div>
<div id="Test_D_Element">Test D</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Check this page for more details about jQuery selectors: http://www.w3schools.com/jquery/jquery_ref_selectors.asp.
Or the more detailed official page: https://api.jquery.com/category/selectors/.
In your particular case, you can select an element by id with the following construction: jQuery("#"+ID), or $("#"+ID).

Set the content of Bootstrap tooltip via Javascript

I have included tooltips in my table's cells. Here is how I did it:
<td data-container="body" data-toggle="tooltip" data-html="true" data-original-title="10.5">10.5</td>
<script type="text/javascript">
$(document).ready(function(){
$(".table td").tooltip();
});
</script>
Until here, I don't have a problem. Now, I want to change the way it works. I have two dictionaries from numeric to text translations.
dic1 = {'0':'zero','1':'one','2':'two','3':'three'....}
dic2 = {'0.25':'a quarter','0.5':'half',....}
Numbers in the table are standards, so there isn't something that I don't have in dictionaries.
I want to change the title of the tooltips to this: one half (1.5) instead of 1.5. Splitting the number and take the text from one dictionary and the text from the other and then combine them.
Adding just the tooltip was easy, but now I think that I am stacked.
I haven't tested it, but something like this should work.
$('.table td').each(function () {
var title = $(this).attr('data-original-title').split('.');
$(this).attr('data-original-title', dic1[title[0]] + ' ' +
dic2['0.' + title[1]] + ' (' + title[0] + '.' + title[1] + ')');
});

Categories