Displaying the results of a Javascript function - javascript

I'm trying to get a javascript function to print out, but nothing comes up. Essentially I'm just setting up a basic page of text boxes, radio buttons and checkboxes for users to fill out and the results of those elements will print out to create a basic barebones profile page.
I apologize in advance for any sloppy or obsolete coding, I'm starting out with this stuff (my first semester of classes in web design). I'm assuming I've made a minor error that I'm not catching that's screwing up with the rest of the code, or I'm just plain missing a key line of code.
Here's the code below (Javascript):
`
function validate()
{
dataOut = document.getElementById("profileOut");
var color = document.profileIn.bgcolor.value;
style.backgroundColor = color;
var border = document.profileIn.border.value;
style.border = border;
var name = document.profileIn.name.value;
dataOut.innerHTML = "<h1 id='name'>" name "</p>";
if (document.GetElementById('sportsgames').checked {
dataOut.innerHTML = "<img src='images/sportsgames.jpg' alt='I like sports and games' />";
} else if (document.GetElementById('tvfilm').checked {
dataOut.innerHTML = "<img src='images/tvfilm.jpg' alt='I like tv and film' />";
} else if (document.GetElementById('artlit').checked {
dataOut.innerHTML = "<img src='images/artlit.jpg' alt='I like art and literature' />";
} else {
dataOut.innerHTML = "<img src='images/nothing.jpg' alt='I hate everything' />";
}
var entry1 = document.profileIn.entry1.value;
dataOut.innerHTML = "<p id='para1'>" entry1 "</p>";
document.getElementById("para1").style.color="#0000FF";
var entry2 = document.profileIn.entry2.value;
dataOut.innerHTML = "<p id='para2'>" entry2 "</p>";
document.getElementById("para2").style.color="#FF0000";
var years = document.profileIn.years.value;
dataOut.innerHTML = "<p>I have been practicing this hobby for " + years + " years.</p>";
var music = document.profileIn.music.value;
dataOut.innerHTML = "<p> My favorite music genre is " + music + ".</p>";
var birthday = document.profileIn.birthday.value;
dataOut.innerHTML = "<p>Birthday:" + music + "</p>";
var email = document.profileIn.email.value;
dataOut.innerHTML = "<p> E-Mail:" + music + "</p>";
var website = document.profileIn.website.value;
dataOut.innerHTML = "<p>Website:" + music + "</p>";
document.getElementById('profileOut').innerHTML = profileOut;
}
</script>`
And the HTML code as well:
<body id="profile">
<form id="profileIn" name="profileIn" method="post" onSubmit="return validate()">
<fieldset id ="set1">
<legend>Your Page</legend>
<label for="bgcolor">
<input type="color" id="bgcolor" name="bgcolor" value="#FFFFFF" /> Select a background color<br>
Choose the thickness of the border<br>
<input type="range" id="border" name="border" value="5" min="0" max="10" step="1" /><br>
0 1 2 3 4 5 6 7 8 9 10
</fieldset>
<fieldset id="set2">
<legend>Your Profile</legend>
Enter your name <input type="text" id="name" name="name" /> <br>
Enter your favourite hobby <br>
<input type="radio" id="sportsgames" name="hobby" value="sportsgames">Sports & Games<br>
<input type="radio" id="tvfilm" name="hobby" value="tvfilm">TV & Film<br>
<input type="radio" id="artlit" name="hobby" value="artlit">Art & Literature<br><br>
<label for="entry">What part of that hobby is your favourite?</label><br>
<textarea id="entry1" name="comments1" rows="8" cols="50">Type in here...</textarea><br>
<label for="entry">Which part of that hobby are you best at?</label><br>
<textarea id="entry2" name="comments2" rows="8" cols="50">Type in here...</textarea><br>
How many years have you practiced this hobby? <br>
<input id="years" type="number" name="years" value="0" min="1" max="100" /><br>
What's your favorite genre of music? <br>
<select id="music">
<option value="Rock">Rock<option>
<option value="Pop">Pop<option>
<option value="Country">Country<option>
<option value="R&B">R&B<option>
<option value="Classical">Classical<option>
</select>
</fieldset>
<fieldset id="set3">
<legend>Your Info</legend>
Birthday <input id="birthday" type="date" name="date" /> <br>
Email <input id="email" name="email" type="email" placeholder="example#gmail.com" /> <br>
Website <input id="website" name="website" type="url" placeholder="www.example.com" />
</fieldset>
<fieldset id="set4">
<input class="btn" type="submit" id="btn1" value="Press to Continue" />
<input class="btn" type="reset" id="btn2" value="Press to Clear" />
</fieldset>
</form>
<section id="profileOut"> </section>
Any help's much appreciated, thanks guys!

Lines like below are incorrect. In Javascript, appending should be done with +.
dataOut.innerHTML = "<h1 id='name'>" name "</p>";
should be
dataOut.innerHTML = "<h1 id='name'>" + name + "</p>";

do you get any errors in your console? (F12 in the browser). Also, the return isn't necessary as far as I know:
onSubmit="return validate()">
can just be:
onSubmit="validate()">

Always check your browser console for errors. A cursory glance revealed:
dataOut.innerHTML = "<p id='para1'>" entry1 "</p>";
Missing concatenation operators here.
In general, though, you seem to be repeatedly overwriting dataOut.innerHTML, which - assuming your code were correct - would just result in "Website: blah" and nothing else. Consider creating an element with createElement, adding text to it (createTextNode, appendChild) and then inserting it.

First Error:
dataOut.innerHTML = "<h1 id='name'>"+name+"</p>"; //Missing +
Second to Forth
if (document.GetElementById('sportsgames').checked) //Missing )
Fifth Error:
dataOut.innerHTML = "<p id='para1'>"+entry1+"</p>"; //Missing +
Sixth Error:
dataOut.innerHTML = "<p id='para2'>"+entry2+"</p>"; //Missing +

You forgot to concatenate (+) some of your variables to your strings, like name, entry1, entry2 so on
Always check your Developer Console if some of your JavaScript is not working.

Related

How do I make a calc with logs information under?

I have build calc and I wanted to add a logs for calculator but my script is not working. Someone see
where is mistake? I am learning for a few days and decided to make a project but after many hours of looking at code, browsing everything in internet I decided to ask you. I know there are probably many easier projects for a beginner, but I don't want to abandon a project before finishing.
Here is js script.
funtion changeContent() {
var x = document.getElementById('textarea');
var liczba11 = document.getElementById('liczba1');
var liczbaa2 = document.getElementById('liczba2');
x.value = x.value + liczba11.value + liczbaa2.value + '\r\n';
}
<form action="">
<fieldset>
<legend>Sumowanie dwóch liczb - wprowadź dane</legend>
<p>Liczba1 <input type="text" name="liczba1" id="liczba1" /></p>
<p>Liczba2 <input type="text" name="liczba2" id="liczba2" /></p>
<p>Wynik : <input type="text" name="wynik" readonly="readonly" /></p>
<button
onclick="this.form.elements['wynik'].value = parseFloat(this.form.elements['liczba1'].value) + parseFloat(this.form.elements['liczba2'].value); return false"
>
Oblicz
</button>
</fieldset>
</form>
<form action="">
<div>
<textarea
name="uwagi"
id="textarea"
cols="30"
rows="3"
value="text"
disabled="disabled"
></textarea>
</div>
</form>
<button onclick="changeContent()">Click to change</button>
It's really difficult to implement, calculation in programming language. There's so mutch anything to handle, priority, divizion by zero. With the power of programming language there's eval function in javascript it can be easy to do.
const btn = document.querySelector('button')
const str = document.querySelector('#liczba1')
const result = document.querySelector('#r')
btn.addEventListener('click', function(e){
e.preventDefault()
if ( /^[0-9\*\/\-\+\(\)]+$/.test(str.value))
{
result.innerText = eval(str.value) // Be awaire of using eval function
console.log(eval(str.value))
} else
result.innerText = 'Error, type missmatch'
})
<fieldset>
<legend>String of calculation</legend>
<p>Example: 3+4 OR 4*3 OR some complicate 7895*265+(423-(4/65+3))</p>
<p><input type="text" name="liczba1" id="liczba1"/></p>
<p>Result <strong id="r"></strong> </p>
<button>
Result
</button>
</fieldset>
IMPORTANT
Check intentionnally using eval function.
Instead of using the onclick handler to hold the code, you can run a function from it.
You also misspelled function.
I added the logging code to the runCalc function so that it all happens at the same time, no extra button needed.
function runCalc(){
liczba11 = document.getElementById('liczba1');
liczbaa2 = document.getElementById('liczba2');
wynik = document.getElementById('wynik');
logs = document.getElementById('textarea');
wynik.value = parseFloat(liczba11.value) + parseFloat(liczbaa2.value);
logs.value += parseFloat(liczba11.value) + " + " + parseFloat(liczbaa2.value) + " = " + wynik.value + "\r\n";
}
<form action="">
<fieldset>
<legend>Sumowanie dwóch liczb - wprowadź dane</legend>
<p>Liczba1 <input type="text" name="liczba1" id="liczba1" /></p>
<p>Liczba2 <input type="text" name="liczba2" id="liczba2" /></p>
<p>Wynik : <input type="text" name="wynik" id="wynik" readonly="readonly" /></p>
<button type="button"
onclick="runCalc()"
>
Oblicz
</button>
</fieldset>
</form>
<form action="">
<div>
<textarea
name="uwagi"
id="textarea"
cols="30"
rows="3"
value="text"
disabled="disabled"
></textarea>
</div>
</form>

Entering multiple records on same HTML page

I am creating a JS form where i need 3 inputs from user and after typing the 3 inputs , on clicking 'Add record' button ,it should display them on the same page one after another (line by line) for every button click. With my code, it is writing every new input entry in the same line and not next line. How do i do it ?
My result:
Andrew Arts 2007 Evelyn Computers 2006
Expected result :
Andrew Arts 2007
Evelyn Computers 2006
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
return false;
}
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<p id='f1'></p>
</body>
You use a <br> tag to break the line inside a <p> tag.
You just have to make a small change in your function :
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
document.getElementById('f1').innerHTML +='<br />'
return false;
}
If you're looking to style your form values , it would be good to append <p>tag for each form value . It will require a small change like below :
function doSubmit() {
document.getElementById('form-value').innerHTML += '<p>'+ document.myform.name.value + " " + document.myform.major.value + " " + document.myform.year.value + " " + "</p>";
return false;
}
Your HTML :
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30"
type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="form-value">
</div>
I would suggest creating a new p element for every submitted input. You also don't want to store the user input into the innerHTML, because it can lead to cross-site scripting attacks. To prevent this, you can use innerText instead. Here is an example of how you can achieve all that with your code:
function doSubmit() {
const newInputParagraph = document.createElement("p");
newInputParagraph.innerText += document.myform.name.value + " ";
newInputParagraph.innerText += document.myform.major.value + " ";
newInputParagraph.innerText += document.myform.year.value + " ";
document.getElementById("inputs").appendChild(newInputParagraph);
}
And you need to add container for input results (simple div) to your markup, for example like this:
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="inputs"></div>

JavaScript - outputting multiple arrays of submitted user input on screen

I'm trying to take the user input of the form and on submit, populate a space in the DOM with the input. I also want to be able to print multiple user inputs in the same space (i.e. something like printing an array of user inputs onto the page each time a user submits)
function create_list_markup() {
document.getElementById("display").innerHTML =
"<h1 class='list-title'>"
+ document.getElementById('title').value + "</h1>"
+ "<br><br>"
+ "Recipient: "
+ document.getElementById('recipient').value
+ "<br>" + "Link: "
+ document.getElementById('link').value
+ "<br>"
+ "Price: "
+ document.getElementById('price').value;
}
function create_gift_markup(gift) {
const markup = `
<p>
<span class=''> ${gift.title} </span><br>
<span class=''> ${gift.recipient} </span><br>
<span class=''> ${gift.link} </span><br>
<span class=''> ${gift.price} </span><br>
</p>`;
return markup;
}
function insert_gifts(gift_markup) {
const gift_fragment = document.createDocumentFragment();
gift_markup.forEach(function __append_markup_to_docfrag(markup) {
let container_element = document.createElement('span');
container_element.insertAdjacentHTML('afterbegin', markup);
gift_fragment.appendChild(container_element.firstElementChild);
});
document.body.appendChild(gift_fragment);
}
function create_list_markup() {
const gift_markup = create_gift_markup(gifts)
insert_gifts(gift_markup)
}
The create_list_markup function works and prints out the user input to the screen (in conjunction with a div with an id of "display"), however I wanted to print multiple outputs to the same space, so I wrote the rest of the code. That's the stuff that doesn't work.
Here is the markup:
<h1>Christmas Gifts</h1>
<form class="gift-form" name="giftform" action="" id="gift">
<h2>Gift Submit Form</h2>
<label>Title of Gift</label>
<input type="text" name="title" value="" placeholder="Enter a title" id="title">
<label>Recipient of Gift</label>
<input type="text" name="recipient" value="" placeholder="Enter a recipient" id="recipient">
<label>Link to Gift Picture</label>
<input type="text" name="link" value="" placeholder="Enter link to picture" id="link">
<label>Price of Gift</label>
<input type="text" name="price" value="" placeholder="Enter price" id="price">
<button type="button" value="Submit" onClick="create_list_markup()">Submit</button>
</form>
<div class="list-box">
<h2>Gift List</h2>
<div id="display"></div>
</div>

Autofocus on dynamically added textboxes - html/javascript

i am adding the text boxes dynamically to the form.
following is the code:
<html lang="en-US">
<head>
<meta name="referrer" content="origin">
<script>
var counter = 0;
var limit = 50;
function addInput(divName, arrName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
var af = "autofocus"
newdiv.innerHTML = "<input type='text' name='" + arrName + "[]' required autofocus=" + af + ">";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
</head>
<body>
<form action="part.php" align="center" method="POST">
<div id = "dynamicInputHolder_1">
<b>Emotion </b><input type="text" value="" name="emotion" id="emotion" class="generatedEmotion" readonly>
<input type="hidden" value="" name="uniqueID" id="uniqueID">
<div id="dynamicInput_1">
<textarea rows="5" cols="50" readonly class="floating-box">
John arrived at Sally's house to pick her up. John and Sally were going to a fancy restaurant that evening for a dinner. John was little nervous because he was going to ask Sally to marry him.</textarea>
</div>
<input type="button" value="Add connecting sentences" onClick="addInput('dynamicInput_1', 'myInputs_1');">
</div>
<br>
</form>
</body>
</html>
I am putting in autofocus="autofocus", but it works only for the first dynamic text box, for other it does not work. Any idea how can i achieve this?
See https://stackoverflow.com/a/47207659/5674976 for a detailed reason for autofocus not working; it only works on page load.
Use elementName.focus()
<html lang="en-US">
<head>
<meta name="referrer" content="origin">
<script>
var counter = 0;
var limit = 50;
function addInput(divName, arrName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
var af = "autofocus"
newdiv.innerHTML = "<input id='my-div-"+counter+"' type='text' name='" + arrName + "[]' required autofocus=" + af + ">";
document.getElementById(divName).appendChild(newdiv);
document.getElementById('my-div-'+counter).focus();
counter++;
}
}
</script>
</head>
<body>
<form action="part.php" align="center" method="POST">
<div id = "dynamicInputHolder_1">
<b>Emotion </b><input type="text" value="" name="emotion" id="emotion" class="generatedEmotion" readonly>
<input type="hidden" value="" name="uniqueID" id="uniqueID">
<div id="dynamicInput_1">
<textarea rows="5" cols="50" readonly class="floating-box">
John arrived at Sally's house to pick her up. John and Sally were going to a fancy restaurant that evening for a dinner. John was little nervous because he was going to ask Sally to marry him.</textarea>
</div>
<input type="button" value="Add connecting sentences" onClick="addInput('dynamicInput_1', 'myInputs_1');">
</div>
<br>
</form>
</body>
</html>
from https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
autofocus HTML5 This Boolean attribute lets you specify that a form
control should have input focus when the page loads, unless the
user overrides it (e.g. by typing in a different control). Only one
form element in a document can have the autofocus attribute, which
is a Boolean.
so you can use autofocus to focus on something (good for server side rendering)
and you need to use javascript if you want to change this after the page is laoded.
Edit:
see #George Campbell answer to how to achieve this: https://stackoverflow.com/a/47207691/6126033
Try to use just "<input type='text' name='" + arrName + "[]' autofocus";
And also ...
$(document).on(<event>, <object>, function(event) {console.log("test"});
(old post, already accepted answer, but anyways....)
try this.
var focusDynForms = function() {
var captureAutoFocus = function (form) {
var el_keys = Object.keys(form.elements);
for(var i = 0; i < el_keys.length; i++) {
var el = form.elements[el_keys[i]];
if (["text","password"].indexOf(el.type)>=0){
if (el.autofocus){
el.focus();
return;
}
}
}
};
var forms = document.querySelectorAll("form");
// dynamically created forms need a helping hand to find focus in life...
forms.forEach(captureAutoFocus);
}
Obviously this only addreses text and password inputs, but you can customize for other types.

using html inside an input tag

I am trying to input a break tag at the end of each line of code so that it doesn't just read all in one line inside the input box.
I have encoded the break tag as i thought that's how you can use html inside of an input box but for some reason it is just showing exactly what i have typed.
Any help to correct this would be much appreciated.
This is what i have so far. I have only encoded one of the break tags for demonstration purposes, just to show you what i have done.
<div data-role="content" id="feedbackcontent">
<form action="MAILTO:bg54wl#student.sunderland.ac.uk" method="post" enctype="text/plain" id="fback">
<label for="fname">Full Name:</label>
<input type="text" name="fname" id="fname" data-clear-btn="true" placeholder="Your Full name..." required>
<label for="email">Email:</label>
<input type="text" name="email" id="email" data-clear-btn="true" placeholder="Your Email Address..." required email>
<label for="comments">Comments (Optional):</label>
<input type="text" name="comments" id="comments" data-clear-btn="true">
<label for="deviceinfo" id="deviceinfo">Device Information:
<input style="height:50px;" readonly name="deviceinfo" id="deviceinformation"/>
</label>
<input type="submit" value="Send">
</form>
</div>
</div><!-- /content -->
<script>
document.addEventListener('deviceready', function(event) {
var content = "";
content += "Version: " + device.cordova + "<br/>";
content += "Platform: " + device.platform + "<br/>";
content += "Device Model: " + device.model + "<br/>";
content += "Platform Version: " + device.version + "<br/>";
content += "UUID: " + device.uuid + "<br/>";
var element = document.getElementById("deviceinformation").value = content;
}, false );
</script>
Input tags completely ignore newlines.
You can use a textarea instead. Textareas preserve whitespace.
<textarea name="theName">
You can have
Multiple lines
In textareas
</textarea>

Categories

Resources