html script variable assignment - javascript

So I have a script block:
<script>
var totalPopulation = 0;
for(xxxxx){
totalPopulation = totalPopulation + xxx
}
</script>
<tr>
<input type="text" name="censusPop" value=totalPopulation/>
<tr>
I'm still quite green to javascript. But is there a way to assign the value of a variable in a script block to a HTML element like input type? I know that the code is unreachable.

hope it will help you to understand how javascript work
<html>
<head>
<script>
var totalPopulation = 0;
function addAndShowPopulation(population) {
totalPopulation = totalPopulation + population;
var input_tag = getTag('my_input_id');
input_tag.value = totalPopulation;
}
function startAdding() {
addAndShowPopulation(10);
setTimeout( function(){startAdding();},1000);
}
function getTag(id) {
return document.getElementById(id);
}
</script>
</head>
<body onload="startAdding();">
<div>
<input type="text" id="my_input_id" name="censusPop" value="" placeholder="Total Population"/>
</div>
</body>
</html>

Yes, you just have to give an id to the input, for instance "id = my_input_id";
Then, in the javascript, just write :
$("my_input_id").value=totalPopulation;
That's how ajax works: find html elements ids and fill them dinamically using javascript values.
Just be carefull that the html in read before the JS. If not, $("my_input_id") will return Null

More so, you need to do something like this:
<tr>
<td>
<input type="text" id="censusPop" name="censusPop" value=""/>
<td>
<tr>
<!-- Other stuff -->
<script>
var totalPopulation = 10;
// or for loop, or whatever here.
var censusText = document.getElementById('censusPop');
censusText.value = totalPopulation;
</script>
</body>
HTML and JavaScript can interact, but not directly like that. The best thing to do is use <script> tags to setup code that updates the browser DOM. By putting the <script> tags after the HTML, usually at the bottom of the <body> tag, you allow the browser a chance to create the elements before you actually try to use them.
Another note: <tr> tags should contain <td> tags, it's the difference between a row and a column.

If you need to do multiple DOM manipulations, I'd suggest using jQuery is the proper way.
<tr>
<input id="censusPop" type="text" name"censusPop" value=""/>
</tr>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
// make sure, the code is executed when the DOM is ready
$(function () {
// grab the input element by its ID
var $input = $('#censusPop'),
totalPopulation = 0;
// do your population calculations
totalPopulation = ....;
// assign the value to the input element
$input.val(totalPopulation);
});
</script>

Related

Javascript reusing forms

I want to get the names of the n (say n==5) children of a given person, by using the same form each time.
I can't seem to be able to produce javascript code that will accomplish this simple task.
for (var i = 0; i<5; i++){
<form id="child_form">
Child name:
<input type="text" id="child_name" name="child_nm" size="40">
<br>
<input type="button" value="Submit" onclick="myFunction()">
</form>
}
<script language="javascript">
<script>
function myFunction() {
add_child_to_array();
}
var array_of_children = [];
function add_child_to_array(){
var input_string = document.getElementById("child_name").value;
alert(input_string);
array_of_inputs.push(input_string);
}
</script>
But clearly one can't do that.
I've tried taking the data out of the form and then resetting the form. It turns out you can do either but not both.
I haven't found a website that deals with this problem.
Help would be greatly appreciated.
You have multiple options to accomplish this task. I would prefer to use the HTML5 template element functionality.
You could alternatively create and append the DOM Elements by yourself.
This is certainly a bit of a mess. Assuming I understand correctly, you need to create the form in javascript, so it can be dynamically added as many times as you want. I have written a generalised way of doing this. You may want to change / simplify it. I have made sure all elements are dynamic so that can be accessed properly. Also, I have used JQuery which I highly suggest.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(function(){
var allForms = document.getElementById("all-forms");
for(var i = 0;i<5;i++){
form = document.createElement("div");
form.id = "form-" + i.toString();
if(i!=0){
form.style.display = "none";
}
input = document.createElement("input");
input.id = "child_name"+i;
input.placeholder = "input"+i;
submit = document.createElement("button");
submit.innerHTML = "go"+i;
submit.id = "submit-"+i;
submit.className = "buttons";
form.appendChild(input);
form.appendChild(submit);
allForms.appendChild(form);
}
$(".buttons").click(function(){
var id = $(this).attr("id").substring(7);
$("#form-"+id).hide();
var nextID = (parseInt(id)+1).toString();
$("#form-"+nextID).show();
});
});
</script>
</head>
<body>
<div id = "all-forms"></div>
</body>
</html>

How to make a JavaScript result appear on the same page, not in an alert popup window

I was wondering instead of using the alert function to show the function result if there was a way to print it in a text field on the same page as the original variable input. Thanks!
create a div in your body for result like
<div id="result"></div>
update from script like
var resultDiv = document.getElementById("result");
resultDiv.innerHTML = <your value>
Without additional libraries, using only browser functions, you can do this with the document.getElementById() function like this:
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" id="textfield">
</body>
<script>
function someFunction() {
return "Hello world!";
}
document.getElementById('textfield').value = someFunction();
</script>
<html>

Transfer data from one HTML file to another

I'm new to HTML and JavaScript, what I'm trying to do is from an HTML file I want to extract the things that set there and display it to another HTML file through JavaScript.
Here's what I've done so far to test it:
testing.html
<html>
<head>
<script language="javascript" type="text/javascript" src="asd.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>
</body>
</html>
next.html
<head>
<script language="javascript" type="text/javascript" src="asd.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
<table>
<tr>
<td id="here">test</td>
</tr>
</table>
</form>
</body>
</html>
asd.js
function testJS()
{
var b = document.getElementById('name').value
document.getElementById('here').innerHTML = b;
}
test.html -> ads.js(will extract value from the test.html and set to next.html) -> next.html
Try this code:
In testing.html
function testJS() {
var b = document.getElementById('name').value,
url = 'http://path_to_your_html_files/next.html?name=' + encodeURIComponent(b);
document.location.href = url;
}
And in next.html:
window.onload = function () {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.name;
}
Description: javascript can't share data between different pages, and we must to use some solutions, e.g. URL get params (in my code i used this way), cookies, localStorage, etc.
Store the name parameter in URL (?name=...) and in next.html parse URL and get all params from prev page.
PS. i'm an non-native english speaker, will you please correct my message, if necessary
The old fashioned way of setting a global variable that persist between pages is to set the data in a Cookie. The modern way is to use Local Storage, which has a good browser support (IE8+, Firefox 3.5+, Chrome 4+, Android 2+, iPhone 2+). Using localStorage is as easy as using an array:
localStorage["key"] = value;
... in another page ...
value = localStorage["key"];
You can also attach event handlers to listen for changes, though the event API is slightly different between browsers. More on the topic.
Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.
Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:
Session Cookies
HTML5 LocalStorage
POST the variable in the url and retrieve them in next.html via window object
With the Javascript localStorage class, you can use the default local storage of your browser to save (key,value) pairs and then retrieve these values on whichever page you need using the key.
Example -
Pageone.html -
<script>
localStorage.setItem("firstname", "Smith");
</script>
Pagetwo.html -
<script>
var name=localStorage.getItem("firstname");
</script>
I use this to set Profile image on each page.
On first page set value as:
localStorage.setItem("imageurl", "ur image url");
or on second page get value as :
var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);
you can simply send the data using window.location.href first store the value to send from testing.html in the script tag, variable say
<script>
var data = value_to_send
window.loaction.href="next.htm?data="+data
</script>
this is sending through a get request
HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed
document.getElementById('here').innerHTML = data.name;
This needed to be changed to
document.getElementById('here').innerHTML = data.n;
I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .
<html>
<head>
<script language="javascript" type="text/javascript" scr="asd.js"></script>
</head>
<body>
<form name="form1" action="#" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>
</body>
client side scripting
function testJS(){
var name = jQuery("#name").val();
jQuery.load("next.html",function(){
jQuery("#here").html(name);
});
}
jQuery is a js library and it simplifies its programming. So I recommend to use jQuery rathar then js. Here I just took value of input elemnt(id = name) on submit button click event ,then loaded the desired page(next.html), if the load function executes successfully i am calling a function which will put the data in desired place.
jquery load function http://api.jquery.com/load/
The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript.
1) page1.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 1 - Codemaker</title>
</head>
<body>
<form method="get" action="page2.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=text name=age size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
2) page2.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 2 - Codemaker</title>
</head>
<body>
<script>
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</body>
</html>
I coded the answers from Alex Fitiskin, and added a bit of extra code.
I added a parameter to the onLoad function to get the form's submit event, and prevent it's default behaviour first.
Here's the code:
test.html
<html>
<head>
<script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get" onsubmit="return testJS(event)">
name:<input type="text" id="name" name="n">
<input type="submit" value="next">
<!-- <button type="button" id="print" onClick="testJS()"> Print </button> //Button not needed anymore -->
</form>
</body>
</html>
next.html
<head>
<script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
<table>
<tr>
<td id="here">test</td>
</tr>
</table>
</form>
</body>
</html>
test.js
function testJS(e) {
e.preventDefault();
var b = document.getElementById('name').value,
url = 'http://path_to_next_location/next.html?name=' + encodeURIComponent(b);
document.location.href = url;
}
function onLoad() {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {},
tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.name;
}
window.onload = onLoad;
This way the onload function will be replaced with the custom onLoad function, and the form will not be submitted the default way, but instead using the code inside the testJS function.
Avoid localstorage use as data are not safe with get method. Best option is to use script set to module and then export & import data via 2 js files to html file. Variable value can be passed between pages using module method.

Bug displaying a div element when a user clicks on a button

I'm writing a webpage and I need to display a div with some content when a user clicks on a button.
I've written the code below and I don't understand why it doesn't work.
Does someone know why ?
My code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
<script type="text/javascript">
function traverse(){
output.innerHTML+='Test'; // Nothing happens !
}
function check() {
var keywords = document.getElementById('text').value.split(" ");
for (var i=0; i < keywords.length; ++i) {
traverse_tree()
}
}
</script>
</head>
<body onload ="init()">
<input id="text" type="text" size="60" value="Type your keywords here" />
<input type="button" value="Display the text 'Test'" onclick="check();" />
<div id="output">
</div>
</body>
</html>
thanks,
Bruno
Perhaps because the function is called traverse() and you're calling traverse_tree()?
Also, in your method traverse, you should get the element using document.getElementById('output'), instead of using a (undefined) variable output:
i.e:
function traverse(){
document.getElementById('output').innerHTML+='Test';
}
You could also speed this up by caching the node (to avoid calling getElementById each time the button is clicked):
// Create a closure by wrapping the cached node in a self-executing
// function to avoid polluting the global namespace
var traverse = (function (nodeId) {
// Cache the node to be updated here
var node = document.getElementById(nodeId);
// This is the function that "traverse()" will call. Return this function,
// which will assign it to the variable traverse.
return function () {
node.innerHTML += 'test';
};
// Execute the function with the id of the node to cache, i.e. output
}('output'));

Changing value of textarea

I write this script to change the value of a textarea but I fail to do so. What's wrong with my code?
<html>
<head>
<script type="text/javascript">
document.getElementsByName("status").innerHTML = "hi";
document.getElementsByName("status").title= "hi";
document.getElementsByName("status").placeholder= "hi";
</script>
</head>
<body>
<textarea placeholder="What's on your mind?" onfocus="window.UIComposer && UIComposer.focusInstance("c4d981e9a2c98b0483252333");" name="status" id="c4d981e9a2c98b0483252333_input" title="What's on your mind?" class="DOMControl_placeholder UIComposer_TextArea">What's on your mind?</textarea>
</body>
</html>
Iif you try using:
var textarea = document.getElementById('c4d981e9a2c98b0483252333_input');
textarea.value = 'hi';
It should work.
Otherwise, because of the way getElementsByName works, you'd need to provide an index (zero-based) to the call to identify which of the textareas you want to work with:
var textarea = document.getElementByName('status')[0]; // selects the first element of name 'status'
textarea.value = 'hi';
Two problems
First, document.getElementsByName returns a NodeList (which is like an array), not a single element.
Second, you do nothing to delay the execution of the JS until the element actually exists. So it won't find it anyway.
Change to document.getElementsByName("status")[0]
Move the <script> element so it appears after the textarea.
I wouldn't be comfortable with using innerHTML to modify a form control either. I'd switch to value instead.
<script type="text/javascript">
document.getElementsByName("status")[0].value = "hi";
</script>
put this script in the body
<script type="text/javascript">
document.getElementById("status").value= "hi";
</script>
change getElementsByName to getElementById
getElementsByName -> returns array of elements
getElementById -> returns single control..
then put the script in between body tags not in header.....
<html>
<head>
</head>
<body>
<textarea placeholder="What's on your mind?" onfocus="window.UIComposer && UIComposer.focusInstance("c4d981e9a2c98b0483252333");" name="status" id="c4d981e9a2c98b0483252333_input" title="What's on your mind?" class="DOMControl_placeholder UIComposer_TextArea">What's on your mind?</textarea>
<script type="text/javascript">
document.getElementById("c4d981e9a2c98b0483252333_input").value = "hi";
document.getElementsByName("status")[0].value = "hi";
</script>
</body>
</html>

Categories