I am learning JS and I am not yet familiar with internal workings. Can someone point out the error in my thinking?
The basic idea is to ask a complex question, construct the answer with JS (to a CSV syntax) and feed it to a textbox. (From here it will be processed to a db.) Example included below: How many children do you have? What is their names and age?
Perhaps, the new element generated by the first button is not added to the document? How to do this, or how to address the value in it?
How can I make the values submitted to previous lines stick in the event of adding a new line. For example 'Jack' and '10' is written to the first line, the user pressed the add new line, than this information should stay in the first line.
Incorrectly working example: The save button stops working if the code in the loop is added.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<p>How many children do you have? What is their names and age?</p>
<input type="text" id="qchildren" />
<div id="qchildren-answer-wrapper"></div>
<button type="button" onclick="addNew()">Add new entry</button>
<button type="button" onclick="save()">Save</button>
<script>
var lines = 0;
function addNew() {
lines++;
document.getElementById("qchildren-answer-wrapper").innerHTML += 'Gyermek neve:<input type="text" id="qchildrenname' + window.lines + '" /> Gyermek eletkora:<input type="text" id="qchildrenage' + window.lines + '" /><br/>';
}
function save() {
var answer = '';
for (var ii = 0; ii < window.lines; ii++) {
answer += document.getElementById('qchildrenname' + ii.toString()).value.toString() + ',' + document.getElementById('qchildrenage' + ii.toString()).value.toString() + ';';
}
document.getElementById("qchildren").value = answer;
}
< /script>
</body>
</html>
=Below code should work (AddNew function changed):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<p>How many children do you have? What is their names and age?</p>
<input type="text" id="qchildren" />
<div id="qchildren-answer-wrapper"></div>
<button type="button" onclick="addNew()">Add new entry</button>
<button type="button" onclick="save()">Save</button>
<script>
var lines=0;
function addNew()
{
lines++;
var newElement = document.createElement("span");
newElement.innerHTML = 'Gyermek neve:<input type="text" id="qchildrenname'+window.lines+'" /> Gyermek eletkora:<input type="text" id="qchildrenage'+window.lines+'" /><br/>';
document.getElementById("qchildren-answer-wrapper").appendChild(newElement);
}
function save()
{
var answer='';
for (var ii=1;ii<=window.lines;ii++)
{
answer+=document.getElementById('qchildrenname'+ii.toString()).value.toString()+','+document.getElementById('qchildrenage'+ii.toString()).value.toString()+';';
}
document.getElementById("qchildren").value=answer;
}
</script>
</body>
</html>
Try code like this:
function addNew()
{
var div = document.createElement('div');
div.innerHTML = 'Gyermek neve:<input type="text" id="qchildrenname'+window.lines+'" /> Gyermek eletkora:<input type="text" id="qchildrenage'+window.lines+'" /><br/>';
document.getElementById("qchildren-answer-wrapper").appendChild(div );
lines++;
}
Demo: http://jsfiddle.net/JByVg/8/
What happens in your case is that all previously created elements are recreated again because element.innerHTML += "some_html" is equal to element.innerHTML = element.innerHTML + "some_html" or, more clear, I suppose, var oldHtml = element.innerHTML;element.innerHTML = ""; element.innerHTML = oldHtml + "some_html"
Browser does not populate value="..." entered by user when you do var oldHtml = element.innerHTML and after += you have old elements recreated without values entered by user. At the same time, appendChild does not recreate old elements.
This example demonstrates how .innerHTML returns only initial HTML (I've added value="test" to your qchildrenname element code)
Related
I'm trying to create an HTML page that allows the user to input integers into a stored array using a button and then search that array for the inputted integers using another button. I am very confused and new to coding so any help would be much appreciated!
Try this out
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="data">[]</p>
<input id="inputNumber" value="0"/> <button id="pushBtn" onclick="push()">PUSH</button>
<input id="findNumber" value="0"/> <button id="pushBtn" onclick="find()">FIND</button>
<script>
var data = [];
function push(e) {
var toAdd = document.getElementById("inputNumber").value;
data.push(toAdd);
refresh();
}
function find(e) {
var toFind = document.getElementById("findNumber").value;
for(var i=0; i < data.length; i++){
if(data[i]==toFind) return alert("found at "+i);
}
return alert("couldn't find that number");
}
function refresh(){
document.getElementById("data").innerHTML = data;
}
</script>
</body>
</html>
Basically, I'm just using using the buttons to call the functions within the script that handles insertion and query for me. Additionally a refresh function is there to refresh the newly added data
So here is the problem.I want user to enter number of index in text box for array. After taking index i want user to enter value from a prompt box to store in that array but that prompt box is coming over and over again and i have to click on button every time to take input
Here is the code
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<label> Enter Number of Records </label>
<input type="text" id="t1">
<input type="button" value="Enter" onClick="record()">
<h1 id="demo"></h1>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Java Script:
var data = document.getElementById("t1").value;
function record(){
var crap = new Array(data);
for(var i=0;i<crap.length;i++){
crap[i] = prompt("Add something in my array","");
document.getElementById("demo").innerHTML += crap[i]+"<br>";
}
In your case, you are retrieving data outside the function. Thus its value will be 'undefined' and the crap will became the array of one value that is undefined. So crap.length will be always 1.
Try this:
function record(){
var data = document.getElementById("t1").value;
var crap = []
if(crap != undefined)
for(var i=0;i<data;i++){
var tmp = prompt("Add something in my array","");
crap.push(tmp);
document.getElementById("demo").innerHTML += crap[i]+"<br>";
}
}
Enjoy coding ....
Try this,This will solve your issue.
You are just declaring an array named crap, and you are trying to get the crap.length even before the array is filled, so you are getting the issue. Since data has your value try looping with data value.
function record(){
data = document.getElementById("t1").value;
var crap = new Array(parseInt(data)); // you should take data here, since crap is empty at this point.
console.log(data)
for(var i=0;i<data;i++){
crap[i] = prompt("Add something in my array","");
document.getElementById("demo").innerHTML += crap[i]+"<br>";
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<label> Enter Number of Records </label>
<input type="text" id="t1">
<input type="button" value="Enter" onClick="record()">
<h1 id="demo"></h1>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Please run the code snippet and check the answer.
I'm making a small website as a test. Very new to JavaScript and HTML forms so I thought i'd throw myself into what I consider to be the deep end and give it a go.
I'm trying to get an interger to be displayed on the page, that is the result of a few calculations.
I want to find the difference between the first number (current value), and the second number (desired value) and then divide that number by 25 and store that as a variable. I then want to display that variable inside a message.
My current HTML :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<form>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<input type="submit" onclick="calculate()">
</form>
<script src="js/main.js"></script>
</body>
</html>
My current JavaScript :
function calculate() {
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
var difference = desiredRating - currentRating;
var gamesToPlay = difference / 25;
document.write("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
You are 99% there. All you have to do is change
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
into
var currentRating = parseInt(document.getElementById("currentRating").value);
var desiredRating = parseInt(document.getElementById("desiredRating").value);
The way you had it, those variables just held the HTML (technically, DOM) elements themselves, and not the values that were in them. This gets the values and then turns them into integers so you can do math with them. If you do this, your site do exactly what you want it to do.
Be careful:
var currentRating = document.getElementById("currentRating").value;
is a String (text) value... to be sure of int value you can do
try{
var currentRatingInt = parseInt(currentRating);
}catch(e){
alert(currentRating + " is not an integer");
}
If you like to display result in page you can use a DIV with and id and do:
document.getElementById("idOfYourDiv").innerHTML = "What you like to display in div";
hope this code will help :
html :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<div>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<button onclick="calculate();">Calculate</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
javascript :
function calculate() {
var currentRating = document.getElementById("currentRating").value;
var desiredRating = document.getElementById("desiredRating").value;
var gamesToPlay = (desiredRating - currentRating) / 25;
gamesToPlay = Math.abs( parseInt(gamesToPlay) );
alert("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
Subtract first field from the other, and if the value is not greater than 0 multiply by -1.
Divide that by 25.
Here is my test code, extracted from a form I'm building:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
function ini(){
console.log("Element dump:");
var elem = document.querySelector('form[name="form"] input[name="dataNasc"]');
for(var i in elem){
console.log(i+":"+elem[i]);
}
console.log("Form element dump:");
var Form = document.forms["form"];
var input = Form.dataNasc;
for(var i in input){
console.log(i+":"+input[i]);
}
}
</script>
<title>Untitled Document</title>
</head>
<body onload="ini();">
<form name="form" action="" method="post">
<label for="dataNasc">Data Nasc.</label>
<input type="text" name="dataNasc" maxlength="10" required="required" tipo="data" value="{dataNasc}" />
</form>
</body>
</html>
In both cases that I pick the input tag (ini function), the attribute "tipo" is not listed. The property returns "undefined". It seams an object is created using the information in the tag, not a conversion "tag to object". Using outerHTML, I can do it manually (hope this property is cross-browser), but I'm wondering if there is a way using JavaScript resources... How can I do it?
Once you have a reference to the element, you can iterate over its attributes NamedNodeMap to discover all of its attributes. So for example and assuming there will only be one matching element matching your selector...
var elt=document.querySelector('form[name="form"] input[name="dataNasc"]'),
attrs=elt ? elt.attributes : [];
for(var i=0; i<attrs.length; i++) {
console.log('attr "'+attrs[i].name+'" contains "'+attrs[i].value+'"');
}
try this:
function ini(){
console.log("Element dump:");
var elem = document.querySelector('form[name="form"] input[name="dataNasc"]');
for(var i in elem){
console.log(i+":"+elem[i]);
}
console.log("Form element dump:");
var Form = document.forms["form"];
var input = Form.dataNasc;
var myObj = {};
for(var i in input){
myObj[i] = input[i];
}
}
This code is attempting to highlight (by adding 'bold' tag) some characters that are in the HTML body. (These are specified in the JS function)
But instead of the text becoming bold, I get the 'bold' tag as the result in the html page that is getting rendered.
While I want some thing like
This is a test message
I get
This is a test <b>message</>
Any help would be awesome.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; child<len; child++){
if (children[child].nodeType === 3){ // textnode
var highLight = new Array('abcd', 'edge', 'rss feeds');
var contents = children[child].nodeValue;
var output = contents;
for(var i =0;i<highLight.length;i++){
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
The problem is that you are putting HTML in to a text node, so it is being evaluated strictly as text. One easy fix would be to simply operate on the innerHTML of the body element, like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var highLight = ['abcd', 'edge', 'rss feeds'],
contents = document.body.innerHTML;
for( i = 0; i < highLight.length; i++ ){
contents = delimiter(contents, highLight[i]);
}
document.body.innerHTML = contents;
}
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
A textNode cannot have child elements so it needs to be replaced, one way;
Replace
children[child].nodeValue = output;
With
var n = document.createElement("span");
n.innerHTML = output;
children[child].parentNode.replaceChild(n, children[child]);