Unable to display text box results in div - javascript

I want to display all the resulting expressions under the Result and Entered button every time I hit "=". But I am stuck trying to figure it out. This is what I have so far. Any help would be much appreciated. Thank you.
<!DOCTYPE html>
<html>
<body>
<head>
</head>
<script>
//Fucntion to bring operation to the operators
function calculation()
{
var x = parseInt(document.getElementById("op1").value);
var y = parseInt(document.getElementById("op2").value);
var z = document.getElementById("operator").value;
var result;
if (z == "+"){
result = x + y;
document.getElementById("result").value = +result;
}else if (z == "-"){
result = x - y;
document.getElementById("result").value = +result;
}else if (z == "*"){
result = x * y;
document.getElementById("result").value = +result;
}else if (z == "/"){
result = x / y;
document.getElementById("result").value = +result;
}
displayResults();
}
function displayResults()
{
var dispArr = ["document.getElementById('op1').value", "document.getElementById('operator').value", "document.getElementById('op2').value",
"=","document.getElementById('result').value"];
dispArr.toString();
document.getElementbyId("expressions").innerHTML = dispArr.join("");
}
//Function to display the operators
function displayOptr(i) {
var optrArr =["+","-","*","/"];
if (i==0){
document.getElementById("operator").value = "+";
} else if (i==1){
document.getElementById("operator").value = "-";
} else if (i==2){
document.getElementById("operator").value = "*";
} else if (i==3){
document.getElementById("operator").value = "/";
}
}
</script>
<div id="bodyDiv">
<h1> CALCULATOR </h1>
<hr/>
<div class="leftDiv">
<div id="colorblock">
<div id = "add" class = "blocks" onClick = "displayOptr(0)">ADD</div>
<div id = "subtract" class = "blocks" onClick = "displayOptr(1)">SUBTRACT</div>
<div id = "multiply" class = "blocks" onClick = "displayOptr(2)">MULTIPLY</div>
<div id = "divide" class = "blocks" onClick = "displayOptr(3)">DIVIDE</div>
</div>
</div>
<div class="rightDiv">
<div id = "calcblock">
<input type ="text" size="3" id="op1"/>
<input type = "text" size="1" id = "operator">
<input type = "text" size="3" id="op2"/>
<input type = "button" value = "=" id="calculate" onClick = "calculation()"/>
<input type = "text" size="6" id = "result" />
</div>
</div>
<hr/>
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut">
<input type = "button" value = "By Result" id = "resultBut"><br><br>
<div id = "expressions"></hr></div>
</div>
</div>
</div>
</body>
</html>

The values for dispArr are in quotes so they're treated as strings. Remove the quotes, then you are using document.getElementbyId instead of document.getElementById on line 39 (under dispArr.toString();)
<html>
<body>
<head>
</head>
<script>
//Fucntion to bring operation to the operators
function calculation()
{
var x = parseInt(document.getElementById("op1").value);
var y = parseInt(document.getElementById("op2").value);
var z = document.getElementById("operator").value;
var result;
if (z == "+"){
result = x + y;
document.getElementById("result").value = +result;
}else if (z == "-"){
result = x - y;
document.getElementById("result").value = +result;
}else if (z == "*"){
result = x * y;
document.getElementById("result").value = +result;
}else if (z == "/"){
result = x / y;
document.getElementById("result").value = +result;
}
displayResults();
}
function displayResults()
{
var dispArr = [document.getElementById('op1').value, document.getElementById('operator').value, document.getElementById('op2').value,
"=",document.getElementById('result').value];
dispArr.toString();
document.getElementById("expressions").innerHTML = dispArr.join("");
}
//Function to display the operators
function displayOptr(i) {
var optrArr =["+","-","*","/"];
if (i==0){
document.getElementById("operator").value = "+";
} else if (i==1){
document.getElementById("operator").value = "-";
} else if (i==2){
document.getElementById("operator").value = "*";
} else if (i==3){
document.getElementById("operator").value = "/";
}
}
</script>
<div id="bodyDiv">
<h1> CALCULATOR </h1>
<hr/>
<div class="leftDiv">
<div id="colorblock">
<div id = "add" class = "blocks" onClick = "displayOptr(0)">ADD</div>
<div id = "subtract" class = "blocks" onClick = "displayOptr(1)">SUBTRACT</div>
<div id = "multiply" class = "blocks" onClick = "displayOptr(2)">MULTIPLY</div>
<div id = "divide" class = "blocks" onClick = "displayOptr(3)">DIVIDE</div>
</div>
</div>
<div class="rightDiv">
<div id = "calcblock">
<input type ="text" size="3" id="op1"/>
<input type = "text" size="1" id = "operator">
<input type = "text" size="3" id="op2"/>
<input type = "button" value = "=" id="calculate" onClick = "calculation()"/>
<input type = "text" size="6" id = "result" />
</div>
</div>
<hr/>
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut">
<input type = "button" value = "By Result" id = "resultBut"><br><br>
<div id = "expressions"></hr></div>
</div>
</div>
</div>
</body>
</html>

Related

Manipulation of div elements with javascript

Can someone explain to me or figure it out. I dont know where I made a mistake here. I have javascript and html code where I get input from user for a flight. I want to make a counter to count all flights function counter() but it gives me the value of name. And another problem is I want when I click on the Accept button to make the background of the div element green function changeColor().
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
var btn1 = document.createElement("BUTTON");
var btn2 = document.createElement("BUTTON");
var t1 = document.createTextNode("Accept");
var t2 = document.createTextNode("Reject");
btn1.appendChild(t1);
btn2.appendChild(t2);
divForOutput.innerHTML += name.value +", " + plainNum.value +"<br>" + "Radius: " + radius.value +", "+"Altitude: "+altitude.value+"<br>"+type.value+"<br>";
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
btn1.setAttribute('onclick','changeColor(this);');
btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
var parentofChild = document.getElementById("output");
output.div.background = green;
}
function counter(){;
var sum = document.getElementsByClassName("printing");
var counter = 0;
for(var i = 0;i <sum.length;i++){
counter+=parseInt(sum[i].innerHTML);
}
document.getElementById("total").innerHTML = counter;
}
<h1>Register flight</h1>
<form>
<div>
<label>Name and surname</label>
<input type="text" id="name">
</div>
<div>
<label>Number plate</label>
<input type="text" id="plainNum">
</div>
<div>
<label>Coordinates</label>
<input type="text" id="coordinates">
</div>
<div>
<label>Radius</label>
<input type="text" id="radius">
</div>
<div>
<label>Altitude</label>
<input type="text" id="altitude">
</div>
<div>
<label>Type</label>
<select id="type">
<option value="Comercial">Comercial</option>
<option value="Buissines">Buissines</option>
</select>
</div>
<div>
<input type="button" value="Submit" onclick="addRow();">
</div>
</form>
<divи>
<h3>Registered flights</h3>
<p>Total:<span id="total">0</span></p>
</div>
<div id="output">
</div>
Below I've fixed some of the code and made things a bit better.
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
//var btn1 = document.createElement("BUTTON");
//var btn2 = document.createElement("BUTTON");
//var t1 = document.createTextNode("Accept");
//var t2 = document.createTextNode("Reject");
//btn1.appendChild(t1);
//btn2.appendChild(t2);
divForOutput.innerHTML = `
${name.value}<br>
Radius: ${radius.value}<br>
Altitude: ${altitude.value}<br>
${type.value}<br>
<button onclick="changeColor();">Accept</button>
<button onclick="disableButtons();">Reject</button>
`;
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
//btn1.setAttribute('onclick','changeColor(this);');
//btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
const output = document.getElementById("output");
output.style.backgroundColor = "green";
}
function counter(){;
const sum = document.getElementsByClassName("printing");
const counter = sum.getElementsByTagName('div').length;
return document.getElementById("total").innerHTML = counter;
}
There is an explanation for the background color here
As for the counter; what I did was count the div elements inside of the output div. That will give you the amount of flights a user has.
Your color setting had several problems. You don't use output.div.background to set the color, and you were using the undefined variable green instead of the string "green". This works:
function changeColor(){
var output = document.getElementById("output");
output.style.backgroundColor = 'green';
}
I don't know what you are trying to count with your counter function, so I can't fix that.

Having trouble displaying total cost

I am struggling to calculate the totalPrice and finalPrice, I've been working on this for hours. I tried everything, am I supposed to put the if and else statements in the script? Tried everything, doesn't work, my clear button doesn't clear either. Thanks for your help!!!
<html>
<head>
<meta charset = "UTF-8">
<title> World Travel </title>
<style>
body {background-color: black; font-family: optima;
color: white; text-align: left}
p { font-size: 20px}
button {font-size: 20px; background-color: white}
input { font-size: 20px}
</style>
</head>
<body>
<script>
var hotelNights= 0;
var travelPrice = 0;
var totalPrice = 0;
var finalPrice = 0;
</script>
<h1> World Travel </h1>
<h2> Price Processing </h2>
<p> Select Destination:
<input type = "radio" id = "a" name = "destination" size = "3"
onclick = /> Europe
<input type= "radio" id = "b" name= "destination" size = "3"
onclick = "destination == 'a';" /> Africa
</p>
<p> Select Air Travel Option:
<input type = "radio" id = "o" name = "airTravel" size = "3"
onclick = "
if (destination == "e") {
totalPrice += 500; }
else {
totalPrice += 700; }
" /> One Way
<input type= "radio" id = "x" name = "airTravel" size = "3"
onclick = "
if (destination == "e") {
totalPrice += 900; }
else {
totalPrice += 1300; }
" /> Round Trip
</p>
<p> Enter number of Hotel nights:
<input type = "text" id = "hotelNights" value = ""
onchange = "
if (destination == "e") {
totalPrice += 300*document.getElementaryById("hotelNights").value; }
else {
totalPrice += 200*document.getElementaryById("hotelNights").value; } " />
</p>
<p> Select Tour type:
<input type = "radio" id = "g" name = "tourPrice" size = "3"
onclick = "
if (desination == "e") {
totalPrice += 1500; }
else {
totalPrice + = 1300; } "/> Grand Package
<input type = "radio" id = "z" name = "tourPrice" size = "3"
onclick = "
if (destination == "e") {
totalPrice += 800; }
else {
totalPrice += 500; } " /> Basic Package
</p>
<p>
<button onclick="
finalPrice= (totalPrice*1.15);
totalPriceTextBox.value = '$' + totalPrice.toFixed(2);
finalPriceTextBox.value = '$' + finalPrice.toFixed(2);
"> Process </button>
</p>
<p> Total Price: $
<input type = "text" id = "totalPriceTextBox" value = "" readonly />
</p>
<p> Final Price (includes 15% surcharge): $
<input type = "text" id = "finalPriceTextBox" value = "" readonly />
</p>
<p>
<button onclick= "
a.checked = false;
hotelNights = '';
o.checked = false;
g.checked = false;
totalPriceTextBox.value = '';
finalPriceTextBox.value = '';
id_of_radio_button.checked = false;
id_of_text_box = '';
"> Clear </button>
</p>
<body>
</html>
......................................................................................................................................................................................................................................................................................................................................................................................................
You can't use double quotes in an inline onclick handler:
onclick = "
if (destination == "e") { // Can't use double quotes here because you're already inside a set of double quotes!
totalPrice += 900; }
else {
totalPrice += 1300; }
" />
You also need to declare and initialize destination.
Also, this onclick looks wrong:
<input type = "radio" id = "a" name = "destination" size = "3"
onclick = /> Europe

Can't get button to show up on click with javascript visibility

I'm having trouble working with my next button on my webpage. I can get the other parts of the page (the answer message) to show up fine with when the button is clicked, but for some reason it will not work with this next button. Hiding it works fine, but when I click the button the next button will not show up. If I don't hide or style = "none", the button shows up fine. I've tried .style = "none" & .style = "block" and .visibility = "hidden" and .visibility = "visible", with no success. If anyone could give me some insight I'd appreciate it!
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky() {
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
} else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next() {
};
<div class="user-response">
What is <input type="text" id="user_answer"> ?
<button onclick="clicky()" type=b utton>Submit</button>
<button onclick="next()" type=s ubmit id="next">Next -></button>
</div>
<p id="correct">{{clue.answer}}</p>
<p id="score">{{score}}</p>
<p id="value">{{clue.worth}}</p>
<form method="GET">
<input type="hidden" name="score_get" value=0>
</form>
<div class="answer" id="answer">
</div>
At the end of the clicky function you are trying to set the innerHTML of a missing element "showed_score", It results with an error and quit the function before it is done.
Just remove this line or add the element to your html
I created this interactive snippet. Looks like there is an error (Uncaught TypeError: Cannot read property 'innerHTML' of null) happening right above that is throwing console errors. Based on your code the elements showed_score and score_get do not exist. Fixing this will hopefully fix your original problem.
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id = "next">Next -></button>
</div>
<p id = "correct"></p>
<p id = "score"></p>
<p id = "value"></p>
<form method = "GET">
<input type = "hidden" name = "score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>
<script type = "text/javascript">
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next(){
};
</script>
I don't know what template engine youre using to render {{clue.answer}} but I imagine there's an answer in there somewhere. Try the following code instead (you were missing an id reference for getElementById :
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id = "next">Next -></button>
</div>
<p id = "correct">{{clue.answer}}</p>
<p id = "score">{{score}}</p>
<p id = "value">{{clue.worth}}</p>
<form method = "GET">
<input type = "hidden" name = "score_get" id="score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>
<div id="showed_score">
</div>
<script type = "text/javascript">
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + Math.floor(score);
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
}
function next(){
}
</script>
Try commenting these 2 lines:
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
They trigger an error which prevents the button from becoming visible.
You probably have an error before it gets to the code for visibility.
Look in your console to find errors and what is causing it.
Here's your example with most of it commented out and it works:
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
//var correct = document.getElementById("correct").innerHTML;
//var score = document.getElementById("score").innerHTML;
//var value = document.getElementById("value").innerHTML;
//var val2 = value.substring(1);
//var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
//document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
//score -= worth;
}
//document.getElementById("showed_score").innerHTML = "Score is now $" + score;
//document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next(){
};
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id="next">Next -></button>
</div>
<p id = "correct">{{clue.answer}}</p>
<p id = "score">{{score}}</p>
<p id = "value">{{clue.worth}}</p>
<form method = "GET">
<input type = "hidden" name = "score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>

Generate user id using javascript and display it in textbox

So i need to display the user id that has been generated in javascript but i have problem to display it on textbox.
here's the javascript coding:
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
}
function SaveDetails(){
var CreateuserID = generateuserID();
document.getElementById('userID').value = CreateuserID;
var name = document.getElementById('userName').value;
var occupation = document.getElementById('userOccupation').value;
sessionStorage.setItem(name, occupation);
display();
var name = document.getElementById('userName').value = "";
var occupation = document.getElementById('userOccupation').value = "";
}
function display(){
var output = document.getElementById('output');
output.innerHTML = "";
for(var i=0;i<sessionStorage.length;i++)
{
var name = sessionStorage.key(i);
var occupation = sessionStorage.getItem(name);
output.innerHTML += name+"|"+occupation+"<br>";
}
}
function generateuserID()
{
var userIDnum = 1;
userIDnum++;
}
window.addEventListener('load', AddDetails, false);
This is the HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="Style.css">
<script src="script.js"></script>
</head>
<br>
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort">
<option value ="userID">userID</option>
<option value ="userID">userName</option>
<option value ="userID">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
</html>
Please help me i have been doing this for days and cant think of solution. I tried using ECMAScript and it wont work either. I'm still new and lack of knowledge.
Your generateuserID() method doesn't return anything. Even if your returned userIDnum everyone's user id will be 2. Do you realize that JavaScript just runs in the browser? None of the variables will exist between different users.
There are many mistakes in your sample. You don't need sessionStorage just for static content. Here is the working codepen [ https://codepen.io/vivekamin/pen/gQMRPx ] .I have created for you from your code. Please check it out. Here is the code. I have used createElement just for sake of working example. However, if you have many elements to append you can use createDocumentFragment which is more efficient. I am just adding the last data to HTML, output element in form of paragraph text
HTML:
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort" id ="sortBy">
<option value ="userID">userID</option>
<option value ="name">userName</option>
<option value ="occupation">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
JS Code:
let counter = 1;
let data = [];
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
let sortBy = document.getElementById('sortBy');
sortBy.addEventListener('change', SortAndDisplay, false);
document.getElementById('userID').value = counter;
}
function SortAndDisplay(){
console.log("Sorting", document.getElementById('sortBy').value);
let sortBy = document.getElementById('sortBy').value;
if(sortBy === "userID"){
data.sort(function (a, b) {
return a.id - b.id;
});
}
else{
sortByNameOrOccupation(sortBy);
}
console.log(data);
displayAfterSort();
}
function SaveDetails(){
let name = document.getElementById('userName');
let occupation = document.getElementById('userOccupation');
data.push({id: counter, name: name.value, occupation: occupation.value });
console.log(data);
counter++;
document.getElementById('userID').value = counter;
name.value='';
occupation.value ='';
let outputSection = document.getElementById('output');
let outputData = data[data.length - 1];
let newP = document.createElement('p');
newP.textContent = outputData['id'] + " " + outputData['name'] + " "+outputData['occupation'];
outputSection.appendChild(newP);
}
function sortByNameOrOccupation(attribute){
data.sort(function(a, b) {
var nameA = a[attribute].toUpperCase(); // ignore upper and lowercase
var nameB = b[attribute].toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
function displayAfterSort(){
let outputSection = document.getElementById('output');
outputSection.innerHTML = '';
let fragment = document.createDocumentFragment();
data.forEach(function(d) {
let p = document.createElement('p');
p.textContent = d['id'] + " " + d['name'] + " "+d['occupation'];
fragment.appendChild(p);
});
outputSection.appendChild(fragment);
}
window.addEventListener('load', AddDetails, false);
To set the value of the textbox. Do:
$('#//ID of the textbox').val(CreateuserID)
This is assuming that 'CreateuserID' is a string or int
EDIT: Your CreateuserID function will need to return a value.

Javascript: Taking values from a textbox and adding it to the divs

So I have been racking my brain on how to add the a different value from the text box to a different div. So div1 gets the first thing the user typed, div2 gets the second, div3 gets the third, and so on. Everytime a user presses the "Add" button whatever the user typed will be added to one of the Div's above it. Right now I have it to where by pressing "Add" the value of the textbox is put in the first div. How do I create a function that will allow the user to add values to other divs. I assume you need a for loop but I do not know how to tackle it.
Here is my code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<div id="colorme" style = "cursor:pointer" onClick= "highlightLink()"><p id = "doubleStuff" ondblclick = "dubleStuff()">check this out</p></div>
<div id="colorme2" style = "cursor:pointer" onClick= "highlightLink2()"><p id = "doubleStuff2" ondblclick = "dubleStuff2()">check this out</p></div>
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick = "workInfoAdd()">Add</button>
<script>
function highlightLink(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'red';
highL2.style.backgroundColor = 'transparent';
};
function highlightLink2(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'transparent';
highL2.style.backgroundColor = 'red';
};
function dubleStuff(){
var x = "You double clicked it";
document.getElementById('putstuff').innerHTML = x;
};
function dubleStuff2(){
var x = "different stuff";
document.getElementById('putstuff').innerHTML = x;
};
function workInfoAdd(){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {
z.value = "";
}
};
</script>
</body>
</html>
Would something like this work.
var i = document.getElementById('addingInfo');
for(i = 0; i < 4; i++){
document.getElementbyId('workInfo').value = i //or some other variable that specifies the "adding info"
Any assistance would be greatly appreciated. As stated above after everytime the user presses ADD, the value they put into the text box will be added to the subsequent div. First add goes to first div, second goes to second div and so on.
You should probably write something like this:
var divIndex = 0;
function workInfoAdd() {
var z = document.getElementById('workInfo');
var p = document.getElementById('addingInfo' + (divIndex || ''));
if (!p) {
return;
}
if (z.value === null || z.value === "") {
alert('please enter work info');
} else {
p.innerHTML = z.value;
z.value = "";
}
divIndex++;
};
<div id="workInfo1" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo"></p>
</div>
<div id="workInfo12" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo1"></p>
</div>
<div id="workInfo13" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo2"></p>
</div>
<div id="workInfo14" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo3"></p>
</div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type="button" name="addWorkInfo" id="addWorkInfo" onclick="workInfoAdd()">Add</button>
Additionally you can use document.querySelector() for more advanced matching of elements ex.
var p = document.querySelector('.workInfo' + divIndex + ' > p.addingInfo' + divIndex);
Try the below code but remember that this solution should be used if you are going to limit the number of div (i.e only 3 or 4 divs) because if you want unlimited divs you will have to program an if-else statement for each possible div:
// Declare variable
var x = 0;
function workInfoAdd(){
// Increment
x++
// Check increment value
if(x == 1){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else { z.value = "";}
}
// Check increment value
else if(x == 2){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo1').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
// Check increment value
else if(x == 3){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo2').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
}
https://jsfiddle.net/6byvuzxf/
I have created check points as mentioned in my comment before.
Hope this helps.
See if this is what you want. I have added a class for all the p tags which will contain the information after click.
Html
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick ="workInfoAdd()">Add</button>
javascript
function workInfoAdd()
{
var elements = document.getElementsByClassName('addingInfo');
for(i=0;i<elements.length;i++)
{
if(elements[i].innerHTML == "")
{
elements[i].innerHTML = document.getElementById('workInfo').value;
document.getElementById('workInfo').value = "";
return;
}
}
}
http://jsfiddle.net/okLme061/1/

Categories

Resources