I'm having issues getting input from a document and outputting it using the this keyword. When outright calling the object and attribute followed by .value I didn't encounter a problem, but trying to use this has become a complication. Calling person.display results in undefined areas. I've looked for how to get a value for this and I'm starting to get further away from the solution. Could someone provide help?
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Lesson 11 Lab</title>
</head>
<body>
<label for="first_name">Enter first name:</label><br>
<input type="text" id="first_name"><br><br>
<label for="last_name">Enter last name:</label><br>
<input type="text" id="last_name"><br><br>
<label for="course">Enter your course:</label><br>
<input type="text" id="course"><br><br>
<label for="section">Enter your section:</label><br>
<input type="text" id="section"><br><br>
<label for="role">Enter your role:</label><br>
<input type="text" id="role"><br><br>
<input type="button" id="button1" value="Show: Person/Class/Role"><br>
<p id="fill_in"></p>
<script src="person_java.js"></script>
</body>
</html>
JavaScript
let person = {
first_name: document.getElementById("first_name"),
last_name: document.getElementById("last_name"),
course: document.getElementById("course"),
section: document.getElementById("section"),
role: document.getElementById("role"),
display: function() {
document.getElementById("fill_in").innerHTML = this.first_name + " " + this.last_name + " has the role of " + this.role + " in " + this.course + " section " + this.section + ".";
}
};
document.getElementById("button1").addEventListener("click", );
You need to reference the value when you are building the string. You need to call your function onclick. With those changes, your code will work fine.
let person = {
first_name: document.getElementById("first_name"),
last_name: document.getElementById("last_name"),
course: document.getElementById("course"),
section: document.getElementById("section"),
role: document.getElementById("role"),
display: function() {
document.getElementById("fill_in").innerHTML = this.first_name.value + " " + this.last_name.value + " has the role of " + this.role.value + " in " + this.course.value + " section " + this.section.value + ".";
}
};
document.getElementById("button1").addEventListener("click", function (){
person.display();
});
<label for="first_name">Enter first name:</label><br>
<input type="text" id="first_name"><br><br>
<label for="last_name">Enter last name:</label><br>
<input type="text" id="last_name"><br><br>
<label for="course">Enter your course:</label><br>
<input type="text" id="course"><br><br>
<label for="section">Enter your section:</label><br>
<input type="text" id="section"><br><br>
<label for="role">Enter your role:</label><br>
<input type="text" id="role"><br><br>
<input type="button" id="button1" value="Show: Person/Class/Role"><br>
<p id="fill_in"></p>
Related
The title pretty much says everything.
I'm making a form that will return your first name and surname with city in a quote using div class = "well". I'm now stuck for some hours now trying to figure out what I'm doing wrong.
<script> /* get info from inputs and add it to a quote. */
function FillInfo(){
var fname = document.forms ["SIgnUpForm"] ["fname"].value;
var sname = document.forms ["SIgnUpForm"] ["sname"].value;
var city = document.forms ["SIgnUpForm"] ["city"].value;
document.getElementById("info").innerHTML = "Thank you" + " " + fname + " " + sname + "from" + " " + city + "." + " " + "You are now being considered as our next adventurer. Good luck!";
}
</script>
and in body is:
<div class="heading2">
<div class="container2">
<p>Do you want to travel troughout space? Then fill out our form!</p><br>
<form name="SignUpForm" onsubmit="return validateForm()" method="get">
<input type="text" name="fname" placeholder="First name" required><br>
<input type="text" name="sname" placeholder="Last name" required><br>
<input type="text" name="city" placeholder="City" required><br><br>
<div id="info" class="well"></div>
<button class="otherpage" onclick="FillInfo();">Submit</button><br><br>
Return
</form>
</div>
</div>
I expect it to write down the quote when i click the submit button, yet in return i get this :
Uncaught TypeError: Cannot read property 'fname' of undefined
at FillInfo (things i put into inputs name, city)
at HTMLButtonElement.onclick (things i put into inputs name, city)
I think you just mistyped the form name
Your Html code: SignUpForm
Your Javascript code :SIgnUpForm
I fixed it and it worked for me.
I used formData to get a form object, then form.get(name) to get the content.
It's a more elegant way to get your content.
I also replaced your button with a input type="button", because it caused a refresh of the page.
note: it doesn't work on IE & safari for iOS
function FillInfo(){
let f = new FormData(document.querySelector('form'));
var fname = f.get("fname");
var sname = f.get("sname");
var city = f.get("city");
document.getElementById("info").innerHTML = "Thank you" + " " + fname + " " + sname + " from " + " " + city + "." + " " + "You are now being considered as our next adventurer. Good luck!";
}
<div class="heading2">
<div class="container2">
<p>Do you want to travel troughout space? Then fill out our form!</p><br>
<form name="SignUpForm" method="get">
<input type="text" name="fname" placeholder="First name" required><br>
<input type="text" name="sname" placeholder="Last name" required><br>
<input type="text" name="city" placeholder="City" required><br><br>
<div id="info" class="well"></div>
<input type="button" class="otherpage" onclick="FillInfo();" value="Submit" /><br><br>
Return
</form>
</div>
</div>
Why? These questions keep coming up about undefined errors in JavaScript when accessing the DOM. Please, ensure the DOM is ready before accessing it. Just putting your scripts after your html won't assure you of that.
Though the "SIgnUpForm" name will give you errors and is corrected here, it doesn't solve the entire problem. Different processor and network speeds and browser mechanisms may result in you having an undefined property error if you don't ensure the Document Object Model (DOM) is ready before you access elements in the html document.
<script> /* get info from inputs and add it to a quote. */
window.onload = function () {
function FillInfo(){
var fname = document.forms ["SignUpForm"] ["fname"].value;
var sname = document.forms ["SignUpForm"] ["sname"].value;
var city = document.forms ["SignUpForm"] ["city"].value;
document.getElementById("info").innerHTML = "Thank you" + " " + fname + " " + sname + "from" + " " + city + "." + " " + "You are now being considered as our next adventurer. Good luck!";
}
});
</script>
Also, consider using jQuery's $(document).ready() method for cross browser compatibility.
I just modify code, it's working in all browsers:
<script> /* get info from inputs and add it to a quote. */
function FillInfo(){
let form = document.querySelector('form');
var fname = form.elements["fname"];
var sname = form.elements["sname"];
var city = form.elements["city"];
document.getElementById("info").innerHTML = "Thank you" + " " + fname.value + " " + sname.value + " from " + " " + city.value + "." + " " + "You are now being considered as our next adventurer. Good luck!";
return false;
}
</script>
<div class="heading2">
<div class="container2">
<p>Do you want to travel troughout space? Then fill out our form!</p><br>
<form name="SignUpForm" onsubmit="return validateForm()" method="get">
<input type="text" name="fname" placeholder="First name" required><br>
<input type="text" name="sname" placeholder="Last name" required><br>
<input type="text" name="city" placeholder="City" required><br><br>
<div id="info" class="well"></div>
<button class="otherpage" type="button" onclick="FillInfo();">Submit</button><br><br>
Return
</form>
</div>
</div>
Can someone help me get closer to doing what I am trying to do here? I'm very new at html/javascript (obviously) and really don't know how to ask what I want.
I'm just trying make a template maker for craigslist. Make an easy to use html page to send to people and have them fill in the input fields and have it spit out the html to post into the body of the CL posting block.
Any direction/guidance would be appreciated. I've already spent about 3 hours on this and now don't know what to do.
Thanks!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br>
<html xmlns="http://www.w3.org/1999/xhtml"><br>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Craigslist Ad Builder</title>
<style type="text/css">
body {margin: 30px;}
</style>
<body style="margin: 10; padding: 10;"><br>
<!--
<script type="text/javascript">
function multiplyBy()
{
var numOne = document.getElementById("length").value;
var numTwo = document.getElementById("width").value;
var numOne = varLength.value;
var numTwo = varWidth.value;
}
function multiplyFunction ()
{
var sqftResult = numOne.value * numTwo.value;
console.log(sqftResult);
document.getElementById("result").innerHTML = sqftResult;
}
</script>
-->
<script>
function scrHTML(){
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var price = document.getElementById("price").value;
var bed = document.getElementById("bedrooms").value;
var bath = document.getElementById("bathrooms").value;
var model = document.getElementById("model").value;
var length = document.getElementById("length").value;
var width = document.getElementById("width").value;
var sqft = document.getElementById("sqft").value;
var sections = document.getElementById("sections").value;
var newused = document.getElementById("new-used").value;
var feature1 = document.getElementById("featureOne").value;
var feature2 = document.getElementById("featureTwo").value;
var feature3 = document.getElementById("featureThree").value;
var feature4 = document.getElementById("featureFour").value;
var feature5 = document.getElementById("featureFive").value;
var link = document.getElementById("link").value;
var htmlOutput = document.getElementById("htmlOutput");
// htmlOutput.value = "<p> <b><u><h1>Contact info:</u></b> <br> <b>"+ name +" | "+ phone +" </h1></b></p><hr><h1>"+title+"</h1><h2>31905 IH 10 West Boerne TX 78006</h2><h2> Sale By: Agent/Broker</h2><h2>$"+price+"</h2><p><b><big><u>KEY FEATURES</u></big></b><br><b>Sq Footage: </b> " + SQFT + " sqft <br><b>Bedrooms: </b>"+beds+" Bed(s)<br><b>Bathrooms: </b>"+baths+" Bath(s)<br><b>Property Categoty: </b>"+newused+"<br><b>Manufacturer: </b>Oak Creek Homes<br><b>Width: </b>"+width+"<br><b>Length: </b>"+length+"<br><br><b><u>OTHER DETAILS AVAILABLE</u></b><hr><h2><b>"+newused+" 2017 Mobile Home from Oak Creek Homes<br>"+model+"</b><b><h3>Special Online Pricing - contact "+ name +" at "+phone+" for pricing sheet and more info!</b></h3><hr><u><b>Features that come STANDARD:</u></b><ul><li>"+feature1+"</li><li>"+feature2+"</li><li>"+feature3+"</li><li>"+feature4+"</li><li>"+feature5+"</li></ul><hr><b><h2>All this for only $"+price+" - call "+name+" at "+phone+" for more info or to come see the house!</b></h2><hr><ul><li>**Price does not include delivery, setup, or A/C</li></ul><hr>Additional Links: "+ link +"<hr><br><br>mobile home, manufactured home, modular home, tiny home, tiny house, cheap house, cheap home, palm harbor, clayton homes, palm harbor homes, titan direct mobile home, oak creek home, oak creek homes, mobile homes texas, mobile home san antonio, manufactured home san antonio, modular home texas, repo home, repossesssed home, foreclosure, foreclosed, cheap home, cheap house, used home, used house, single wide, double wide, triple wide, titan factory direct";
htmlOutput.value = link
}
</head>
</script>
<form>
Posting Title<br>
<input type="text" name="title" id="title" /><br>
<br>
Name:
<input type="text" name="name" id="name" /><br>
Phone:
<input type="text" name="phone" id="phone" /><br>
Price:
<input type="text" name="price" id="price" /><br>
Bedrooms:
<input type="text" name="bedrooms" id="bedrooms" /><br>
Bathrooms:
<input type="text" name="bathrooms" id="bathrooms" /><br>
Model:
<input type="text" name="model" id="model" /><br>
Length:
<input type="text" name="length" id="length" /><br>
Width:
<input type="text" name="width" id="width" /><br>
Square Feet:
<input type="text" name="sqft" id="sqft" /><br>
Single or Double:
<input type="text" name="sections" id="sections" /><br>
New or Used:
<input type="text" name="new-used" id="new-used" /><br>
Feature 1:
<input type="text" name="featureOne" id="featureOne" /><br>
Feature 2:
<input type="text" name="featureTwo" id="featureTwo" /><br>
Feature 3:
<input type="text" name="featureThree" id="featureThree" /><br>
Feature 4:
<input type="text" name="featureFour" id="featureFour" /><br>
Feature 5:
<input type="text" name="featureFive" id="featureFive" /><br>
Link:
<input type="text" name="link" id="link" /><br>
<input type="button" value="Generate HTML" onclick= "scrHTML()" id="txtOutput" />
<input type="text" id="htmlOutput" />
</form>
</body>
</html>
Maybe this is what you are looking for. I've added a hidden div which will serve as the result container. When the user clicks the button the form will hide and the container with the output will be shown.
I've also cleaned up your code a bit.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Craigslist Ad Builder</title>
<script>
function scrHTML(){
var resultDiv = document.getElementById("result");
var formDiv = document.getElementsByTagName("form")[0];
// the input values
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
// etc..
// here you can put your result html
resultDiv.innerHTML = "<p>" + name + "<br/>" + phone + "</p>";
// hide the form and display the result div
formDiv.style.display = "none";
resultDiv.style.display = "block";
}
</script>
</head>
<body>
<form>
Name:
<input type="text" name="name" id="name" /><br>
Phone:
<input type="text" name="phone" id="phone" /><br>
<input type="button" value="Generate HTML" onclick="scrHTML()" id="txtOutput" />
</form>
<div id="result" style="display: none"> </div>
</body>
</html>
As you can see, the basic HTML structure should be like this:
<html>
<head>
<script></script>
</head>
<body>
<!-- content here -->
</body>
</html>
Thank you for the answers - below is what I've decided to use as the best answer.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br>
<html xmlns="http://www.w3.org/1999/xhtml"><br>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Craigslist Ad Builder</title>
<style type="text/css">
body {margin: 30px;}
</style>
<script type="text/javascript">
<!--
function multiplyBy() {
var numOne = document.getElementById("length").value;
var numTwo = document.getElementById("width").value;
var numOne = varLength.value;
var numTwo = varWidth.value;
}
function multiplyFunction() {
var sqftResult = numOne.value * numTwo.value;
console.log(sqftResult);
document.getElementById("result").innerHTML = sqftResult;
}
function scrHTML() {
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var price = document.getElementById("price").value;
var beds = document.getElementById("bedrooms").value;
var baths = document.getElementById("bathrooms").value;
var model = document.getElementById("model").value;
var length = document.getElementById("length").value;
var width = document.getElementById("width").value;
var sqft = document.getElementById("sqft").value;
var sections = document.getElementById("sections").value;
var newused = document.getElementById("new-used").value;
var feature1 = document.getElementById("featureOne").value;
var feature2 = document.getElementById("featureTwo").value;
var feature3 = document.getElementById("featureThree").value;
var feature4 = document.getElementById("featureFour").value;
var feature5 = document.getElementById("featureFive").value;
var link = document.getElementById("link").value;
var htmlOutput = document.getElementById("htmlOutput");
htmlOutput.value = "<p> <b><u><h1>Contact info:</u></b> <br> " +
"<b>" + name + " | " + phone + " </h1></b></p>" +
"<hr>" +
"<h1>" + title + "</h1>" +
"<h2>31905 IH 10 West Boerne TX 78006</h2>" +
"<h2> Sale By: Agent/Broker</h2>" +
"<h2>$" + price + "</h2>" +
"<p><b><big><u>KEY FEATURES</u></big></b><br>" +
"<b>Sq Footage: </b> " + sqft + " sqft <br>" +
"<b>Bedrooms: </b>" + beds + " Bed(s)<br>" +
"<b>Bathrooms: </b>" + baths + " Bath(s)<br>" +
"<b>Property Category: </b>" + newused + "<br>" +
"<b>Manufacturer: </b>Oak Creek Homes<br>" +
"<b>Width: </b>" + width + "<br>" +
"<b>Length: </b>" + length + "<br><br>" +
"<b><u>OTHER DETAILS AVAILABLE</u></b>" +
"<hr>" +
"<h2><b>" + newused + " 2017 Mobile Home from Oak Creek Homes<br>" + model + "</b>" +
"<h3><b>Special Online Pricing - contact " + name + " at " + phone + " for pricing sheet and more info!</b></h3>" +
"<hr>" +
"<u><b>Features that come STANDARD:</b></u>" +
"<ul>" +
"<li>" + feature1 + "</li>" +
"<li>" + feature2 + "</li>" +
"<li>" + feature3 + "</li>" +
"<li>" + feature4 + "</li>" +
"<li>" + feature5 + "</li>" +
"</ul>" +
"<hr>" +
"<b><h2>All this for only $" + price + " - call " + name + " at " + phone + " for more info or to come see the house!</b></h2><hr>" +
"<ul>" +
"<li>**Price does not include delivery, setup, or A/C</li>" +
"</ul>" +
"<hr>" +
"Additional Links: " + link + "<hr><br><br>" +
"mobile home, manufactured home, modular home, tiny home, tiny house, cheap house, cheap home, palm harbor, clayton homes, palm harbor homes, titan direct mobile home, oak creek home, oak creek homes, mobile homes texas, mobile home san antonio, manufactured home san antonio, modular home texas, repo home, repossesssed home, foreclosure, foreclosed, cheap home, cheap house, used home, used house, single wide, double wide, triple wide, titan factory direct";
}
//-->
</script>
</head>
<body style="margin: 10; padding: 10;"><br>
<form>
Posting Title<br>
<input type="text" name="title" id="title" /><br>
<br>
Name:
<input type="text" name="name" id="name" /><br>
Phone:
<input type="text" name="phone" id="phone" /><br>
Price:
<input type="text" name="price" id="price" /><br>
Bedrooms:
<input type="text" name="bedrooms" id="bedrooms" /><br>
Bathrooms:
<input type="text" name="bathrooms" id="bathrooms" /><br>
Model:
<input type="text" name="model" id="model" /><br>
Length:
<input type="text" name="length" id="length" /><br>
Width:
<input type="text" name="width" id="width" /><br>
Square Feet:
<input type="text" name="sqft" id="sqft" /><br>
Single or Double:
<input type="text" name="sections" id="sections" /><br>
New or Used:
<input type="text" name="new-used" id="new-used" /><br>
Feature 1:
<input type="text" name="featureOne" id="featureOne" /><br>
Feature 2:
<input type="text" name="featureTwo" id="featureTwo" /><br>
Feature 3:
<input type="text" name="featureThree" id="featureThree" /><br>
Feature 4:
<input type="text" name="featureFour" id="featureFour" /><br>
Feature 5:
<input type="text" name="featureFive" id="featureFive" /><br>
Link:
<input type="text" name="link" id="link" /><br>
<input type="button" value="Generate HTML" onclick= "scrHTML()" id="txtOutput" /><br>
<textarea type="text" id="htmlOutput" style="width:500px;height:300px"></textarea>
</form>
</body>
</html>
<input type="text" name="members[0].name">
<input type="text" name="members[0].address">
Javascript code :
var input_text;
var inputs=document.querySelectorAll("input[type=text],textarea, select");
_.each(inputs, function(e, i) {
var keyName = $(e).attr("name");
if (typeof keyName != "undefined") {
var text = $(e).parent().find('label').text();
if ($(e).is('select')) {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).find(':selected').text() + "</td></tr>";
}
else {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).val() + "</td></tr>";
}
}
});
console.log(input_text);
As You can see, I m getting the values of all the inputs in $(e).val() except those above mentioned inputs.
Those inputs aren't an "array" in the browser. They just use a naming convention in their name which is used by some server-side handling (for instance, in PHP) to organize the form data for you when it's submitted.
I don't know what you mean by "previewing," but you can see the values of those elements by simply looping through the elements of your form (yourForm.elements), or by using yourForm.querySelectorAll("input[type=text]") (or $(yourForm).find("input[type=text]") using jQuery — I missed the jquery tag on your question at first).
Example of theForm.elements:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.elements, function(element) {
if (element.type === "text") {
console.log(element.name + " = " + element.value);
}
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of theForm.querySelectorAll:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.querySelectorAll("input[type=text]"), function(element) {
console.log(element.name + " = " + element.value);
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of $(theForm).find:
$("form input[type=button]").on("click", function() {
var form = document.getElementById("the-form");
$(form).find("input[type=text]").each(function() {
console.log(this.name + " = " + this.value);
});
// Of course, we could have just used `$("#the-form input[type=text]").each`...
// but I was assuming you'd already have `form`
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So many ways to get the input type values using formID
$('#formId input, #formId select').each(
function(index){
var input = $(this);
}
);
OR
var formElements = new Array();
$("form :input").each(function(){
formElements.push($(this));
});
OR
var $form_elements = $("#form_id").find(":input");
hope it helps you.
You can use serializeArray or serialize for it .
$("form").serializeArray();
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Doc
JavaScript:
function validateForm(){
var getNoun = document.formPG.fNoun.value;
var getVerb = document.formPG.fVerb.value;
var getPronoun = document.formPG.fPronoun.value;
var getAdverb = document.formPG.fAdverb.value;
var getAdjective = document.formPG.fAdjective.value;
var getSillyWord = document.formPG.fSillyWord.value;
var getMagic = document.formPG.fMagic.value;
if((getNoun) === ""){
alert("You entered a number value, please enter a Noun.");
document.formPG.fNoun.focus();
document.getElementById('iNoun').style.borderColor = "red";
return false;
}
//write story to [document].html
paragraph = "There was once a " + getAdjective + " magician who roamed the wild terrains of " + getAdverb + ".<br>";
paragraph += "The magician " + getNoun + " cast the mighty spell " + getMagic + " around the " + getSillyWord + ".<br>" + getPronoun + " knew there was only one way to win the war - " + getVerb + ".";
document.write(paragraph);
}
HTML:
<body>
<div class="container">
<h1>Mad Lib</h1>
<form name="formPG" onsubmit="validateForm()" method="post">
Noun: <input type="text" name="fNoun" id="iNoun"><br>
Pronoun: <input type="text" name="fPronoun" id="iPronoun"><br>
Verb: <input type="text" name="fVerb" id="iVerb"><br>
Adverb: <input type="text" name="fAdverb" id="iAdverb"><br>
Adjective: <input type="text" name="fAdjective" id="iAdjective"><br>
Silly Word: <input type="text" name="fSillyWord" id=""iSillyWord"><br>
Magic Spell: <input type="text" name="fMagic" id="iMagic"><br>
<input type="submit" value="submit">
</form>
<br>
<script src="madLib_v2.js"></script>
</div>
</body>
The problem is whenever I hit the "submit" button the page hits the document.getElementById('iNoun').style.borderColor = "red"; and goes away. The page refreshes instantly and the box is only highlighted for a fraction of a second. I want it to stay there until the page is refreshed basically or until they get it correct.
Do with return validateForm() .Then only its prevent page refresh .
Remove the unwanted space and quotes in elements attributes.like id=""iSillyWord"-extra quotes and type="submit "-unwanted space
function validateForm() {
var getNoun = document.formPG.fNoun.value;
var getVerb = document.formPG.fVerb.value;
var getPronoun = document.formPG.fPronoun.value;
var getAdverb = document.formPG.fAdverb.value;
var getAdjective = document.formPG.fAdjective.value;
var getSillyWord = document.formPG.fSillyWord.value;
var getMagic = document.formPG.fMagic.value;
if ((getNoun) === "") {
alert("You entered a number value, please enter a Noun.");
document.formPG.fNoun.focus();
document.getElementById('iNoun').style.borderColor = "red";
return false;
}
//write story to [document].html
paragraph = "There was once a " + getAdjective + " magician who roamed the wild terrains of " + getAdverb + ".<br>";
paragraph += "The magician " + getNoun + " cast the mighty spell " + getMagic + " around the " + getSillyWord + ".<br>" + getPronoun + " knew there was only one way to win the war - " + getVerb + ".";
document.write(paragraph);
}
<body>
<div class="container">
<h1>Mad Lib</h1>
<form name="formPG" onsubmit="return validateForm()" method="post">
Noun: <input type="text" name="fNoun" id="iNoun"><br> Pronoun: <input type="text" name="fPronoun" id="iPronoun"><br> Verb: <input type="text" name="fVerb" id="iVerb"><br> Adverb: <input type="text" name="fAdverb" id="iAdverb"><br> Adjective:
<input type="text" name="fAdjective" id="iAdjective"><br> Silly Word: <input type="text" name="fSillyWord" id="iSillyWord">
<br> Magic Spell: <input type="text " name="fMagic" id="iMagic"><br>
<input type="submit" value="submit">
</form>
<br>
</div>
</body>
prevent the default behavior as the form is getting submitted. Once it is valid use ajax to submit the form
JS
function validateForm(e){
e.preventDefault();
// rest of the code
}
HTML
pass the event object to the function
onsubmit="validateForm(event)"
DEMO
PROBLEM SOLVED
I just started learning JavaScript, and I came across a problem while coding a quick tool for a game that I play. I want users to be able to input a couple of things via an HTML Form and I want the JS Script to take that input and turn it into an SQL.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HabSQL - Online SQL Generator</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel='stylesheet' type='text/css'>
</head>
<body>
<header>Welcome to HabSQL v1.0! The Online Habbo SQL Generator!</header>
<p>HabSQL is strictly for use with Habbo Furniture SQLs and Data. Please enter all necessary information accordingly.</p>
<script src="scripts/habSQL.js"></script>
<form action="javascript:void(habSQL())">
<fieldset>
Furniture Name: <input id="furniName" type="text">
Furniture ID: <input id="furniID" type="number"><br>
SWF File Name: <input id="fileName" type="text"> (Exclude .SWF)<br>
Sprite ID: <input id="spriteID" type="number"> (We recommend that you use the same ID as Furniture ID).
</fieldset>
<fieldset>
Furniture Type: <input id="furniType" type="radio" value="s" name="furniType">Floor <input id="furniType" type="radio" value="i" name="furniType">Wall <input id="furniType" type="radio" value="e" name="furniType">Effect<br>
</fieldset>
<fieldset>
Furniture Width: <input id="furniWidth" type="number" class="dimensions"> Furniture Length: <input id="furniLength" type="number" class="dimensions"> Furniture Height: <input id="furniHeight" type="number" class="dimensions"><br>
Can you stack furniture on it? <input id="canStack" type="radio" value="1" name="canStack">Yes <input id="canStack" type="radio" value="0" name="canStack">No<br>
Can you sit on it? <input id="canSit" type="radio" value="1" name="canSit">Yes <input id="canSit" type="radio" value="0" name="canSit">No<br>
Can you walk on/through it? <input id="canWalk" type="radio" value="1" name="canWalk">Yes <input id="canWalk" type="radio" value="0" name="canWalk">No<br>
Can you recycle it? <input id="canRecycle" type="radio" value="1" name="canRecycle">Yes <input id="canRecycle" type="radio" value="0" name="canRecycle">No<br>
Can you trade it? <input id="canTrade" type="radio" value="1" name="canTrade">Yes <input id="canTrade" type="radio" value="0" name="canTrade">No<br>
Can you sell it on the Marketplace? <input id="canSell" type="radio" value="1" name="canSell">Yes <input id="canSell" type="radio" value="0" name="canSell">No<br>
Can you give it to someone as a gift? <input id="canGive" type="radio" value="1" name="canGive">Yes <input id="canGive" type="radio" value="0" name="canGive">No<br>
Can you stack it in the inventory? <input id="invStack" type="radio" value="1" name="invStack">Yes <input id="invStack" type="radio" value="0" name="invStack">No<br>
</fieldset>
<fieldset>
Interaction Type:<br>
<input id="intType" type="radio" value="default" name="intType">None<br>
<input id="intType" type="radio" value="bed" name="intType">Bed<br>
<input id="intType" type="radio" value="vendingmachine" name="intType">Vending Machine<br>
<input id="intType" type="radio" value="trophy" name="intType">Trophy<br>
<input id="intType" type="radio" value="gate" name="intType">Gate<br>
<input id="intType" type="radio" value="onewaygate" name="intType">One Way Gate<br>
<input id="intType" type="radio" value="dice" name="intType">Dice<br>
<input id="intType" type="radio" value="teleport" name="intType">Teleporter<br>
(More Interaction Types Coming in v2.0)<br>
</fieldset>
<fieldset>
How many interactions does the furniture have? (i.e. a dice has 6 sides and a closed side, therefore 7 interactions.)<br>
<input id="intCount" type="number"><br>
If your furniture gives out an item, what is the item's ID? 0, if none. (View external_flash_texts.txt or external_flash_texts.xml for ID #'s.)<br>
<input id="vendingID" type="number"><br>
</fieldset>
<input type="Submit" value="Generate!">
</form>
Furniture SQL:<br>
<textarea id="furniSQL" readonly="true" rows="10" cols="50"></textarea>
</body>
</html>
And here is my JS:
// HabSQL - Online Habbo SQL Generator
// Developed by Thomas Yamakaitis - March 3, 2015
function habSQL() {
var furniID = document.getElementById('furniID').value;
var furniName = document.getElementById('furniName').value;
var fileName = document.getElementById('fileName').value;
var furniType = document.getElementById('furniType').value;
var furniWidth = document.getElementById('furniWidth').value;
var furniLength = document.getElementById('furniLength').value;
var furniHeight = document.getElementById('furniHeight').value;
var canStack = document.getElementById('canStack').value;
var canSit = document.getElementById('canSit').value;
var canWalk = document.getElementById('canWalk').value;
var spriteID = document.getElementById('spriteID').value;
var canRecycle = document.getElementById('canRecycle').value;
var canTrade = document.getElementById('canTrade').value;
var canSell = document.getElementById('canSell').value;
var canGive = document.getElementById('canGive').value;
var invStack = document.getElementById('invStack').value;
var intType = document.getElementById('intType').value;
var intCount = document.getElementById('intCount').value;
var vendingID = document.getElementById('vendingID').value;
var comma = ", ";
var commaQuotes = "', '";
var quoteComma = "', ";
var commaQuote = ", '";
document.getElementById('furniSQL').innerHTML = "INSERT INTO `furniture` (`id`, `public_name`, `item_name`, `type`, `width`, `length`, `stack_height`, `can_stack`, `can_sit`, `is_walkable`, `sprite_id`, `allow_recycle`, `allow_trade`, `allow_marketplace_sell`, `allow_gift`, `allow_inventory_stack`, `interaction_type`, `interaction_modes_count`, `vending_ids`, `is_arrow`, `foot_figure`, `height_adjustable`, `effectM`, `effectF`, `HeightOverride`) VALUES (" + furniId + commaQuote + furniName + commaQuotes + fileName + commaQuotes + furniType + quoteComma + furniWidth + comma + furniLength + comma + furniHeight + commaQuote + canStack + commaQuotes + canSit + commaQuotes + canWalk + quoteComma + spriteID + commaQuote + canRecycle + commaQuotes + canTrade + commaQuotes + canSell + commaQuotes + canGive + commaQuotes + invStack + commaQuotes + intType + quoteComma + intCount + comma + vendingID + ");";
}
I can't seem to pinpoint exactly what it is that I am doing wrong. If somebody could please assist me, that would be greatly appreciated.
Thanks!
Thanks to a few users here! The solution was a typo and I believe it was also value instead of innerHTML too.
A simple typo: furniId instead of furniID on the last line
JavaScript is case-sensitive so if you capitalize a variable name differently it's a completely different variable, and so it does not know what you mean.
You got a typo: furniID in your last element which is document.getElementById('furniSQL').value= is spelled as furniId
Textareas are modified by value, not innerHTML
so set it up to
document.getElementById('furniSQL').value = "INSERT INTO `furniture` (`id`, `public_name`, `item_name`, `type`, `width`, `length`, `stack_height`, `can_stack`, `can_sit`, `is_walkable`, `sprite_id`, `allow_recycle`, `allow_trade`, `allow_marketplace_sell`, `allow_gift`, `allow_inventory_stack`, `interaction_type`, `interaction_modes_count`, `vending_ids`, `is_arrow`, `foot_figure`, `height_adjustable`, `effectM`, `effectF`, `HeightOverride`) VALUES (" + furniId + commaQuote + furniName + commaQuotes + fileName + commaQuotes + furniType + quoteComma + furniWidth + comma + furniLength + comma + furniHeight + commaQuote + canStack + commaQuotes + canSit + commaQuotes + canWalk + quoteComma + spriteID + commaQuote + canRecycle + commaQuotes + canTrade + commaQuotes + canSell + commaQuotes + canGive + commaQuotes + invStack + commaQuotes + intType + quoteComma + intCount + comma + vendingID + ");";
and you should be good to go.