I am trying to target an id element using a variable in jquery, like so:
var liked_artist = $('#js-helper-liked-artist').val();
var artist_id = $('#js-helper-artist-id').val();
var target = '#individual' + artist_id + '';
$(target).addClass('individual-heart-hover');
However, this is not targeting the id it should correctly. Any ideas? I've tried it without the empty string at the end as well.
EDIT:
HTML:
<i class="fa fa-heart fa-stack-1x individual-heart" id="individual-{{$artist->id}}"></i>
individual-{{$artist->id}} renders as individual-8
and artist_id is 8 (console.log shows this).
Shouldn't it be var target = '#individual-' + artist_id + '';? Unless it's a typo in your post, I think you are missing the dash.
did you enclose your code in the document ready function?
$(document).ready(function() {
// ....
});
Related
I have Bootstrap Table that contains an edit button on each row. I've used a data formatter to make the pass the id of the record over with a data attribute that can be extracted when clicked. When I inspect the element in the console I can see the ID is in the dataset property, but when I try to get it out using element.dataset the console contains an error telling me that the dataset is undefined. It's frustrating because I can see it's there!
Here's my click event:
$(".job-edit").click(function(event) {
var editModal = $("#jobEditModal");
var clicked = $(event.target);
var id = clicked.dataset.jobid;
console.log(id);
event.stopPropagation();
//editModal.modal();
});
And the formatter that sets the button up:
job.editFormatter = function (value) {
return "<button class='btn job-edit text-center' data-jobId='" + value + "'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Edit</button>";
}
So far I've tried replacing .dataset with .getAttribute(), but that didn't work either, I've also tried changing the casing of jobid to jobId, past that I'm not sure what could be causing the problem.
instead of using dataset you can directly get the jobid by using .data() method of jquery like below.you are getting undefined value for dataset as the clicked variable is a jquery object which does not have a definition for dataset
$(".job-edit").click(function(event) {
var editModal = $("#jobEditModal");
var id = $(this).data("jobid");
console.log(id);
event.stopPropagation();
//editModal.modal();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn job-edit text-center' data-jobId='2'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Edit</button>
Your issue is because clicked is a jQuery object which has no dataset property.
To fix this you need to use the native element reference:
var id = e.target.dataset.jobid;
Alternatively, use the data() method of the jQuery object:
var id = clicked.data('jobid');
Have such button on my page (for showing current total in shopping cart):
<div class="col s2 offset-s4 valign" id="shoppingCart">
<a class="waves-effect waves-teal btn-flat no-margin white-text right" th:inline="text"><i class="material-icons right">shopping_cart</i>[[#{${total}+' руб'}]]</a>
</div>
Written function for updating total number on that button:
function updateShoppingCart(newTotal) {
var $div = $("#shoppingCart");
var $a = $("<a class='waves-effect waves-teal btn-flat no-margin white-text right'></a>");
var $i = $("<i class='material-icons right'>shopping_cart</i>");
var $string = formatDecimal(newTotal,',','.') + " руб";
$a.append($i);
$a.append($string);
$div.children().remove();
$div.append($a);
}
But it does not work. Please help find bug or what I'm doing wrong.
It's a lot more efficient to set $div = $('#shoppingCart');; in the global scope and use that var instead. This way your JS won't search through your entire DOM every time the function is called.
Your stuff doesn't work because your vars are very odd. I believe what you want to achieve is this:
HTML
<a class="waves-effect waves-teal btn-flat no-margin white-text right" th:inline="text">
<i class="material-icons right">shopping_cart</i>
<span>[[#{${total}+' руб'}]]</span>
</a>
JS:
function updateShoppingCart(newTotal) {
var $div = $("#shoppingCart");
var $a = $("a", $div); //select the <a> within the shoppingcart div
var $i = $("i", $div); //select the <i> within the shoppingcart div
var $span = $("span", $div); //select the newly added span
var newPrice = formatDecimal(newTotal,',','.') + " руб";
$span.text(newPrice);
}
I kept the $a and $i in as examples, but I don't see a need for you to use them or completely replace them, since you only want to change the text. By using a span, you can target the price without replacing all the html.
On a sidenote, the $ is generally used to state a var is a jquery object. string is not a jquery object in this scenario, so the $ there is a bit odd.
On a sidenote, if you want to replace html within an element, you should try doing it like so:
function updateShoppingCart(newTotal) {
var $div = $("#shoppingCart");
var newPrice = formatDecimal(newTotal,',','.') + " руб";
//Create the new HTML as a string, not as an element
var newHtml= '<i>Shopping_cart</i>'+newPrice+'';
//empties div beforehand current html, no seperate removal needed.
//Then places the html string within the element
$div .html(newHtml);
}
See working JSFiddle here
In some part of an html page, I have a link with the following code :
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
I would like to automatically display the same link in another part of the same page by using a javascript.
What would be the script to insert in my page ?
Thank you in advance for any help in this matter.
Patrick
Try this:
myVar = document.getElementById("idname");
varLink = (myVar.attributes.href);
As son as you know the target id:
<div id="targetID">New Link: </div>
<div id="targetID2">New Link 2: </div>
And If you are using jQuery you can do like this:
var link = $("#idname").clone();
link.attr("id",link.attr("id") + (Math.random() * 10));
$("#targetID").append(link);
If not:
var link = document.getElementById("idname");
var newLink = document.createElement("a");
newLink.href = link.href;
newLink.className = link.className;
newLink.innerHTML = link.innerHTML;
newLink.id = link.id + (Math.random() * 10);
document.getElementById("targetID2").appendChild(newLink);
See this Example
<script>
window.onload = function() {
// get data from link we want to copy
var aHref = document.getElementById('idname').href;
var aText = document.getElementById('idname').innerHTML;
// create new link element with data above
var a = document.createElement('a');
a.innerHTML = aText;
a.href = aHref;
// paste our link to needed place
var placeToCopy = document.getElementById('anotherplace');
placeToCopy.appendChild(a);
}
</script>
Use code above, if you want just to copy your link to another place. JSFiddle
First, I want to point out that if you will just copy the element that will throw an error because the copied element will have the same id of the first one, so if you will create a copy of your element you don't have to give it the same id.
Try this code:
function copyLink(newDestination){
var dest=document.getElementById(newDestination);
var newLink=document.createElement("a");
var myLink=document.getElementsByClassName("classname")[0];
newLink.href=myLink.href;
newLink.className = myLink.className;
newLink.innerHTML = myLink.innerHTML;
newDestination.appendChild(newLink);
}
The newDestination parameter is the container element of the new Link.
For example if the new Container element has the id "div1":
window.onload = function() {
copyLink(div1);
}
Here's a DEMO.
Thank you very much to everyone for so many prompt replies.
Finally, I was able to use Jquery.
So, I tried the solution given by Andrew Lancaster.
In my page, I added the codes as follows, in this order :
1-
<span id="span1">
<a class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
and further down the page :
2-
<script type="text/javascript">
var span1val = $('#span1').html();
$('#span2').html(span1val);
</script>
Therefore, the two expected identical links are properly displayed.
But, unfortunately, I forgot to say something in my initial request:
the original link is in the bottom part of my page
I would like to have the duplicated link in a upper part of my page
So, would you know how to have the duplicated link above the original link ?
By the way, to solve the invalid markup mentioned by David, I just deleted id="idname" from the original link (that I could ignored or replaced by other means).
Thank you again in advance for any new reply.
Patrick
Using Jquery you could wrap your link in a span with an ID and then get the value of that ID and push it into another span id.
HTML
<span id="span1">
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
jQuery
var span1val = $('#span1').html();
$('#span2').html(span1val);
Example can be found here.
http://jsfiddle.net/3en2Lgmu/5/
<li class="catalog-list-item" data-icon="false">
<a href="/items/170893265">
How would I use console.log to log the href /items/IDHERE (IDHERE = 170893265) by using catalog-list-item?
$.get("http://m.roblox.com/Catalog/CatalogSearch?startRow=0&keyword=&filter=Collectibles",
function(Data) {
var test = $(Data).find('.catalog-list-item')
var itemID = test.attr("href");
console.log(itemID);
});
And that won't work for me (the test part does work, not the itemID part though.)
If
<li class="catalog-list-item" data-icon="false">
<a href="/items/170893265">
is the full response, then li.catalog-list-item will be the selected element in $(Data). I.e. $(Data).find('.catalog-list-item') would try to find a .catalog-list-item element inside a .catalog-list-item element, which doesn't work.
You can .filter the selection and then search for the a element(s):
var test = $(Data).filter('.catalog-list-item').find('a');
You left out the a tag, which is the one you're targeting -- the one that has the href attribute you're looking for:
var test = $(Data).find('a'); //<<<<-------
var itemID = test.attr("href");
console.log(itemID);
To get just the id use:
var itemID = test.attr("href").split('/').pop();
you realize the href attribute isn't in the li tag. I suggest you do this
var test = $(Data).find('.catalog-list-item')
var itemID = test.find('a').attr("href")
console.log(itemID)
I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product