Javascript object and parameters reference from the HTML - javascript

I have this idea of mine that I want to implement by using function parameters and objects, but the its not working as expected.
First HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Main</title>
<script type="text/javascript" src="scripting.js"></script>
</head>
<body>
<div >
<form id='radio'>
<input type="radio" name="choice" onClick="text(this.value)" value="list">
<input type="radio" name="choice" onClick="text(this.value)" value="box"></form>
<h1 id="title">" "</h1>
<p id="description"></p>
</div>
</body>
</html>
This is quite straight forward, I will use the value of the radio button as a parameter for my javascript text() function.
Here is my JavaScript code:
var choices = document.getElementsByName('choice');
var list = { a : 1 , b : 'Hi' };
var box = { a : 2, b : 'Hello'};
function text(choice) {
var i;
for (i = 0; i < choices.length; i += 1)
{
if(choices[i].checked)
{
document.getElementById('title').innerHTML = choice["a"];
document.getElementById('description').innerHTML = choice["b"];
}
}
}
I have created two objects with same name as the radio button from the HTML code. Next, in my function made a for loop to check which radio button is clicked. Based on the formula, the Head and Paragraph tags should display object contents in their respective tags. When I just input the parameter as a plain value, it prints out the value of the radio button. However, I am using the parameter as a reference to object variable. Example:
function parameter choice = "list";
document.getElementById('title').innerHTML = choice["a"];
Instead of getting the value displayed. I get "undefined" as a result.
Can someone help with this?

Two ways to approach this. If you keep the current variables and now that they will be global (in the window object), then use this:
var list = { a : 1 , b : 'Hi' };
var box = { a : 2, b : 'Hello'};
var choice = 'list';
console.log(window[choice]);
Notice we put choice in bracket because list and box are properties of window.
Because choice equals 'list', therefore, window[choice], window['list'], and window.list all refer to the same object named list.
Another approach is to place list and box in an object:
var types = {
list: { a : 1 , b : 'Hi' },
box: { a : 2, b : 'Hello' }
};
var choice = 'list';
console.log(types[choice]);
I prefer this method over putting everything in the global/window object.

Related

how to transfer values between html pages?

I'm opening new page from anothe like this:
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
the second html page looks like this:
<div class="row contractor_data__item">
<label for="code">Номер</label>
<input type="text" name="code" id="code" disabled/>
<input type="hidden" name="documentId" id="documentId">
<input type="hidden" name="actId" id="actId">
<input type="hidden" name="actCode" id="actCode">
</div>
on the page opening in the new window I have a few fields to fill. For example, I've filled "code" field on the first page and need to fill the "code" field in the page opened. How to do this?
the second part of question is that I've filled some fields on the page opened, like documentId and need to pass it to the first page I've called this one from on close, for example or on the field filled. How to perfrorm this?
In HTML5 you can use session to pass object from page to another:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
For further reference you can check here
Edit:
Sample Code:
Page1.html
<!DOCTYPE html>
<html>
<head>
<title>Page1</title>
<script type="text/javascript">
sessionStorage.setItem("name","ShishirMax");
var fName = sessionStorage.getItem("name");
console.log(fName);
function myFunction(){
window.open("page2.html");
}
</script>
</head>
<body>
This is Page 1
</br>
<button onclick="myFunction()">SendThis</button>
</body>
</html>
Page2.html
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
This is Page 2</br>
<input type="text" name="txtName" id="txtName" value="">
<script type="text/javascript">
var fName = sessionStorage.getItem("name");
console.log(fName);
document.getElementById("txtName").value = fName;
</script>
</body>
</html>
Try the following code for the test purpose.
hi if you want transfer data in some page you can use localStorage our sessionStorage in js
difference between sessionStorage clear when you close browser and localstorage will be clear only if you ask it
go refer to documentation for sintax e.g :
you value is stak in 'data' variable in this e.g
var data;
sessionStorage.setItem('nameyourvar', data);
after you can take on other page with :
sessionStorage.getItem('nameyourvar')
Use a query string. That's what they're for. Dont' forget to wrap your values in encodeURIcomponent in case they contain any special characters.
window.open("somewhere.html?firstname="+encodeURIComponent(firstname)+"&lastname="+encodeURIComponent(lastname)+"");
In the new window you can get the values from the query string like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var firstname = getParameterByName('firstname'); // "Bob"
var lastname = getParameterByName('lastname'); // "Dole"
Function is from here.
Since other people are mentioning localstorage, you should know that localstorage isn't supported in all browser. If you're interested in using something like that (you should really use query strings instead) you can check out this cross browser database Library I wrote.
Set your items to the database on the first page
jSQL.load(function(){
jSQL.createTable("UserData", [{FirstName: "Bob", LastName: "Dole"}]);
jSQL.persist(); // Save the data internally
});
Get your items from the second page
jSQL.load(function(){
var query = jSQL.query("SELECT * FROM `UserData`").execute();
var row = query.fetch("ASSOC");
var firstname = row.FirstName;
var lastname = row.LastName;
});
You can use GET parameters.
When you're opening second page, pass all the data you want to pass as GET parameters in the url, for example :
var billhref = "whatever.html?code=your_code&parameter2=parameter2_value" ;
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
Make a JS function to get parameters on the second page :
function getParams() {
var params = {},
pairs = document.URL.split('?')
.pop()
.split('&');
for (var i = 0, p; i < pairs.length; i++) {
p = pairs[i].split('=');
params[ p[0] ] = p[1];
}
return params;
}
Then use this function to get url parameters like this :
params = getParams();
for( var i in params ){
console.log( i + ' : ' + params[i] );
}
This will return output like :
code : your_code
parameter2 : parameter2_value
Using PHP will help you get around this problem with even shorter code
For example, in PHP, to get the parameters code, you'll just have to write :
$code = $_GET['code'];
And it will give you assign a variable named code the value you have passed in the url against code parameter( your_code in this example ).

How do i make my submit answer continue stacking on top of each other

I am currently doing a school project and i need to stimulate a server side application. What i am substituting it with is "Local Storage" but i have an issue. I am able to have the text in my "Text box" stack on top of each other once user have submitted their question. Once they reload, the data will still be displayed. But i do not know how to stack on top of it AGAIN after they reload. Below is my testing code
<!doctype html>
<html>
<head>
<body onload="display()">
<input type="text" id="Name"></input>
<input type="submit" id="submit" onclick="SavetoStorage()"></input>
<p id ="hoho">
</p>
<script>
var name;
var groupOfName = ["Hello", "Chicken", "Pork","Beef"];
function SavetoStorage() {
var name = document.getElementById("Name").value;
groupOfName[groupOfName.length] = name;
var newone = groupOfName;
document.getElementById("hoho").innerHTML = newone;
localStorage.groupOfName = newone;
}
function display() {
var groupOfName = localStorage.groupOfName;
document.getElementById("hoho").innerHTML = groupOfName;
}
</script>
</head>
</body>
</html>
You need to be dynamically loading the groupOfName variable like so:
var tmp = localStorage.groupOfName; //this is a string
var groupOfName = Array.from(tmp); //turn it into an array
Hopefully this helps to point you in the right direction
You can use the setItem method from localstorage.
It uses 2 parameters:
a key and a value
so you can do something like this:
var inputValue = document.getElementById("Name").value;
localStorage.setItem("name", inputValue);
The above code sets the key "name" and that key holds the inputValue
So now you can retrieve the value by calling another local storage method called getItem:
var retrieveValue = localStorage.getItem("name");
The above code retrieves the item, and what does that item holds? the value from the input, so now you can add it to your html as you wish
So that's the basics but as you only have 1 input the value will be getting overwrited, and LocalStorage doesn't supports arrays but there's a workaround so you can use arrays, it goes something like this:
//this first part converts your array to string
localStorage.setItem("names", JSON.stringify(names));
//The second part returns your item and coverts it to an array again
var storedNames = JSON.parse(localStorage.getItem("names"));

button click, adds some text and number to a div. Doesn't work

I really need some help to create this order list. It's the mening that, when you click on the button it adds the text inside the addToList, to the div, so it shows up on the page. It should add the data (name, price), in javascript.
But can't get it to work properly.
<html>
<body>
<div id="myList">
</div>
<button onclick="addToList('donut', '25,-')">add</button>
</body>
</html>
<style>
#myList {
border: 1px solid black;
margin-bottom: 10px;
}
</style>
<script>
function displayListCart() {
var myList = document.getElementById("myList");
};
function addToList(name,price) {
var itemOrder = {};
//itemOrder with data
itemOrder.Name=name;
itemOrder.Price=price;
//Add newly created product to our shopping cart
listCart.push(itemOrder);
displayListCart();
}
</script>
Here is a Fiddle Demo.
I'm not a fan of inline calls to JavaScript functions because it violates separation of concerns, so I've changed the way the event is bound. This isn't part of your problem, but I'm using this approach:
HTML:
<div id="myList">
</div>
<button id="btn" data-name="donut" data-price="25,-">add</button>
Note:
I've added the values as data attributes on the button. You can then
access them from JavaScript.
JavaScript:
function displayListCart(listCart) {
var myList = document.getElementById("myList");
for (i = 0; i < listCart.length; i++) {
myList.innerHTML = myList.innerHTML + listCart[i].Name + " : " + listCart[i].Price;
}
};
function addToList(name, price) {
var itemOrder = {};
//itemOrder with data
itemOrder.Name = name;
//debugging -- check to make sure this returns what you expect
console.log(itemOrder.Name);
itemOrder.Price = price;
//debugging -- check to make sure this returns what you expect
console.log(itemOrder.Price);
//Add newly created product to our shopping cart
//declare listCart before you use it
var listCart = [];
listCart.push(itemOrder);
//pass listCart to the display function
displayListCart(listCart);
}
function getValues() {
addToList(myBtn.getAttribute('data-name'), myBtn.getAttribute('data-price'));
}
var myBtn = document.getElementById("btn");
myBtn.addEventListener("click", getValues, false);
Notes:
You need to declare listCart before you add objects to it.
I suspect you intended to pass listCart to the display function so that you can access the objects within it for display.
You were missing the logic that adds the values to the div. You need to iterate over the array and access the object properties.
First of all, if you open the Dev Tools, you will see an error - Uncaught ReferenceError: listCart is not defined. So the first thing you need to do is create listCart array, like this : var listCart = [];
Then you should modify your displayListCart function, to display a new div for every item in listCart, like this:
function displayListCart() {
var myList = document.getElementById("myList"),
myListContent = "";
listCart.forEach(function(cart) {
myListContent += "<div>" + cart.Name + ": " + cart.Price + "<div>";
});
myList.innerHTML = myListContent;
};
The code example

Javascript how to assign a data field to a variable

I have this code in my HTML code. I'm trying to assign a field to a variable and then show it in my HTML code. What I'm trying to accomplish is showing in my HTML code just the last four digits of the 'ID' data field, right now shows 8 digits. This is my code:
<body onload="myFunction()">
<script>
function myFunction()
{
var str = ID //'ID' IS A DATA FIELD BUT 'STR' VARIABLE DOESN'T TAKE IT**
var res = str.substring(5, 8);
document.getElementById("javi").innerHTML = res;
}
</script>
And then I call it int the html body
<p id="javi"></p>
var str = document.getElementById('Javi').textContent
should get you the text of your p
from there your substring should work

Does not append input strings dynamically on the web page

I am new in Javascripting language.
I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT CODE
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the input Array, but unable to show on the web page. Need help please.
Tell me one more thing there is one code on given link. It also not gives desired answer. Please help me overcome from this problem.
<html>
<body>
<script>
function addValue(a) {
var element1 = document.createElement('tr');
var element2 = document.createElement('td');
var text = document.createTextNode(a);
var table = document.getElementById('t');
element2.appendChild(text);
element1.appendChild(element2);
table.tBodies(0).appendChild(element1);
}
</script>
Name: <input type="text" name="a">
<input type="button" value="Add" onClick='javascript:addValue(a.value)'>
<table id="t" border="1">
<tr><th>Employee Name</th></tr>
</table>
</body>
</html>
In your code where you push an item to the end of your input array, you're trying to push the array instead of the value to the array. So if your problem is that your values aren't being appended to the page is because you're trying to append the array that's empty initially onto itself.
So instead of
input.push(input);
It should be
input.push(s);
Since "s" you already declared to be the value from the text field.
And if you're not going to use that parameter you're passing in, I would get rid of it.
References: Javascript Array.Push()

Categories