I've got following page:
<div><script>AddSomeContent(??, 1)</script></div>
<div><script>AddSomeContent(??, 2)</script></div>
I need to replace the ?? with the surrounding <div> DOM object, so the function AddSomeContent can modify it. Is there any oportunity to do this?
Before any other comments: I don't have any other option. I'm already trying to hack some existing page, and only thing I can control is content of the <script>.
I'm using jquery, but I can change it.
Edit: for clarification. AddSomeContent looks like:
function AddSomeContent(somediv, parameter)
{
$(somediv).append('there goes some data, that I dynamically create from some stuff depending on the parameter');
}
And I want to first div contain result with parameter = 1, second div parameter=2
You can try this, though it's somewhat of a hack:
(function() {
var scr = document.getElementsByTagName('script'),
parent = scr[scr.length - 1].parentNode;
// parent is the parent node of the last script on the page
})();
If you've got code in <script> tags like that, then when it runs the last script on the page will be the one that contained it.
I remember this from a previous question. The number of scripts on the page is incremented by 1 with each script that is processed, and they are processed in order. So this function will get the current script number:
function countScripts() {
return document.scripts.length;
}
Then you can go get the parentNode of that script:
var thisScriptParent = document.scripts[countScripts()].parentNode;
Related
On the first page, the user is asked to select a name from a list (select/option tags) and click the "edit" button. User's choice is stored using the "option" variable and we redirect him/her to the next page.
When the body of the next page loads, it triggers the second function, which displays the option made previously as the main header of the page.
The problem is that, although onEdit() runs, displayOption() displays the variable as the empty string (as declared above the functions).
Why doesn't the second function "see" the alteration?
var option = "";
//"edit" button (onclick)
function onEdit() {
var selector = document.getElementById("selector");
option = selector.options[selector.selectedIndex].value;
window.location.href = "nextPage.html";
return false;
}
//"nextPage.html" body (onload)
function displayOption() {
var header = document.getElementById("header-main");
header.innerHTML = option;
}
Use local storage for that, it is easy to use and in this case highly appropriate.
See mdn docs
Example
on first page simply declare
localStorage.setItem('option', 'selectedOption');
on the second page get the var
var option = localStorage.getItem('option');
EDIT
as wendelin commented it is even more appropriate to use session storage, because it remove itself automatically.
The reason this doesn't work is that when nextPage.html loads, the entire script is re-evaluated, and option is now back to its default value of "".
You'll need another solution to persist the user's choice across refreshes. One of the more common approaches to something like this is to set the value as a query string parameter that can be read from within displayOption.
I've been searching for a few hours to try and find a solution to my issue, for some reason partially similar answers on here don't seem to be working for me - so I'm creating my own question.
Basically, I'm loading pre-rendered HTML from the server using jQuery's $.get method, and I need to split the HTML returned into two sections (one that's wrapped in a div called #section-one and the other simply alongside that div, with no parent element).
See the example below:
$.get('http://jamie.st/remote_file.php', function(data){
// I want to get '#section-one' and then remove it from data, basically splitting a single returned HTML resource into two, that can be placed in two different areas of the page.
var sectionOne = $(data).find('#section-one');
// This should only return the HTML of '#section-one'
console.log(sectionOne);
// Also how can I then remove '#section-one' from the 'data' variable? The equivalent of calling the below, but from the 'data' variables string/html.
$(sectionOne).remove();
// So eventually the below would return the HTML without the '#section-one' element (and it's children)
console.log(data);
});
I've also created a jsfiddle which you can play around with if you need to, it's set up to use a real PHP file that I've hosted for demo purposes.
http://jsfiddle.net/6p0spp23/6/
If you can submit a jsfiddle link back that would be much appreciated, thanks in advance guys!
When you create a jQuery object with the remote contents $(data) becomes a collection of elements so instead of find() you want to use filter() like so:
$.get('http://jamie.st/remote_file.php', function(data){
var $data = $(data),
$sectionOne = $data.filter('#section-one'),
$rest = $data.filter(':not(#section-one)');
console.log($sectionOne);
console.log($rest);
});
Demo fiddle
I think the best way to put the received data inside a parent div. Then you can call remove or any other method to use it.
You can make parent div hidden using .hide() method if you don't want to show it.
Here I did it:
http://plnkr.co/edit/jQKXyles8sP8dliB7v0K?p=preview
// Add your javascript here
$(function() {
$.get('http://jamie.st/remote_file.php', function(data) {
$("#parent").hide();
$("#parent").html(data);
$("#section-one").remove();
console.log($("#section-one").html())
alert($("#parent").html())
});
});
When you remove a subsection from a derived jQuery object, the original string is not updated with the change so if you want the updated html content you need to generate it from the jQuery object. One way to do this is to
$.get('http://jamie.st/remote_file.php', function (data) {
var $ct = $('<div />', {
html: data
});
// I want to get '#section-one' and then remove it from data, basically splitting a single returned HTML resource into two, that can be placed in two different areas of the page.
var sectionOne = $ct.find('#section-one');
// This should only return the HTML of '#section-one'
console.log(sectionOne);
// Also how can I then remove '#section-one' from the 'data' variable? The equivilant of calling the below, but from the 'data' variables string/html.
$(sectionOne).remove();
// So eventually the below would return the HTML without the '#section-one' element (and it's children)
console.log($ct.html());
});
Demo: Fiddle
How would I do the question asked above. I have tried .append() in javascript but can you get data from one html file and insert it into another?? Some please help.
If the page you are receiving the data was created by your js then do it like this.
var childPage = window.open("somepage.html");
The child page would need a global function to receive data, then just call it.
childPage.passData(dataToPass);
If the page to receive the data is the parent, and the input is on the child do like this.
window.parent.someFunction(dataToPass);
Your respective functions would then have to take said data and do the work fro there.
the functions do have to be on the global scope of each page.
Your should wrap the inputs in a<form> whose action attribute is set to the url of the page in which you want to display the values, as shown below:
<form action='url to second page' method='get'>
<input name='name' value='something' />
<button>Submit</button>
</form>
In the second html page, You can retrieve the request parameters by calling the js function given in this answer when it is loaded:
For example,
<html>
<head>
<title>b.html</title>
<script>
function load() {
var params = getRequests();
console.log(params['name']);
}
function getRequests() {
var s1 = location.search.substring(1, location.search.length).split('&'),
r = {}, s2, i;
for (i = 0; i < s1.length; i += 1) {
s2 = s1[i].split('=');
r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
}
return r;
};
</script>
</head>
<body onload='load();'></body>
</html>
The function getRequests() returns an object containing all request parameters with the name of input element as key value. So if your first html page contains an input with name='test', the following code :
var params= getRequests();
var value =params['name'];
will give you the value of test input in second html page. Then you can use DOM API methods such as document.getElementById() to target the table elements in which you want to display the value, and set it's innerText.
can you get data from one html file and insert it into another?
Try .load()
$("#mydivid").load("/myotherpage.html");
To get a specific part of that page
$("#mydivid").load("/myotherpage.html #dividonotherpage");
We can also do something after it has loaded
$("#mydivid").load("/myotherpage.html", function() {
$("#mydivid").show();
/* like grab the values of attributes .. */
});
https://api.jquery.com/load/
edit: / reading #QBM5, I see you might be referring to 'data' as local client side user input from another window. Disregard this answer if so, as this will not pick up changes that are not set as part of the original delivered markup.
I'm no javascript guru, I'm having to call an external JS file twice in one page. The JS file includes a function. Having this function called twice (once in each JS include) breaks the functionality. So I thought I'd modify the 2nd instance to a different function name. This works to allow the first instance to work correctly but breaks the 2nd one (The one with the function changed).
The function name is address and I'm trying to work just exactly what else needs to be modified in this script to reflect the name change. I fear there are other mentions of "address" that is legitimate and not associated with the function name. I'm at my wits end and am just not sure. Anyone care to look at this JS and help me find which instances of the word address need to be changed to correctly reflect the one function and var name?
/**
* execute part
*/
$(document).ready(function(){
address.bindZipcodeFind();
});
var address = {
bindZipcodeFind: function(){
$('.zipcode-searcha').click(function(){
$('.zipcode-search-resulta').text("로딩중...");
$.get('http://www.nuvonoir.com/postalcode2/zipsearch-action.php',{
query: $('#dongNamea').val()
},function(data){
$('.zipcode-search-resulta').html(data);
address.bindPutAddress();
})
});
},
bindPutAddress: function(){
$('.zipcode-search-resulta a').click(function(){
$('[id=zipcode1a]').val($(this).parent().parent().find('.postcd1').text());
$('[id=zipcode2a]').val($(this).parent().parent().find('.postcd2').text());
$('[id=OrdAddra]').val(address.remove_useless_addr($(this).parent().parent().find('.address').text()));
address.hideZipcodeFinder();
$('[name=addr]').focus();
return false;
});
},
remove_useless_addr: function(address){
if(address.indexOf('~') != -1){
address = address.split(' ').slice(0,-1).join(' ');
}
return address;
},
hideZipcodeFinder: function(){
$('.zipcode-findera').slideUp();
}
}
If you have no way to mitigate including code twice, then there's the only option: write that function was called elsewhere:
global variable
invisible element with certain id
or even more magic things:
field in document object or document root node (html/body)
location hash (URL part after #)
cookie/sessionStorage based on document.lastModified (it is equal to page generating time on server) or anything remaining stable within one page load.
Example using global variable:
function once() {
if (window.myOnceFuncIsCalled) return;
// do the main work
window.myOnceFuncIsCalled = true;
}
Very confused here.
I have a search box which reads a list of school names from my database. When I select a school, the id (from the db) gets put in a hidden textbox.
I also have a search box which reads a list of courses from my database. However, I made the query so that it only reads the courses from the selected school.
It does that, in theory.
I was planning to pass the school id, which I grab from the hidden box, to the search script which in turn passes it to my database query. However, the variable I put my school id in doesn't seem to be updating.. yet it does. Let me explain.
I come on the page. The school for my test account has id 1. The id number in my hidden box is indeed 1. I search for a school which I know has some courses assigned to it: the id number in the box changes to 3.
I have a JS variable called school_id which I declared outside of my $(document).ready. I assume that means it's global (that's what I got taught even though SO told me once it isn't really the correct way to do this. Still have to look into that). I wrote a function which updates this variable when the school search box loses focus:
$("#school").blur(function() {
school_id = $("#school_id").val();
});
A quick javascript:alert(school_id); in my browser bar also shows the updated variable: it is now 3 instead of 1.
Onto the search script part of my page (excerpt of the script):
script:"/profiel/search_richting?json=true&limit=6&id=" + school_id + "&"
As you can see, I pass the school_id variable to the script here. However, what seems to be happening is that it always passes '1', the default variable when the page loads. It simply ignores the updated variable. Does this string get parsed when the page loads? In other words, as soon as the page loads, does it actually say &id=1? That's the only idea I can come up with why it would always pass '1'.
Is there a way to make this variable update in my script string? Or what would be the best way to solve this? I'm probably missing out on something very simple here again, as usual. Thanks a lot.
EDIT
Updated per request. I added a function getTheString as was suggest and I use the value of this function to get the URL. Still doesn't work though, it still seems to be concatenating before I get a chance to update the var. HOWEVER, with this code, my ajax log says id:[object HTMLInputElement], instead of id:1. Not sure what that means.
<script type="text/javascript">
var school_id;
$(document).ready(function() {
$("#school").blur(function() {
school_id = $("#school_id").val();
});
// zoekfunctie
var scholen = {
script:"/profiel/search_school?json=true&limit=6&",
varname:"input",
json:true,
shownoresults:false,
maxresults:6,
callback: function (obj) { document.getElementById('school_id').value = obj.id; }
};
var as_json = new bsn.AutoSuggest('school', scholen);
var richtingen = {
script: getTheString(),
varname:"input",
json:true,
shownoresults:true,
maxresults:6
};
var as_json2 = new bsn.AutoSuggest('studierichting', richtingen);
});
function getTheString() {
return "/profiel/search_richting?json=true&limit=6&id=" + school_id + "&";
}
</script>
This is because the URL is static, it is not updated as the ID changes.
You should update the URL as part of the code you wrote to get the ID:
$("#school").blur(function() {
school_id = $("#school_id").val();
// update URL here ...
});
Aren't you concatenating script:"/profiel/search_richting?json=true&limit=6&id=" + school_id + "&" before the event is fired and the var updated?
Okay. So the problem was my third party plug-in instead of the code I wrote. I fixed this by editing the code of the autoSuggest plugin so it now includes my id field in the AJAX request.
var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp)+"&id="+ $("#school_id").val();
Thanks to everyone who tried to help me out!