Get input value and insert into table on different page - javascript

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.

Related

Storing a variable from an html document to display it in another

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.

How to call a JavaScript function within a JSP tag attribute

I have a customized tag attribute called urlStat, having a dynamic value, so i created a function dedicated to determine the attribute value as follow:
function getTag() {
console.log("-------------SUCCESS---------------");
var questionId = ${question.idQuestion};
var values = {};
<c:forEach var="item" items="${tags}">
values['${item.key}'] = '${item.value}';
</c:forEach>
return values[questionId];
}
Ps: tags is a Map.
And i called the method within the attribute urlStat:
<ser:page headerAff="true" navAff="true" footerAff="false"
urlStat= "getTag()">
But the code is not executed, i can't even see the success message in the console view.
What's wrong with this solution?
I also tried to read the value directyly from the attribute:
urlStat= "${ tags.[question.idQuestion] }"
but i'm getting EL parse ERROR.
The reason is that you can not ensure getTag() method executed,due to the browser or application do not know the meaning of attribute urlStat
<ser:page headerAff="true" navAff="true" footerAff="false"
urlStat= "getTag()">
If you want to make this work,you can change to below code:
<ser:page headerAff="true" navAff="true" footerAff="false">
<script type="text/javascript">
getTag();
</script>
</ser:page>

When sending GET through jQuerys load the variables are not available

I am using jQuery to GET the contents of a navigation file and load it into a div on part of my page.
I am supplying it a value containing the page name so I can update the "active" class on the navigation.
Here is the code I am using to show the GET information, this works flawlessly as when I pass it a variable from my browser (i.e header.html?page=foo) it works perfectly.
<script>
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
alert($_GET["page"]);
</script>
As you can see at the moment it just shows an alert with the value.
When I am calling this page, It is as simple as:
<script>
$("#header").load("header.html?page=bar");
</script>
For the life of me I cannot understand why it is coming back as "undefined" when called from the .load, as I have used it many times before with GET variables.
Any input would be much appreciated,
Kris.
When Javascript is being run by .load, the document is the original document, not the page being loaded.
To pass parameters to the script being loaded, use a global variable.

Access element, which contains current <script>

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;

Variable not updating in script string, yet it updates

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!

Categories