jquery set base href - javascript

I'm trying to set the base href with JQuery by reading a PHP file.
Why does $("base").load("ip.php"); work but $("base[property='href']").load("ip.php"); doesn't?
Of course what I need is to set the href parameter only, not the content of base.
I found I could get it working by using $("head").load("ip.php"); but would like to know why above isn't working.

Try something like this to set href value
$('base').attr('href','http://www.google.com');
Its depend how your file ip.php is
For example
ip.php
<?php
echo 'http://www.google.com';
?>
Then
$.get('ip.php',function(response){
$("base").attr("href", response);
});

I don't know exactly, but in my opinion, u got the meaning of the selector wrong. I think [property='href'] is not a valid selector. href is the property you should search for, and not the value.
You can select DOM-elements with jquery using $("base"). Additionally you can use a key-value combination to search for certain attribute-values of your element.
$("a[href$='.org']")
With this selector you would select elements with a href attribute which ends with '.org'.
So the point is: you still select the DOM-element and NOT a part of that element. But your search is better specified.

just need :
window.location = "http://yoursite.php";

dont use load, use $.ajax!
$.ajax({
url: "ip.php"
}).done(function (data) {
$("base").attr("href", data);
});

Related

Prefixing a URL in an window.open function jQuery

I have this HTML:
Track Your Package »
Somebody on this site was able to provide me with a script to prefix the URL with the domain http://www.example.com/ Here's the script:
$(document).ready(function(){
$('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick', $('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick').replace("window.open('", "window.open('http://www.example.com/"));
});
However, I am having a little trouble with this:
The first issue is where there is multiple instances of the element. Here's a fiddle: http://jsfiddle.net/VMmZx/
Instead of one anchor being signed with ID=4 and the other with ID=5 as intended, they're both being signed with ID=4.
The idea is, each window.open function should be prefixed with http://www.example.com however, the remainder of the URL should remain intact...
The second problem I'm encountering is when the element does not exist on a page, the remainder of the jQuery fails...
Here's another fiddle: http://jsfiddle.net/VPf32/
The <a> should get the class foo, but since the element does not exist on the page, the jQuery does not execute.
Since the JavaScript is being included in the HTML template of the ASP.NET server, this can create many problems.
I hope I've been clear and you can help me. Thanks.
You can use .each() to iterate over each matching element and change them individually:
$('a[onclick^="window.open(\'TrackPackage.asp"]').each(function(index, element) {
element = $(element);
element.attr('onclick', element.attr('onclick').replace(/open\('/, 'open(\'http://www.example.com/'));
});​
However, I don't think using links with a href of # and an onclick opening a window is as semantic as it could be. If possible, try changing the markup to this:
Track Your Package »
Now if someone is curious where it will lead them, the browser can show something useful in the status bar when you hover over it.
If you need to adjust the behavior further, add a class and bind for the click event. When they click, prevent the default action and open the window yourself, as you did before.
Why are you doing the click even inline like that? I would just output the links like:
Link Text
And then:
$('a[target=_blank]').click(function(){
var prefix = 'http://domain.com';
window.open(prefix + $(this).attr('href'));
});

revise href attribute

So I have a link like this:
<a href="http://thissite.org/thisfolder/21/thispage.php">
What I want to do is revise it but keep part of it eg:
<a href="http://thissite.org/thatfolder/21/thatpage.php">
Can this be done with Jquery or js?
I know I can replace href property with jquery but I need to leave part of the url ("21") and just change the text before and after it.
I was thinking maybe grab the href property, stick it in a variable and take it apart and put it back together somehow.
Any help with this would be largely appreciated.
You can call replace in a property setter function:
$('a').attr('href', function(index, old) {
return old.replace(/thisfolder/i, 'thatfolder');
});
A rough way of doing this would be:
// "elem" is the element, for example elem=document.getElementById('link_to_change')
var url = elem.getAttribute("href").split("/");
url.pop();
url.push("thatpage.php");
elem.setAttribute("href",url.join("/"));

Retrieving links using Jquery

I posted this up a day or two ago, received an answer which worked on JSfiddle, but didn't work on my actual code.
<div id="PublicResults">
<h2>
<dl>
<dt>
<a onmouseout="swho.alone.OnMouseOut(event)" onmouseover="swho.alone.showPopup(event, 'DR647E481', 'pra**', '', '', 'everyone', 'closed')" href="/SWApp/detailAction.do?key=DR647E481&search=pra**&soundex=&stanfordonly=&affilfilter=everyone&filters=closed">Ajay Prakash</a>
</dt>
Now, I tried $jq("#PublicResults a").attr("href"), which worked in jsfiddle, but isn't working on the page (my console reads undefined). However, when I try $jq("#PublicResults a[href]").attr("href"), I get the url of the current webpage- so I guess the issue is that .attr() is returning only the first element
So my question is twofold- if what I wrote just above is correct, how do I make .attr() return all elements. If not, what should I do to retrieve the url in href?
You have to loop troughout the array list of all links do you want to scraping:
$jq("#PublicResults a").each(function()
{
alert($(this).attr("href"));
});
If you have your jQuery instance tied to $jq() (instead of the usual $() or jQuery()), then $jq("#PublicResults a[href]").attr("href") should work. Could you post a link to where it doesn't work?
I suspect one of the following:
You may be running the jQuery code before the #PublicResults element is added to the page
It is possible that the $jq() function is not available
Something else may be altering your link href
You can use map to extract all of the href's from the jQuery wrapped objects. eg.
$('...').map(function() { return $(this).attr('href'); });
This returns a jQuery wrapped array, to get a normal JavaScript one, just use .get().

Firefox add <a xmlns="http://www.w3.org/1999/xhtml">

EDIT: This isn't happening because of the ajax call. I changed it to use a value from a TinyMCE component for fun and I get the same thing.
content = tinyMCE.get('cComponent').getContent(); //content at this point is <p>test</p>
valueToDisplay = content;
If I do:
jQuery(selector).html(valueToDisplay);
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p>
Has anyone ever seen this before using Firefox 3.6.10 and jQuery 1.4.2, I am trying to change a link text using the result from a jQuery ajax call.
I get the result expected from the ajax call:
function getValueToDisplay(fieldType){
var returnValue;
jQuery.ajax({
type: "GET",
url: "index.cfm",
async:false,
data: "fieldtype="+fieldType,
success:function(response){
returnValue = response;
}
});
return returnValue;
}
If I check the value at this point I get the expected value
console.log(returnValue) //output this --> <p>Passport Photo</p>
However when I use jQuery(selector).html to insert it inside of an existing anchor
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">Passport Photo</a></p>
I have been trying to figure out where that xmlns anchor is added but can't narrow it down to anything specific.
EDIT: I have tried forcing dataType:"html" in the ajax call...no change.
Your selector represents something that is, or is in an a tag.
A much more minimal version of your problem would be:
html:
<a id="test"></a>
js:
$('#test').html('<p>test</p>');
result:
<a id="test"><p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p></a>
Change things around so you aren't putting p tags in an a tag, or do the following:
$('#test').empty().append('<p>test</p>');
I would like to extend the answer, as of why is happening, and provide a workaround.
Doing a GreaseMonkey script i was trying to change the content of an element, perhaps not changing per se but adding more elements as the tag had only an IMG inside.
Original:
<a onclick=something><img src=url></a>
What i tried to do was to insert a DIV element that would wrap the already IMG and another new SPAN second child, so the objetive was to end up with this:
<a onclick=something><div><img src=url><span>text</span></div></a>
Using the innerHTML property it would be like this:
ANode.innerHTML = '<div>' + ANode.innerHTML + '<span>text</span></div>';
but instead i got:
<a onclick=something><div><a xmlns="http://www.w3.org/1999/xhtml"><img src=url><span>text</span></a></div></a>
Looking at the answers here did help a bit although there's no real explanation. After a while i noticed something that does not happens with the example in the question, which now i believe is the key to this issue. I was the same as jfrobishow thinking where was it happening, i thought there was something wrong concatenating the ANode.innerHTML.
Answering, at the original question, the part of narrowing it down to where does this happens, notice that the out-of-nowhere <A> was enclosing both the IMG and the new SPAN nodes, so this made me curious, the unwanted <A> was being added just before the DIV element was "built". So from this, the original example, and my following workaround you can notice that this happens when you insert a new BLOCK node inside an Anchor, as both DIV and P (original example) elements are BLOCK elements.
(If you don't know what i mean by BLOCK is from the display property of an element http://www.w3schools.com/cssref/pr_class_display.asp)
The obvious workaround is to replace the type of node you're inserting, to a non-block element, in my case the problem was the DIV i wanted, but of course it depends on the objective of your script, most of the things are there by design, i put a DIV because i needed it, so i fixed it turning that DIV into another SPAN ( which is an inline element) but i still needed to behave like a block element so put the style, this is what worked for me:
ANode.innerHTML = '<span style="display:block;">' + ANode.innerHTML + '<span>text</span></span>';
So, plainly, this problem is not from scripting (Javascript for me) but from style (CSS) stuff.
BTW, this happened at Firefox 3.6.18, notice this does not happens at Firefox 5.0.
The problem is placing block elements inside an anchor tag.
This is not valid HTML, even though most browsers will parse it fine.
You just need to use a <span></span> element inside the anchor, instead of a <div> or <p>.
This is happening because in your <html> you declared a XML Namespace (xmlns). If the xmlns anchor is not breaking anything, just leave it there.
Also, don't use async:false, make a callback function to be called on success.
EDIT: Actually that just fixed the issue with that particular value... it started happening on other values where it used to be fine.
Somehow this fixed the issue.
Changed
jQuery(selector).html(valueToDisplay)
to
jQuery(selector).html(
function(index, oldHtml)
{
return valueToDisplay;
}
);
According to the doc, if I read it right it should be doing the same thing as I am not using oldHtml in the function. (http://api.jquery.com/html/).
From the doc: "jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content."
Try changing dataType in your ajax call to "text"
Using .append() instead of .html() fixed the issue for me. Never seen this before today. Why is it adding the extra xmlns? I tried changing my dataType to "text" as well, but it didn't work. It was really messing up my CSS styles as well, but using .append() completely resolved the issue. Thanks!
UPDATE: I needed to completely replace the content of my div with the result of an .ajax() query. .append() by itself wasn't sufficient, as it would just add to the content, so I found another workaround:
First clear the div:
$("#myDiv").html("");
Then, append the content using .append():
$("#myDiv").append("My content");
It's not perfect, but it works.

Using jQuery, how do I change the elements html value? (div)

Using a ajax request I want to change content of my div.
<div id="d1">202</div>
So I want to change the content to a different number.
$('d1').InnerText???
Also, say I wanted to increment the number, how could I do that? Do I have to convert to int?
$("#di").html('My New Text');
Check out the jQuery documentation.
If you wanted to increment the number, you would do
var theint = parseInt($("#di").html(),10)
theint++;
$("#di").html(theint);
P.S. Not sure if it was a typo or not, but you need to include the # in your selector to let jQuery know you are looking for an element with an ID of di. Maybe if you come from prototype you do not expect this, just letting you know.
This would changed the inner text of your HTML element.
$('#d1').text(parseInt(requestResponse)++);
Unless you're embedding html like <b>blah</b> I'd suggest using $("#di").text() as it'll automatically escape things like <, > and &, whereas .html() will not.
Use the text function:
$("#d1").text($("#d1").text() + 1);
$('#d1').html("Html here");
jQuery('#d1').html("Hello World");
if your value is a pure text (like 'test') you could use the text() method as well. like this:
$('#d1').text('test'); Or $('#d1').html('test');
anyway, about the problem you are sharing, I think you might be calling the JavaScript code before the HTML code for the DIV is being sent to the browser. make sure you are calling the jQuery line in a <script> tag after the <div>, or in a statement like this:
$(document).ready(
function() {
$('#d1').text('test');
}
);
this way the script executes after the HTML of the div is parsed by the browser.
$("#div1").innerHTML="your text goes here..";

Categories

Resources