Nesting in javascript - javascript

I don't know if that title even describes what I want to do, but here goes.
I have some JavaScript, which changes the href of a link, depending on what item is selected in a select box. Here's the code:
function setText(text) {
var selectVal = text;
var url = $('twitter2').attr("href");
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('a').attr("href", url);
}
The problem is there are multiple links on the page. Would there be a way to specify which link to change the URL of? Sorry for the woeful explanation, here's the accompanying html.
<twitter2><a><img src="http://stream.cz.cc/images/twitter.png" onmouseover="this.src='http://stream.cz.cc/images/twitterover.png'" onmouseout="this.src='http://stream.cz.cc/images/twitter.png'" /></a></twitter2>
Any advice?

Add an id to your image tag and JQuery select it by the ID.
<img id="THISONE" src="http://stream.cz.cc/images/twitter.png" onmouseover="this.src='http://stream.cz.cc/images/twitterover.png'" onmouseout="this.src='http://stream.cz.cc/images/twitter.png'" /></a>
Javascript:
function setText(text) {
var selectVal = text;
var url = $('twitter2').attr("href");
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#THISONE').attr("href", url);
}

first of all
var url = $('twitter2').attr("href") would give you nothing, as twitter2 does not have any href attribute.
second, you can access your a as:
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('twitter2 a').first().attr("href", url).
This will change the href of the first a inside the <twitter2> tag

Related

Javascript url content with parameter?

I wish to pass 'selectlang' parameter in javascript and redirect to the MVC controller but the var 'selectlang' have error and mention that it does not exist in current content? Please guide me thanks!
My javascript:
$('.filterlang').on("click", function () {
var selectlang = document.getElementById("Language").value;
location.href = '#Url.Content("~/SURV_Main/SURV_Main_Details/?key=" + Model.Survey_Key +"&Language=" + selectlang)';
});
filterlang is button class and "Language" is dropdownlist id.
Have you tried this:
$(document).on(".filterLang", "click", function(){
var selectedLang = $("#Language").val(); // if it is normal dropdown, this will work for both cases
var selected2Lang = $("#Language").select2("val"); // if it is select2 dropdown
window.location = '#Url.Content("~/SURV_Main/SURV_Main_Details/?key=" + Model.Survey_Key +"&Language=' + selectlang + '")';
});
Hope this helps.

GET request iframe

<div id="result"></div>
<button id="send">Request</button>
JavaScript:
var button = document.getElementById("send"),
div = document.getElementById('result');
button.addEventListener('click', function() {
var result = createIframe("f", "/lorem.txt");
console.log(result.contentWindow);
div.innerHTML = result.contentWindow.document.body.innerHTML;
});
function createIframe(name, src, debug) {
var tmpElem = document.createElement('div');
tmpElem.innerHTML = '<iframe name="' + name + '" id="' + name + '" src="' + src + '">';
var iframe = tmpElem.firstChild;
iframe.style.display = 'none';
document.body.appendChild(iframe);
return iframe;
}
I have on the local server is a file lorem.txt. With hidden frame I am trying to query the contents of this file and paste it into <div id="result"></div>. But for some reason it does not is inserted. What could be the problem?
I believe elements with the ids of "send" and "result", respectively do not exist at the moment when your javascript code is running, therefore the click event will not be attached to the button. You need to make sure that these elements exist when you try to get them by their ids or attach events to them.
Solution: Either make sure your code is running after the document has been loaded or put your relevant script tag below the html you have described in your question.

Jquery Javascript best way to check elements done appending

I have a list of elements that are dynamically appended after an Ajax call. I am using a plugin that creates a lightbox click event for the anchors dynamically appended. It works fine except sometimes it says that the title is undefined. I realize this is because the plugin gets initiated before the title attribute is completely done appending to the DOM. I know of several ways to do this, but what is the BEST way to check that all these elements are completely appended?
Ajax call is already made and data parsed with this function (colorbox title is the one that evaluates to 'undefined' for only some):
function pageImages(images,_q){
for(var i = 0; i < images.count; i++){
$('#pageImages').append('<div class="pageImageItem"><a href="' + images.data[i]._clickurl + '" title= "' + images.data[i]._title + '">\
<img src="' + images.data[i]._thumbnailUrl + '" alt= "' + images.data[i]._title + '"/>\
</a><div class="hoverInfo"><h2>' + images.data[i]._title + '</h2><p>' + limitCharacters(images.data[i]._clickurl,40) + '</p></div></div>');
}
$(".pageImageItem a").colorbox({maxWidth:'95%', maxHeight:'95%', title: function(){
var url = $(this).attr('href'),
title = $(this).attr('title');
console.log(title);
return '<h2>' + title + '</h2>' + limitCharacters(url,40) + '';
}});
}
And here is a picture of what is happening (anchor highlighted is the element that clearly has a title attribute but is showing undefined in lightbox):
You can wrap the jQuery element find block in a timeout without timevalue. The timeout will wait for all javascript to be finished with all processes. Example:
window.setTimeout(function() {
$(".pageImageItem a").colorbox({maxWidth:'95%', maxHeight:'95%', title: function(){
var url = $(this).attr('href'),
title = $(this).attr('title');
console.log(title);
return '<h2>' + title + '</h2>' + limitCharacters(url,40) + '';
}});
});

How do I display an image from a URL using a Variable to create the URL

I am wishing to include an image in a page that will change each day.
My variable string calculation works (can display the url using but am having problems working out how to put the variable as the url this is what I have so far:
<script>
var tD = new Date();
var datestr = "http://www.fakeurl.com/" + (tD.getMonth()+1) + "/" + tD.getDate() + ".jpg";
document.getElementById("+datestr+")
img src='"+ datestr +"' style="border: 0px;" /
</script>
What do I need to do different to get it to actually display my image?
I am a newby please help.
First of all you need to make sure that the script will run after the IMG element has been loaded.
In order to insure this you need to use jQuery.
$(document).ready(myOnloadFunc);
or to use
<body onload="myOnloadFunc()">
While the JavaScript function myOnloadFunc() will include your original code.
There is a mistake in the original code you posted, please see my corrections.
var tD = new Date();
var datestr = "http://www.fakeurl.com/" + (tD.getMonth()+1) + "/" + tD.getDate() + ".jpg";
var imgElement = document.getElementById("imgElementID");
imgElement.src = datestr;
imgElement.style = "border: 0px;" ;
I think you mixed up the variable "datestr" with the IMG element.
<script>
function myFunction()
{
var tD = new Date();
var datestr = "http://www.fakeurl.com/" + (tD.getMonth()+1) + "/" + tD.getDate() + ".jpg";
alert(datestr);
document.getElementById("datestr").src = datestr;
}
</script>
----------------------
HTML:
<img id="datestr" src="" style="border: 0px;"/>
I hope this will help you....

Javascript to get the div info

I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
​$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});​​​​​​​​
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.

Categories

Resources