Its on the same domain.. both my Jquery code and the url to read.
What i want to do is first read the webpage using Jquery and then parse certain links which has "ProductDetails.php" and extract "ProductCode" from the webpage into array.
The html page may have many instances of a href="ProductDetails.php which looks like below.
<a href="ProductDetails.php?ProductCode=SMS%2D15%2DXLG%2DA7&CartID=1" class="carttext colors_productname cart-item-name">item 1 <a>
<a href="ProductDetails.php?ProductCode=SMS%dfdfde&CartID=2" class="carttext colors_productname cart-item-name">test me item <a>
I dont know if this is really possible
You would have to do something like this:
var filteredAnchors = $( document.body ).find( 'a' ).map(function( _, anchor ) {
if( anchor.getAttribute('href').indexOf( 'ProductDetails.php' ) === 0 ) {
return anchor.getAttribute('href').match( /ProductCode=(.*?)&/ )[ 1 ];
}
}).get();
filteredAnchors now should contain all product codes.
Example: http://jsfiddle.net/WgwSr/
Something like this should get you started:
$.ajax({
url: "pagetoload.html",
success: function(htmlofthepage) {
var html = $(htmlofthepage),
resultarray = []; // the array containing our final result set
// getting all of the anchor tags we want to look at
$('a[href^="ProductDetails.php"]', html).each(function () {
var t = $(this), // the anchor tag
href = t.prop('href'), // the href of the tag (eg. ProductDetails.php?...)
start = href.indexOf('ProductCode', 0),
begin = 0,
end = 0;
if (start > -1) {
begin = href.indexOf('=', start) + 1;
end = href.indexOf('&', begin);
resultarray.push(href.split(begin, end));
}
});
}
});
Use jQuerys eachfunction:
jQuery(function($){
var links = [];
$("a[href^=ProductDetails.php]").each(function(){
links.push(this.href.replace(/^.*\?/,'');
});
});
Related
I have a variable called links that stores any URLs that have been visited previously.
I need to match the URLs on the page with the results from the variable. If they match assign the class "visited" to just those links.
So for example if my page has:
<a href="link1.html">
<a href="link2.html">
<a href="link3.html">
<a href="link4.html">
<a href="link5.html">
and the links variable has:
link1.html
link3.html
link4.html
In this case like to add the class "visited" to the links that are stored in the variable link1.html, link3.html and link4.html in this case. There are loads of links with all sorts of text. These ones are just for a simple example.
This is what I have so far:
$(document).ready(function() {
$('#rightbox li a').each(
function(intIndex){
var links = $(this).attr('href');
console.log(links);
$.ajax({
url: links,
type:'HEAD',
error: function() { },
success: function() {
var visited = (links)
$("#visitedLinkContainer").append(visited);
$(this).attr('href').addClass("visited");`
// I tried this but it adds visited to everylink which I knew would, but I don't know what to put here`
}
});
});
});
This is for a personal project at home. I'm using local storage at the moment, but I'd prefer to do it this way if possible.
Thank you for any help received
Use the following code:
links.forEach(function(link) {
$('#rightbox li a[href="' + link + '"]').addClass('visited');
});
The jQuery selector [<attribute>="<value>"] selects elements that their <attribute> equals to <value>.
I've created an example: https://codepen.io/anon/pen/OwMbgp
html
Link1
Link2
Link3
Link4
Link5
Link2
CSS
.visited {
color: red;
}
JS
$(document).ready(function() {
// Faking that you already entered the first 2 links
var visited = ['#1', '#2'];
// when clicking it adds the class visited right away
$( "a" ).click(function() {
visited.push($(this).attr('href'));
$(this).addClass( "visited" );
});
// loop trough the visited url and find the corresponding a tags that all have the urls inside the visited variable
$.each(visited, function( index, value ) {
// this gets all links with that same value, if you don't want this you need to store something unique of the a tag or the entire element inside the var visited
var allLinks = $('a[href^="' + value + '"]');
$.each(allLinks, function() {
$(this).addClass( "visited" )
})
// this allert shows you what index and value are
alert( index + ": " + value );
});
});
Hope this helped somehow
convert this line [var links = $(this).attr('href');], to this:
var LINK = $(this),
links = LINK.attr('href');
now, after line $("#visitedLinkContainer").append(visited); put here instead of yours code:
LINK.addClass("visited");
or try this:
$("#rightbox [href='"+links+"']").addClass("visited");
for(var i=0; i<arrayOfLinksAlreadyVisited.length;i++) {
$("#rightbox li a").each(function() {
if($(this).attr("href") == arrayOfLinksAlreadyVisited[i])) {
$(this).addClass("visited");
}
//Match the href with arrayOfLinksAlreadyVisited[i]
//if true then addClass visited to this anchor tag via
//keyword this
// else do nothing
});
}
I hope the above logic will work for you.
There are href links on the page, its text is not complete. for example page is showing link text as "link1" however the correct text should be like "link1 - Module33". Both page and actual texts starts with same text (in this example both will starts with "link1").
I am getting actual text from JSON object from java session and comparing. If JSON text starts with page text (that means JSON text "link1 - Module33" startsWith "link1" (page text), then update "link1" to "link1 - Module33".
Page has below code to show the links
<div class="display_links">
<ul id="accounts_links_container">
<li id="accounts_mb_2_id"><a href="javascript:void(0)" class="linksmall"
id="accounts_mb_2_a"> link1 </a></li>
<li id="accounts_mb_11_id"><a href="javascript:void(0)" class="linksmall"
id="accounts_mb_11_a"> link2 </a></li>
.
.
.
// more links
</ul>
</div>
Note : li id is not static its different for each page text, however ul id is static.
I am reading correct & full link text from JSON object (from java session) as below
var sessionValue = <%= json %>; // taken from String array
and reading page text as below :-
$('.display_links li').each(function() { pageValue.push($(this).text()) });
sessionValue has correct updated text and pageValue has partial texts. I am comparing using below code
for(var s=0; s<pageValue.length; s++) {
var pageLen = $.trim(pageValue[s]).length;
for(var w=0; w<sessionValue.length; w++) {
var sesstionLen = $.trim(sessionValue[w]).length;
var newV = sessionValue[w].substring(0, pageLen);
if($.trim(newV)==$.trim(pageValue[s])){
**// UPDATING VALUES AS BELOW**
pageValue[s]=sessionValue[w];
}
}
}
I am trying to update page value text to session value text as pageValue[s]=sessionValue[w]; (in above code) but its not actually updating the values. Sorry for the poor comparing text logic.
Please help, how to update it dynamically in the loop after comparing to make sure I am updating the correct link text.
pageValue[s]=sessionValue[w]; just updates the array; it has no effect whatsoever on the li's text.
If you want to update the li's text, you need to do that in your each. Here's an example doing that, and taking a slightly more efficient approach to the comparison:
$('.display_links li a').each(function() {
var $this = $(this);
var text = $.trim($this.text());
var textLen = text.length;
for (var w = 0; w < sessionValue.length; ++w) {
var sessionText = $.trim(sessionValue[w]);
if (sessionText.substring(0, textLen) == text) {
text = sessionText;
$this.text(text);
break; // Found it, so we stop
}
}
pageValue.push(text); // If you want it for something
});
I think it's cleaner to just select the elements you care about (in this case the anchor tags) and then use built-in functionality to compare rather than reimplementing a startsWith function.
var sessionValue = ['link1 - Module33', 'link2 - foobar'];
$('.display_links li a').each(function() {
var $this = $(this);
var text = $this.text().trim();
sessionValue.forEach(function(sessionValue) {
if (sessionValue.startsWith(text)) {
$this.text(sessionValue);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display_links">
<ul id="accounts_links_container">
<li id="accounts_mb_2_id"> link1 </li>
<li id="accounts_mb_11_id"> link2 </li>
</ul>
</div>
The result of $(this).text() is a primitive string, not a reference to the textNode of the element. It doesn't matter if you update pageValue, because it is not related to the original element.
Instead of pushing the strings to an array to process, you can stay inside the $.each() loop and still have access to the elements, which is needed to update the text. Something like this:
$('.display_links li').each(function() {
var $li = $(this);
var liText = $.trim($li.text());
var liLen = liText.length;
for(var w = 0; w < sessionValue.length; w++) {
var sessionLen = $.trim(sessionValue[w]).length;
var newV = sessionValue[w].substring(0, liLen);
if ($.trim(newV) === liText) {
**// UPDATING VALUES AS BELOW**
$li.text(sessionValue[w]);
}
}
});
I am a noob and thought I would take a shot at this.
Here is my approach although the sessionValue array is a bit foggy to me. Is the length undetermined?
I declared var's outside of the loop for better performance so they are not declared over and over.
Iterate through elements passing each value through Compare function and returning the correct value and update immediately after all conditions are satisfied.
var i = 0;
$('.display_links li a').each(function(i) {
$(this).text(Compare($(this).text(), sessionValue[i]));
i++;
});
var Compare;
var update;
Compare = function(val1, val2) {
// Check if val1 does not equal val2 and see if val2 exists(both must be true) then update.
if(!val1 === val2 || val2) {
update = val2
}
return update;
}
So, i have span element where i appending some content - sometimes this content is duplicated. How to remove this one value which is duplicate of another ...
This is how looks like my output html:
<span class="some_class">
"value01"
"value01"
"value02"
"value03"
"value03"
</span>
I can't add any function because i have no idea how to do this, can u help me?
If these values are being added by JS code, then You can make sth like this:
http://jsfiddle.net/Sahadar/Nzs52/5/
You just have to make object which will store all strings placed inside this span, then just before insertion check if this inserted string is already in store object.
function(event) {
var textareaValue = textarea.value();
if(insertedTexts[textareaValue]) {
event.preventDefault();
textarea.value('');
} else {
insertedTexts[textareaValue] = true;
someSpan.append("\""+textareaValue+"\"");
}
}
If these values are already inside span, use function as follows:
var someSpan = $('.some_class');
var insertedTexts = [];
var result = someSpan.text().match(/"\w+(?=\")/gm);
result = result.map(function(value) {
return value.substring(1,value.length);
});
result.forEach(function(value) {
if(insertedTexts.indexOf(value) === -1) {
insertedTexts.push(value);
}
});
var newSpanText = "\""+insertedTexts.join('""')+"\"";
someSpan.text(newSpanText);
console.info(result, insertedTexts);
It's rebuilding span text (trimming etc.) but main functinality is preserved.
jsFiddle working copy:
http://jsfiddle.net/Sahadar/kKNXG/6/
Create an array variable
var vals = [];
which keeps track of the items. Then, in your function that appends items to the span check:
if (vals.indexOf("Mynewvalue") > -1) {
// Add to the span...
}
Hello there JavaScript and Jquery gurus, I am getting and then displaying list of a facebook user's friend list by using the following code:
<script>
function getFriends(){
var theword = '/me/friends';
FB.api(theword, function(response) {
var divInfo = document.getElementById("divInfo");
var friends = response.data;
divInfo.innerHTML += '<h1 id="header">Friends/h1><ul id="list">';
for (var i = 0; i < friends.length; i++) {
divInfo.innerHTML += '<li>'+friends[i].name +'</li>';
}
divInfo.innerHTML += '</ul></div>';
});
}
</script>
graph friends
<div id = divInfo></div>
Now, in my Facebook integrated website, I would eventually like my users to choose their friends and send them gifts/facebook-punch them..or whatever. Therefore, I am trying to implement a simple Jquery filter using this piece of code that manipulates with the DOM
<script>
(function ($) {
// custom css expression for a case-insensitive contains()
jQuery.expr[':'].Contains = function(a,i,m){
return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function listFilter(header, list) { // header is any element, list is an unordered list
// create and add the filter form to the header
var form = $("<form>").attr({"class":"filterform","action":"#"}),
input = $("<input>").attr({"class":"filterinput","type":"text"});
$(form).append(input).appendTo(header);
$(input)
.change( function () {
var filter = $(this).val();
if(filter) {
// this finds all links in a list that contain the input,
// and hide the ones not containing the input while showing the ones that do
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("a:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
.keyup( function () {
// fire the above change event after every letter
$(this).change();
});
}
//ondomready
$(function () {
listFilter($("#header"), $("#list"));
});
}(jQuery));
</script>
Now, This piece of code works on normal unordered list, but when the list is rendered by JavaScript, it does not. I have a hunch that it has to do something with the innerHTML method. Also, I have tried putting the JQuery filter code within and also right before tag. Neither seemed to work.
If anyone knows how to resolve this issue, please help me out. Also, is there a better way to display the friends list from which users can choose from?
The problem is here:
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("a:Contains(" + filter + ")").parent().slideDown();
Since you're rendering this:
divInfo.innerHTML += '<li>'+friends[i].name +'</li>';
There is no anchor wrapper, the text is directly in the <li> so change the first two lines to look in those elements accordingly, like this:
$(list).find("li:not(:Contains(" + filter + "))").slideUp();
$(list).find("li:Contains(" + filter + ")").slideDown();
You could also make that whole section a bit faster by running your Contains() code only once, making a big pact for long lists, like this:
$(input).bind("change keyup", function () {
var filter = $(this).val();
if(filter) {
var matches = $(list).find("li:Contains(" + filter + ")").slideDown();
$(list).find("li").not(matches).slideUp();
} else {
$(list).find("li").slideDown();
}
});
And to resolve those potential (likely really) innerHTML issues, build your structure by using the DOM, like this:
function getFriends(){
var theword = '/me/friends';
FB.api(theword, function(response) {
var divInfo = $("#divInfo"), friends = response.data;
divInfo.append('<h1 id="header">Friends/h1>');
var list = $('<ul id="list" />');
for (var i = 0; i < friends.length; i++) {
$('<li />', { text: friends[i].name }).appendTo(list);
}
divInfo.append(list);
});
}
By doing it this way you're building your content all at once, the <ul> being a document fragment, then one insertion....this is also better for performance for 2 reasons. 1) You're currently adding invalid HTML with the .innerHTML calls...you should never have an unclosed element at any point, and 2) you're doing 2 DOM manipulations (1 for the header, 1 for the list) after the much faster document fragment creation, not repeated .innerHTML changes.
I would like to .get a page and then use jquery to find elements such as links. How do i make $('#blah') search the get data instead of the page?
You should be able to create a dom element from the returned HTML without actually adding it to the document, and then search through that using the jQuery methods:
jQuery.get('/my_url/', function(html_data) {
// If your html_data isn't already wrapped with an HTML object, you may
// need to wrap it like so:
//
// var jQueryObject = $("<div>" + html_data + "</div>");
var jQueryObject = $(html_data);
jQueryObject.find("a.link_class");
// Or, as stated by gregmac below, you could just do the following:
$("a.link_class", html_data);
// or, if wrapping is required:
$("a.link_class", "<div>" + html_data + "<div>");
});
For finding links or a specific element like your example, you can do this:
$.get('test.html', function(data) {
var links = $('a', data); //Use the response as the context to search in
var blah = $('#blah', data);
});
I'm pretty sure you'll be limited to only getting links from a local server/page too.
// create blank array
var links = new Array();
// where should we $.get
var url = '/menus';
$.get(url, function(data) {
// get anchors from the url
links = $(data).find('a');
// loop through all of them
for(i=0; i<links.length; i++)
{
// do something (may alert a lot of links... be prepared)
alert($(links[i]).attr('href'));
}
});
you can simply do this:
$('#result').load('ajax/test.html #container');
only the content of #container will be shown.