Add text and attribute to div depending on url with jquery - javascript

On page load, I'm trying to add the text (capitalized) of the last part of the url to a li and its attribute data-filter (with a dot behind).
For example, if the page has this url:
www.myexample.com/#commisions
the li would look like this:
<ul>
<li><a data-filter=".commisions" href="#">Commisions</li>
</ul>
I have tried with this method but it doesn't remove the # from the text:
var url = document.URL
var cuturl = url.substr(url.lastIndexOf('/') + 1);
$( ".navbar-brand" ).html( cuturl );
Any idea how can achieve it?

Try this
var url = document.URL;
var cuturl = url.split("#")[1];
$("li a").html(cuturl);
$("li a").attr('data-filter','.'+cuturl);

Simply replace "\" with "#"
var cuturl = url.substring(url.lastIndexOf('#') + 1);
or
var cuturl = url.split("#")[1];

Related

Javascript variable... can't reference

Could someone tells me why this reference doesn't work?
var a_nav_href = $(this).attr("data-id"); //get the id data when click in a tag**strong text**
$(".wrapper").find("section[id=a_nav_href]").css({"background-color": "red"});
You have written:
var a_nav_href = $(this).attr("data-id");
$(".wrapper").find("section[id=a_nav_href]").css({"background-color": "red"});
In this code snippet "a_nav_href" is part of selector but as a string. You need to append the value of a_nav_href tot he selector.
Replace it with
$(".wrapper").find("section[id=" + a_nav_href + "]").css({"background-color": "red"});
This will return a selector query looking like this
$(".wrapper").find("section[id=someIDWhichIWantToSearch]").css({"background-color": "red"});
Your code looks for id=a_nav_href
You want:
$(".wrapper").find("section[id=" + a_nav_href + "]").css({"background-color": "red"});

Fetch html of a tag by id with slash [duplicate]

In html code I am using code
<input type = "text" id = "abc#def.com"> to get text
now it need to get its value which is entered in text field. I am using jquery to do that:
$( document ).ready( function() {
$( ".bid" ).click( function() {
idVal = this.id
bidID = "#" + idVal + "bid"
spanID = "#" + idVal + "cbid"
bidValue = $(bidID).val();
alert(idVal)
alert(bidID)
alert(bidValue) //this alert says undefined
$( spanID ).html( ' ' ).load( '{% url online_machines %}?id=' + idVal + '&bidvalue=' + bidValue);
});
});
By doing this i get the value error undefined.
I tried to remove special characters from the id to get its value. But I need the id with special characters. How can
I get its value using jquery ?
Instead of trying for ID using #, try this to match attribute like this,
$('[id=ID]')
or
$('[id='+ID+']')
so instead of
bidID = "#" + idVal + "bid"
you can try
bidID = "[id=" + idVal + "bid]"
Try escaping it:
$('#abc\\#def.com').val();
First paragraph of http://api.jquery.com/category/selectors/
It looks like JQuery has a useful method for this as of version 3 called escapeSelector.
$('#' + $.escapeSelector(my_id_with_special_chars));
https://api.jquery.com/jQuery.escapeSelector/
$(document.getElementById('abc#def.com')) also works.
Use the function CSS.escape() to select that DOM element.
In your case for the id abc#def.com you can use the below code.
$("#" + CSS.escape('abc#def.com'));
Have a shot at this, not 100% on whether this is what you're after. Let me know:
$( document ).ready(function() {
$(".bid").click(function() {
idVal = $(this).attr('id');
bidID = "#" + idVal + "bid";
spanID = "#" + idVal + "cbid";
bidValue = bidID.val();
alert(idVal);
alert(bidID);
alert(bidValue);
spanID.html(' ').load('{% url online_machines %}?id=' + idVal + '&bidvalue=' + bidValue);
});
});
This solution below worked for me, it is pretty clean:
//your HTML id has special characters:
var option= "Some option with (parenthesis or # )";
//use this type of jquery query:
$(`[id="order_${option}"]`).prop('checked',true)

Find anchor tag using href value and change href value with new href value

This is the html code:
<td>
<a class="buttontext" href="/kkdmpcu/control/MilkDeliveryScheduleReport.txt?shipmentId=10306&reportTypeFlag=milkDeliverySchedule" target="_blank" onclick="javascript:setSelectedRoute(this, 10306);" title="Milk Delivery Schedule">Delivery Schedule</a>
</td>
<td>
<a class="buttontext" href="/kkdmpcu/control/KVGenerateTruckSheet.txt?shipmentId=10306&reportTypeFlag=abstract" target="_blank" onclick="javascript:setSelectedRoute(this, 10306);" title="Abstract Report">Route Abstract Report</a>
</td>
I have the href value. Using href value I should find the anchor tag and change the href value to new value using jQuery. This is the code I currently have which is not working:
$('a[href$=(existingUrl)]'); // existingUrl is the href value I have
.attr('href', resultUrl); // resultUrl is the url that I need to replace with existingUrl.
//The whole code I have Right now
function setSelectedRoute(existingUrl, shipmentId) {
var updatedUrl = existingUrl.toString();
var facilityIndex = updatedUrl.indexOf("facilityId");
if(facilityIndex > 0){
updatedUrl = updatedUrl.substring(0, facilityIndex -1);
}
var form = $("input[value=" + shipmentId + "]").parent();
var routeId = form.find("option:selected").text();
var resultUrl = updatedUrl + "&facilityId=" + routeId;
alert(resultUrl);
$('a[href='+existingUrl+']').attr('href', resultUrl);
}
You should not use semicolon between the selector and the attr method, also if existingUrl is a variable you should concatenate it, try this:
$('a[href="'+existingUrl+'"]').attr('href', resultUrl);
this is not the href attribute, it is the a tag itself, that is first mistake, therefore existingUrl will get the object instead.
change the code like
function setSelectedRoute(existingUrl, shipmentId) {
var updatedUrl = $(existingUrl).attr('href'); // first instance
// or var updatedUrl = existingUrl.getAttribute('href');
var facilityIndex = updatedUrl.indexOf("facilityId");
if(facilityIndex > 0){
updatedUrl = updatedUrl.substring(0, facilityIndex -1);
}
var form = $("input[value=" + shipmentId + "]").parent();
var routeId = form.find("option:selected").text();
var resultUrl = updatedUrl + "&facilityId=" + routeId;
alert(resultUrl);
$('a[href="'+$(existingUrl).attr('href')+'"]').attr('href', resultUrl); //second instance
}
for the second instance, you can directly use existingUrl
$(existingUrl).attr('href', resultUrl);

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.

Add mailto: with jQuery?

<table id="here" border="1">
<tr><td>London</td><td>london#us.uk</td><td>aaa</td><td>aaa</td></tr>
<tr><td>Manchester</td><td>manchester#us.uk</td><td>aaa</td><td>aaa</td></tr>
<tr><td>Liverpool</td><td>liverpool#us.uk</td><td>aaa</td><td>aaa</td></tr>
<tr><td>Ipswich</td><td>ipswich#us.uk</td><td>aaa</td><td>aaa</td></tr>
</table>
Is possible add link mailto: for second columns with email addresses with jQuery (not modify HTML)? If yes, how?
http://jsfiddle.net/zwsMD/1/
You could just replace the contents of each second td with an a element with a mailto: href: http://jsfiddle.net/zwsMD/5/.
​$("#here td:nth-child(2)").each(function() {
var email = $(this).text();
// replace contents
$(this).html(
$("<a>").attr("href", "mailto:" + email).text(email)
);
});​​​​​​​​​​​​​​​​​​​​
Assuming it's always the second td of each row, you could iterate over those elements and wrap the contents in an a element:
$("#here td:nth-child(2)").each(function() {
$(this).contents().wrap("<a href='mailto:" + $(this).text() + "'>");
});​
Here's a working example.
You will need to loop around every row, find the cell you want and wrap a link around the content. You can use wrapInner for this.
$("#here tr").each(function() {
var td = $(this).children().eq(1);
var email = "mailto:" + td.text();
td.wrapInner($("<a>").prop("href", email));
});​
Live example
You could do something like this
​$('td:nth-child(2)').each(function(){
var text = $(this).text();
var href = "mailto:"+text;
var $a = $('<a>', { href: href, text: text});
$(this).text('').append($a);
});​​​​​​​​​​​​​​​​​​​​
fiddle here http://jsfiddle.net/zwsMD/6/

Categories

Resources