All.
Please see the following code, which should, as far as I can gather, grab IDs a1, a2 & a3, and throw them in the new textbox with the ID 'compiled':
Javascript
<script type="text/javascript">
function submitAllForms() {
var answer1 = (document.getElementById("a1").value);
var answer2 = (document.getElementById("a2").value);
var answer3 = (document.getElementById("a3").value);
document.getElementById("compiler").innerHTML = ("<input type="text" id="compiled">" + "Question1? " + answer1 + " Question2? " + answer2 + " Question3? " + answer3 + "\nEnd" + "</input>");
}
</script>
HTML
<body>
<form id="q1" method="post">
<p>Question1?</p>
<input type="text" placeholder="answer" id="a1" />
</form>
<form id="q2" method="post">
<p>Question2?</p>
<input type="text" placeholder="answer" id="a2" />
</form>
<form id="q3" method="post">
<p>Question3?</p>
<input type="text" placeholder="answer" id="a3" />
</form>
<input type="button" value="Submit" onclick="submitAllForms()" />
<form id="compiler" method="post">
</form>
</body>
The problem I've got is that upon hitting the submit button, the console spits out the error:
Uncaught ReferenceError: submitAllForms is not defined
Which to me doesn't make sense. I can't see where I've gone wrong.
Any help appreciated! Thanks in advance!
You've syntax error in javascript. You need to delete " (what is bad idea), or escape it using \, as below:
function submitAllForms() {
var answer1 = (document.getElementById("a1").value);
var answer2 = (document.getElementById("a2").value);
var answer3 = (document.getElementById("a3").value);
document.getElementById("compiler").innerHTML = ("<input type=\"text\" id=\"compiled\">" + "Question1? " + answer1 + " Question2? " + answer2 + " Question3? " + answer3 + "\nEnd" + "</input>");
}
It's good idea to use editor with syntax highlighting. After fast copy–paste I seen that parts of code which should be strings, but they wasn't.
Escaping special characters (see more in w3schools) let you use quotes etc. inside strings just as normal characters in it.
Seems to work OK. Tidied up a bit to remove errors with the string concatenation, but the function is called by the code as written.
function submitAllForms() {
var answer1 = document.getElementById("a1").value;
var answer2 = document.getElementById("a2").value;
var answer3 = document.getElementById("a3").value;
document.getElementById("compiler").innerHTML = "<input type=text id=compiled>Question1? " + answer1 + " Question2? " + answer2 + " Question3? " + answer3 + "\nEnd</input>";
}
<body>
<form id="q1" method="post">
<p>Question1?</p>
<input type="text" placeholder="answer" id="a1" />
</form>
<form id="q2" method="post">
<p>Question2?</p>
<input type="text" placeholder="answer" id="a2" />
</form>
<form id="q3" method="post">
<p>Question3?</p>
<input type="text" placeholder="answer" id="a3" />
</form>
<input type="button" value="Submit" onclick="submitAllForms()" />
<form id="compiler" method="post">
</form>
</body>
Related
I want to solve this question with CSS, form, javascript and I tried to do javascript and included 3 if statements but it not really showing me the output
is it because the if statements should each be closed with brackets? or maybe there is a mistake in the way I write the variables I tried many things, and it's not working please help I'm still a beginner programmer and I can't figure it out
function myFunction(){
var Fname= document.getElementById("fname").value;
var Lname= document.getElementById("lname").value;
var Name = Fname + " " + Lname;
var date= document.getElementById("date").value;
var tr= document.getElementById("t").value;
var tour= document.getElementById("tour").value;
var request= document.getElementById("request").value;
var v = Number(document.getElementById("visitor").value);
var city = document.getElementById("city").value;
var x="";
var y="";
var z="";
var total=x+y+z;
{
if (v<=0){
v=prompt(" minimum visitors are 1 try again");
}
else if (city == "Amman $50") {
x = v * 50;
}
else if (city == "Salt $20") {
x = v * 20;
}
else {
x = v * 10;
}
}
{
if ( tour==Yes )
{
y= 50;
}
else {
y=x;
}
}
{
if (trans==Car)
{
z= 30;
}
else{
z=20;
}
}
document.getElementById("result").innerHTML = "Arrival date" + date + "<br>"
+ Name.toUpperCase() +
"<br>"+" City " + city + v + "visitors"
+"<br>" + " transportation " + tr +
"<br>" + "tour leader :" + tour
"<br>"+ "any medical:" + request +
"<br>" +"Amount=$ " + total ;
return false;
};
body{
margin:20px;
text-align:center;
}
form{
background-color:orange;
}
div.sec {
margin-left:300px;
}
div.transpo {
margin-right:450px;
}
<h3 style="text-align:center"> <span style="color:red;font-size:40px;">V</span>isit <span style="color:red;font-size:40px;">J</span> ordan </h3>
<form>
<div class="transpo">
<input type="text" id="fname" size="30" placeholder="First Name">
<br><br>
<select id="city">
<option value="select your city "> Select your city </option>
<option value="50 ">Amman $50</option>
<option value="20 ">Salt $20</option>
<option value="10 ">Jarash $10</option>
</select>
<br><br>
<label><b>Number of visitors</b></label>
<br>
<input type="number" id="visitor">
<br><br>
<label style="margin-right:10px;"><b> Transportation</b></label>
<br>
<input type="radio" id="car" name="transportation" value="car" id="t">
<label id="car" for="car">car $30</label>
<input type="radio" id="bus" name="transportation" value="bus" id="t">
<label for="bus">bus 20$</label><br>
</div>
<div class="sec">
<input type="text" id="lname" size="30" placeholder="Last Name">
<br><br>
<label><b>Arrival Date:</b></label><br>
<input type="date" id="date">
<br><br>
<label><b> Any medical Request:</b></label>
<br>
<textarea rows="1" cols="20" id="request"></textarea>
<br><br>
<label><b> Tour Leader $50</b></label>
<br>
<input type="radio" id="yes" name="tour" value="yes" id="tour">
<label for="yes">yes</label>
<input type="radio" id="no" name="tour" value="no" id="tour">
<label for="no">no</label><br>
</div>
<button type="button" onclick="myFunction()"> PREVIEW </button>
<button type="submit" onClick=""> Submit </button>
</form>
<p style="background-color:#99ccff;width:420px;font-weight: bold;" id="result"> </p>
<p style="background-color:#99ccff;width:420px;font-weight: bold;" id="result2"> </p>
If you open your console in your browser (pressing F12 as default) you can see that the Javascript is returning an error.
Uncaught SyntaxError: "" string literal contains an unescaped line break
This refers two missing quote marks on row 174 and row 176, both are missing on the end of the file.
However your code still don't work, if you press preview you get another error
<input type="radio" id="car" name="transportation" value="car" id="t">
<input type="radio" id="bus" name="transportation" value="bus" id="t">
on these two lines you specify id twice which is not allowed.
Tips so you can more easily solve these issues on your own:
You should start to use the console to find errors in your code.
Try to reread your code and look for small errors like a missing "
If you are unsure how something works like a html or javascript feature use websites like w3school to look up well expained documentation.
Good luck in your future coding adventures.
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>
<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
<script type="text/javascript">
function gr8r( form ) {
document.write( '"' + form.s1.value + '"' );
if ( form.s1.value > form.s2.value )
document.write( ' is gr8r than ' );
else
document.write( ' is not gr8r than ' );
document.write( '"' + form.s2.value + '"' );
}
</script>
<form action="" method="post">
<input type="text" name="s1" value="" />
<input type="text" name="s2" value="" />
<br />
<input type="button" value="click" onclick="gr8r(this.form)" />
</form>
The result I expect is javascript to execute after i click on the button and then display html form...but html form isn't displaying afterwards...
Any help very much appreciated, thanks!
The output i want is:
2 is gr8r than 1
<form action="" method="post">
<input type="text" name="s1" value="" />
<input type="text" name="s2" value="" />
<br />
<input type="button" value="click" onclick="gr8r(this.form)" />
</form>
You could try this:
<script type="text/javascript">
function gr8r( form ) {
document.getElementById("output").innerHTML = document.getElementById("s1").value;
if ( document.getElementById("s1").value > document.getElementById("s2").value )
document.getElementById("output").innerHTML += ' is gr8r than ';
else
document.getElementById("output").innerHTML += ' is not gr8r than ';
document.getElementById("output").innerHTML += document.getElementById("s2").value;
}
</script>
<div id="output"></div>
<form action="" method="post">
<input type="text" id="s1" value="" />
<input type="text" id="s2" value="" />
<br />
<input type="button" value="click" onclick="gr8r(this.form)" />
</form>
The div is used to display the ouput. The div and the fields of the form are both selected by their id.
If you want to be sure that the user does not enter a string, use this javascript:
function gr8r( form ) {
if (isFinite(document.getElementById("s1").value) && isFinite(document.getElementById("s2").value)) {
document.getElementById("output").innerHTML = document.getElementById("s1").value;
if (document.getElementById("s1").value > document.getElementById("s2").value)
document.getElementById("output").innerHTML += ' is gr8r than ';
else
document.getElementById("output").innerHTML += ' is not gr8r than ';
document.getElementById("output").innerHTML += document.getElementById("s2").value;
}
else {
document.getElementById("output").innerHTML = "Please enter only floats!";
}
}
What are you trying to accomplish? Display the text under or above the form? Document.Write will actually override the entire content of the document when it is not run inline during load. So to do what you want to do you need to create a container to put the text into and then place the text in there. So for example :
<div id="message"></div>
<form action="" method="post">
<input type="text" name="s1" value="" />
<input type="text" name="s2" value="" />
<br />
<input type="button" value="click" onclick="gr8r(this.form)" />
</form>
Then the javascript would be :
<script type="text/javascript">
function gr8r( form ) {
message = document.getElementById("message");
msgStr = '"' + form.s1.value + '"';
if ( form.s1.value > form.s2.value )
msgStr += ' is gr8r than ';
else
msgStr += ' is not gr8r than ';
msgStr += '"' + form.s2.value + '"';
message.innerHTML = msgStr;
}
</script>
A better way to do this would be to use a JavaScript framework called JQuery(http://jquery.com). It provides easy ways to attach event handlers and manipulate contents. Removing inline javascript is good for maintenance.