The code below is a form that generates html codes
I want each field to be on a separate line in the "Post text" field
Current output:
<div>texthere</div><script>texthere</script><style>texthere</style>
Expected output:
<div>texthere</div>
<script>texthere</script>
<style>texthere</style>`
function submitted() {
var formValue0 = '<div>' + document.getElementsByName("content")[0].value + '</div>';
var formValue1 = '<script>' + document.getElementsByName("content")[1].value + '<\/script>';
var formValue2 = '<style>' + document.getElementsByName("content")[2].value + '</style>';
document.getElementsByName("content")[3].value = formValue0 + formValue1 + formValue2;
return false;
}
<form onsubmit="return submitted()">
Field 1:<br><input type="text" name="content"><br>
Field 2:<br><input type="text" name="content"><br>
Field 3:<br><input type="text" name="content"><br>
<input type="submit" value="DONE"><br><br>
Post text:<br><textarea name="content" style="height:200px"></textarea>
</form>
You can use this code for several things and speed up your work with repeated codes like a custom post that would have to edit the html manually
You can use new line character \n like this -
function submitted() {
var formValue0 = '<div>'+ document.getElementsByName("content")[0].value +'</div>\n';
var formValue1 = '<script>'+ document.getElementsByName("content")[1].value +'<\/script>\n';
var formValue2 = '<style>'+ document.getElementsByName("content")[2].value +'</style>\n';
document.getElementsByName("content")[3].value = formValue0+formValue1+formValue2;
return false;
}
<form onsubmit="return submitted()">
Field 1:<br><input type="text" name="content"><br>
Field 2:<br><input type="text" name="content"><br>
Field 3:<br><input type="text" name="content"><br>
<input type="submit" value="DONE"><br><br>
Post text:<br><textarea name="content" style="height:200px"></textarea>
</form>
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>
I'm trying to display a text area depending on what radio button the user clicks. When the "contest" function is commented out, the newsletter part works fine. But when the contest function is included, the newsletter does not work. I've tried debugging but I can't seem to find an issue. I've tried using different forms but it doesn't change the problem.
My HTML:
function newsletter() {
var response = "";
if(document.getElementById("yes").checked) {
response += "<p><b>Enter Your Address:</b></p>";
response += '<input type="text" id="address"><br>';
var output = document.getElementById("isChecked");
output.innerHTML = response;
}
}
function contest() {
var resp = "";
if(document.getElementById("answer").value == "Y") {
resp += "<p><b>Enter your credit card information to verify age ($0.00 charge)</b></p>";
resp += "<br>";
resp += '<input type="text" id="first4" size="4" maxlength="4">';
resp += "-";
resp += '<input type="text" id="second4" size="4" maxlength="4">';
resp += "-";
resp += '<input type="text" id="third4" size="4" maxlength="4">';
resp += "-";
resp += '<input type="text" id="fourth4" size="4" maxlength="4"';
var out = document.getElementById("contestOutput");
out.innerHTML = resp;
}
}
body {background-color: pink; }
<center>
<h1>Magnificant Music!</h1>
</center>
<p>Welcome Blue Note Records visitors! On this site, you can enter your information to recieve a card sent every month informing you about the lastest releases on your favorite record label, and a chance to enter a contest that could win you a brand new instrument of your choice!</p>
<form action="" method="post">
<fieldset>
<p><b>Personal Information</b></p>
<label>First Name:</label>
<input type="text" id="firstName"><br>
<label>Last Name:</label>
<input type="text" id="lastName"><br>
<label>Middle Initial</label>
<input type="text" id="middleInit"><br>
</fieldset>
<br>
<fieldset>
<p><b>Do you want to recieve a newsletter?</b></p>
<input type="radio" name="news" id="yes">Yes<br>
<input type="radio" name="news" id="no">No<br>
<button type="button" onclick="newsletter();">Submit</button>
<div id="isChecked"></div>
</fieldset>
<br>
<fieldset>
<p><b>Would you like to enter the contest for a brand new instrument of your choice (Y / N)? (18 yrs old minimum)</b></p>
<input type="text" size="1" id="answer"><br>
<button type="button" onclick="contest();">Submit</button>
<div id="contestOutput"></div>
</fieldset>
</form>
The answer, provided by #jcubic, was the error. Closing the tag fixed the error encountered.
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
I'm writing an app using web2py and I'm currently trying to make a form where the user can add/remove additional fields on the fly. I've got this working by using jQuery to add the addition fields to the DOM but the problem is only the hardcoded fields are being submitted (I am dumping form.vars at the top of the page to check). I have made sure the dynamic fields have unique names and I've been scouring the html for errors but have come up with nothing.
Here's my javascript:
$(document).ready(function(){
var wrapper = $("#formwrapper");
var addbutton = $("#addfield");
var removebutton = $('#removefield');
var x = 2;
$(addbutton).click(function(){
$(wrapper).append(
"<div id='extrareward"+ x +"'><h3>Reward " + x + "</h3>" +
"<label>Minimum amount to get reward: </label>" +
"<input name='min"+ x +"' type='text'><br>" +
"<label>Reward Description: </label>" +
"<textarea name='reward"+ x +"' rows='10' cols='40'></textarea></div>"
);
x++;
});
$(removebutton).click(function(){
if (x > 2) {
x--;
var id = '#extrareward' + x;
$(id).remove();
}
});
});
And here's the html form from the page source with one static and one dynamic block:
<form action="#" enctype="multipart/form-data" method="post">
<div id="formwrapper">
<label>Minimum amount to get reward: </label>
<input name="min1" type="text" value=""><br>
<label>Reward description: </label>
<textarea cols="40" name="reward1" rows="10"></textarea><br>
<div id="extrareward2">
<h3>Reward 2</h3>
<label>Minimum amount to get reward: </label>
<input name="min2" type="text"><br>
<label>Reward Description: </label>
<textarea name="reward2"></textarea>
</div>
</div>
<input id="submitbutton" type="submit">
<div style="display:none;">
<input name="_formkey" type="hidden" value="1e315a07-a035-4858-822c-614c962ebb98">
<input name="_formname" type="hidden" value="default">
</div>
</form>
and finally here is the code for the controller:
#auth.requires_login()
def create2():
form = FORM(DIV(LABEL('Minimum amount to get reward: '), INPUT(_name='min1', _type='text'), BR(),
LABEL('Reward description: '), TEXTAREA(_name='reward1'), BR(),
_id='formwrapper'),
INPUT(_id='submitbutton', _type='submit'))
if form.process(keepvalues=True).accepted:
session.flash = 'form accepted'
else:
session.flash = 'form rejected'
return dict(loginform=auth.login(),
rewardtiersform=form)
Might be that I'm just missing a silly error somewhere but I've been scratching my head for too long in this. Help much appreciated!
I am using this code to generate dynamically ADD More input fields and then plan on using Save button to save their values in database. The challenge is that on Save button, I want to keep displaying the User Generated Input fields. However they are being refreshed on Save button clicked.
javascript:
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum++;
var row = '<p id="rowNum' + rowNum + '">Item quantity: <input type="text" name="qty[]" size="4" value="' + frm.add_qty.value + '"> Item name: <input type="text" name="name[]" value="' + frm.add_name.value + '"> <input type="button" value="Remove" onclick="removeRow(' + rowNum + ');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum' + rnum).remove();
}
</script>
HTML:
<form method="post">
<div id="itemRows">Item quantity:
<input type="text" name="add_qty" size="4" />Item name:
<input type="text" name="add_name" />
<input onclick="addRow(this.form);" type="button" value="Add row" />
</div>
<p>
<button id="_save">Save by grabbing html</button>
<br>
</p>
</form>
One approach is to define a template to add it dynamically via jQuery
Template
<script type="text/html" id="form_tpl">
<div class = "control-group" >
<label class = "control-label"for = 'emp_name' > Employer Name </label>
<div class="controls">
<input type="text" name="work_emp_name[<%= element.i %>]" class="work_emp_name"
value="" />
</div>
</div>
Button click event
$("form").on("click", ".add_employer", function (e) {
e.preventDefault();
var tplData = {
i: counter
};
$("#word_exp_area").append(tpl(tplData));
counter += 1;
});
The main thing is to call e.preventDefault(); to prevent the page from reload.
You might want to check this working example
http://jsfiddle.net/hatemalimam/EpM7W/
along with what Hatem Alimam wrote,
have your form call an upate.php file, targeting an iframe of 1px.