Call javascript function from html in different locations - javascript

I'm trying to call a javascript function that allow to print a div, defined as:
function printdiv(printpage) {
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printpage).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
That is inside a file 'main.js' in a js folder. The HTML file has a button that calls this function:
<input id="downloadScan" type="button" onclick="printDiv('document');" class="btn btn-default" value="Print">
And the same html file contains the location of the javascript function:
<script src="./js/main.js"></script>
But when I click the button, nothing happens. I tried to directly put the function inside the HTML file and it works. What is the problem?

Normally you would place script tags in your page header (or in some cases body) however given they are not present at page load I fear it may be an execution order problem.
It appears as though you are trying to dynamically create pages, you can achieve this with out needing to create the entire structure of the page, and instead just dynamically creating the content (body). It also appears as though you are trying to maintain the contents of the body and do an "append".
Try the following setup:
index.html
<html>
<head>
<script src="./js/main.js"></script>
</head>
<body>
<input id="downloadScan" type="button" onclick="appendDiv('Some text not in a div');" class="btn btn-default" value="Print">
<input id="downloadScan2" type="button" onclick="appendDiv('<div>Some content in a div</div>');" class="btn btn-default" value="Print">
</body>
</html>
main.js
function appendDiv(content) {
document.body.innerHTML = document.body.innerHTML + content;
}
https://jsfiddle.net/acvgout7/

Related

How do I give parameters to a function in a javascript file that accesses HTML and CSS attributes?

I am trying to pass html parameters to a function in a javascript file, I tried it like this:
function func(element, value) {
element.getElementById('myelement').InnerHTML = value;
}
and then something like this:
<button type="button"
onclick="script.js.func(document, 'example')">Click Me!</button>
<p id="myelement"></p>
But it doesn't work. I'm fairly new to JavaScript so sorry if I'm not as good.
I know that script.js.anything probably wouldn't work, but I don't know how to do it.
Rather than using the HTML onclick attribute, you can use JavaScript Event Listeners:
var button = document.getElementById("mybutton");
var paragraph = document.getElementById("myelement");
function func(value) {
paragraph.innerHTML = value;
}
button.addEventListener("click", function() {
func("incredible value here");
});
<button id="mybutton">Click me!</button>
<p id="myelement"></p>
If you need to specify the parameters in the HTML itself, you can specify them with a data- attribute:
var button = document.getElementById("mybutton");
var paragraph = document.getElementById("myelement");
function func(value) {
paragraph.innerHTML = value;
}
button.addEventListener("click", function() {
var value = button.getAttribute("data-value");
func(value);
});
<button id="mybutton" data-value="some value">Click me!</button>
<p id="myelement"></p>
If the JavaScript file is included in the head of your HTML, you should be able to just call it like this:
<button type="button"
onclick="func('Testing')">Click Me!</button>
<p id="myelement"></p>
Now, as far as passing parameters into the call, you can pass things like strings, numbers, etc no problem. If you want to pass in the "document", as in your example, I would actually recommend to do that inside the JavaScript function, instead of passing it in.
function func(value) {
document.getElementById('myelement').InnerHTML = value;
}
And your HTML:
<button type="button"
onclick="func('Testing')">Click Me!</button>
<p id="myelement"></p>
In your case, using vanilla JS, I think this can resolve your issue.
I think I understand what you are trying to do with this code
<button type="button" onclick="script.js.func(document, 'example')">Click Me!</button>
You are trying to load the script.js file and then the function inside it which is func.
For that in JavaScript you have to load the file first and then you can use the JavaScript functions. Something like this:
<script type="text/javascript" src="script.js"></script> <!-- Assuming the js file is on same level as the index.html file -->
<button type="button" onclick="func(document, 'example')">Click Me!</button>
On a fundamental level, this should work. If you want to refactor or clean your code have a look at other answers.

writing text into the div using document.write

I am trying to add text to two DIVS with ids= DIV1 and DIV2 in a html page(home.html) from a js page main.js using document.write() command. On clicking the button in html page, the respective text must appear in the hmtl page.
The code is as given below. I keep getting an error: document.write can be a form of eval. Is there a possible way of using document.write() and print the text in the div sections.
HTML code:
<head>
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>
</body>
JAVASCRIPT code:
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.write('<div id="div1">'+"Name:"+ arr.name +'</div>');
document.write('<div id="div2">'+"School:"+ arr.school +'</div>');
}
Name:abc
School:pqrst
...using document.write() command
Don't. Only use document.write during the initial parsing of the page, or to write to a new window you've just opened (or better yet, don't use it at all).
Instead, use the DOM. Example:
function xyz(){
var arr = {name: "abc", school: "pqrst"};
addDiv("name", "Name:" + arr.name);
addDiv("age", "School:" + arr.school);
}
function addDiv(id, content) {
var d = document.createElement("div");
d.id = id;
d.textContent = content;
document.body.appendChild(d);
}
<input type="button" value="click!" onclick="xyz()">
If you have an HTML string you want to insert, you can do that with insertAdjacentHTML, but beware of combining text from an object with HTML, because any < or & in the text must be escaped correctly (more than that if you're going to put the content into an attribute, as with your id values). It happens that your two example values don't have those characters, but you can't assume that in the general case.
You can use insertAdjacentHTML() in place of document.write(). Refer this for more details
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="name">'+"Name:"+ arr.name +'</div>');
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="age">'+"School:"+ arr.school +'</div>');
}
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>

Set to true state a checkbox in a different page(javascript)

Here's the Script.
javascript
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
$('#website-design').attr('checked',true);
window.location.href = "/contact";
}
}
}
I want to check my checkboxes when I click the button with an id=website-design-check.
Here is my HTML.
first.html
<a href="/contact" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
Here's the second HTML file where checkbox is.
second.html
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
Now how can I achieve what I want base on the description given above. Can anyone help me out guys please. I'm stuck here for an hour. I can't get any reference about getting a checkbox state from another page.
To do this, you can modify your button link and add in additional parameters that you can then process on the next page.
The code for the different pages would be like:
Edit: I changed it to jQuery, it should work now.
Script
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
window.location.href = "second.html?chk=1";
}
}
second page
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script type="text/javascript">
var url = window.location.href.split("?");
if(url[1].toLowerCase().includes("chk=1")){
$('#website-design').attr('checked',true);
}
</script>
since your checkbox is in another html page, so it's totally normal that you can't get access to it from your first html page!
what I can offer u is using the localstorage to keep the id and then use it in your second page to check if it's the ID that u want or not.
so change your function to this :
function linkPageContact(clicked_id){
localStorage.setItem("chkId", "clicked_id");
window.location.href = "/contact";
}
then in your second page in page load event do this :
$(document).ready(function() {
var chkid = localStorage.getItem("chkId");
if(chkid === 'website-design-check'){
$('#website-design').attr('checked',true);
});
You can't handle to other sites via JavaScript or jQuery directly. But there's another way. You can use the GET method to achive this.
First you need to add to the link an attribute like this in your first.html:
/contact?checkbox=true
You can change the link as you want with JavaScript.
Now it will refer to the same page but it can be now different. After that you can receive the parameter with this function on the second.html.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
I got it from this post thanks to Bakudan.
EDIT:
So here is an short theory.
When the user clicks the button on the first page, then you change the link from /contact to /contact?checkbox=true. When the user get forwarded to second.html then you change the checkbox depending on the value, which you got from the function findGetParameter('checkbox').
As all have mentioned you need to use session/query string to pass any variable/values to another page.
One click of the first button [first page] add query string parameter - http://example.com?chkboxClicked=true
<a href="secondpage.html?chkboxClicked=true>
<button>test button</button>
</a>
In the second page- check for the query string value, if present make the checkbox property to true.
In second page-
$(document).ready(function(){
if(window.location.href.contains('chkboxClicked=true')
{
$('#idOfCheckbox').prop('checked','checked');
}
})
Add it and try, it will work.
Communicating from one html file to another html file
You can solve these issue in different approaches
using localStorage
using the query parameters
Database or session to hold the data.
In your case if your application is not supporting IE lower versions localStorage will be the simple and best solution.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<a href="contact.html" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
<script>
function linkPageContact(clicked_id) {
localStorage.setItem("chkId", clicked_id);
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script>
$(document).ready(function () {
var chkid = localStorage.getItem("chkId");
if (chkid === 'website-design-check') {
$('#website-design').attr('checked', true);
}
});
</script>
</body>
</html>

how to get textarea input from another HTML page

In a.html:
I have a textarea that is converted into a link after the user clicks the submit button. When the user clicks on the link they are redirected to b.html.
<textarea id="sentenceId">
</textarea>
<br>
<button type="button" id="buttonId" onclick="createLink(document.getElementById('sentenceId').value)">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"></a>
</p>
In b.html:
I would like to display the original text.
In script.js:
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
}
If you want to open a new page and get the text there, you could use a post-form and an input[type="hidden"] to send the text and display it afterwards.
If you wand the link to be sendable, you'd either have to encode the text as get-parameter or save it to a database and add the id of the entry to the link.
As #Kramb already mentioned, localStorage is a possibility, but only if you stay on the same browser and both pages have the same domain.
Using localStorage
The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the browsing session ends—that is, when the browser is closed.
a.html
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
localStorage.setItem("textArea", val);
}
b.html
function getText(){
var textVal = localStorage.getItem("textArea");
}
Another option would be to use a query string.
a.html
function navigateTo(val){
window.href.location = "b.html?text=" + val;
}
This will pass the value of the text from textarea with the url during navigation. Once b.html has loaded, you can do the following.
b.html
function getText(){
var url = window.location.href;
var queryIndex = url.indexOf("=") + 1;
var passedText = url.substring(queryIndex);
document.getElementById('foo').value = passedText;
}
This is possible using JavaScript. You can do an AJAX call to another page on you website, and search for an element to get its content. In you're case an textarea
I wrote an example on codepen.io for you. Click here
To make things simpler im using jQuery in this example.
So how does it work?
First of, include jQuery inside the <head> tag of you're website.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
I created the following structure
structure
root
scripts
jQuery.min.js
index.js
index.html
textarea.html
Contents of index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta -->
<meta charset="UTF-8" />
<title>My New Pen!</title>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<!-- Styles -->
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<button id="clickme">To load the textarea content, click me!</button>
<div id="content">The data from the textarea will be shown here, afte you click on the button :)</div>
<!-- Scripts -->
<script src="scripts/index.js"></script>
</body>
</html>
Contents of texarea.html
<textarea id="textarea">
I am the content of the textarea inside the textarea.html file.
</textarea>
Contents of index.js
(function() {
$(document).ready(function() {
/**
* The button which triggers the ajax call
*/
var button = $("#clickme");
/**
* Register the click event
*/
button.click(function() {
$.ajax({
url: "textarea.html",
type: "GET"
}).done(function(response) {
var text = $(response).filter("#textarea").html();
$("#content").append("<br/><br/><strong>" + text + "</strong>");
});
});
});
})()
So what does index.js do exactly?
As you can see i created an Ajax call to the textarea.html file. The .done function holds the response data. The data inside it can be anything depending on the content of the textarea.html file.
$(response).filter("#textarea").html();
The above piece of code filters out the #textarea div and then gets the innerHTML using the jQuery html() function.
If you want to get the value of the textarea through the [value] attribute, you can replace above line to
$(response).filter("#textarea").val();
I believe you want to do this:
function createLink() {
var textvalue = document.getElementById('sentenceId').value;
document.getElementById("link").innerHTML = textvalue;
document.getElementById("buttonId").className ="hideme";
document.getElementById("sentenceId").className ="hideme";
}
.hideme{
display: none;
}
<textarea id="sentenceId">
</textarea>
<br>
<button id="buttonId" onclick="createLink()">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"/>
</p>

document.getElementById doesn't get newly entered HTML text input value

I use the following code.
The idea is to print the contents of the div with name "PrintThis" which incorporates the text input area "textarea1".
The problem is that getElementById only ever returns the string loaded with the page; "cake" in this case.
If I change "cake" to "pie" by clicking and typing into "textarea1" on the page then printContents still has "cake" not "pie".
<html>
<head> </head>
<script type="text/javascript">
function printFunction(divName) {
var printContents = document.getElementById(divName).innerHTML;
//Now call a script to print (not included)
}
</script>
<body>
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10" style="width:95%!important;" ">cake</textarea>
</div>
<input type="button" value="Print Div" onClick="printFunction('printThis')">
</body></html>
In my production version I also use AJAX to post the text area value back to the server, so could in theory use a page refresh, though that doesn't run, I tried using these options.
document.location.reload(true);
window.top.location=window.top.location;
The production version does have jQuery available too.
first of all you are trying to get innerHTML of the div, instead of the actual textarea.
secondly instead of trying to get innerHTML try using value.
http://jsfiddle.net/qdymvjz8/
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10">cake</textarea>
</div>
<input type="button" value="PrintDiv" onClick="printFunction('textarea1')">
function printFunction(divName) {
var printContents = document.getElementById(divName).value;
}
If you are having multiple items in your div in production then you can iterate through the children of the div and drag out the values.
function printFunction(divName) {
var printContents = document.getElementById(divName),
childItemCount = 0,
stringToPrint = '';
for (childItemCount; childItemCount < printContents.children.length; childItemCount++) {
stringToPrint += printContents.children[childItemCount].value;
}
console.log(stringToPrint);
//Now call a script to print (not included)
}

Categories

Resources