Display textbox multiple times - javascript

The HTML part contains a textarea with a label.The user has to enter text and the form should be submitted and refreshed for the user to enter text again for say 5 more times. How can I do this using Javascript?
This is the html code:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</form>
<button type="button" class="btn" id="sub" onclick="func()">Next</button>
The javascript code:
var x=1;
document.getElementById("p1").innerHTML="Question"+x;
function func()
{
var frm = document.getElementsByName('myform')[0];
frm.submit();
frm.reset();
return false;
}

Here are two methods you can use. Both of these require you to add a submit button to your form, like this:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
<!-- add this button -->
<input type="submit" value="Submit" class="btn">
</form>
<!-- no need for a <button> out here! -->
Method 1: sessionStorage
sessionStorage allows you to store data that is persistent across page reloads.
For me info, see the MDN docs on sessionStorage. This method requires no external libraries.
Note that in this method, your page is reloaded on submit.
window.onload = function() {
var myForm = document.forms.myform;
myForm.onsubmit = function(e) {
// get the submit count from sessionStorage OR default to 0
var submitCount = sessionStorage.getItem('count') || 0;
if (submitCount == 5) {
// reset count to 0 for future submissions
} else {
// increment the count
sessionStorage.setItem('count', submitCount + 1);
}
return true; // let the submission continue as normal
}
// this code runs each time the pages loads
var submitCount = sessionStorage.getItem('count') || 0;
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
};
Method 2: AJAX with jQuery
If you don't mind using jQuery, you can easily make AJAX calls to submit your form multiple times without reloading.
Note that in this example your page is not reloaded after submit.
window.onload = function() {
var myForm = document.forms.myform;
var submitCount = 0;
myForm.onsubmit = function(e) {
$.post('/some/url', $(myForm).serialize()).done(function(data) {
submitCount++;
});
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
e.preventDefault();
return false;
};
};
Hope this helps!

You shuld create an array and push the value of the textbox to the array in func().

We can create a template using a <script type="text/template>, then append it to the form each time the button is clicked.
const btn = document.getElementById('sub');
const appendNewTextArea = function() {
const formEl = document.getElementById('form');
const textareaTemplate = document.getElementById('textarea-template').innerHTML;
const wrapper = document.createElement('div');
wrapper.innerHTML = textareaTemplate;
formEl.appendChild(wrapper);
}
// Call the function to create the first textarea
appendNewTextArea();
btn.addEventListener('click', appendNewTextArea);
<form name="myform" method="post" id="form">
</form>
<button type="button" class="btn" id="sub">Next</button>
<script id="textarea-template" type="text/template">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</script>

Related

Prevent sending form with JavaScript

I have html form with action ="script.php" which sends data.
I want prevent form to being sent with JS but it does nothing and sends data.
Naslov = title
This is html:
<form name = "my_form" enctype="multipart/form-data" method = "POST" action = "skripta.php">
<div class="form-group row ">
<div class="col-md-6">
<span id="porukaTitle" class="bojaPoruke"></span>
<label for="naslov">Naslov</label>
<input type="text" name="naslov" class="form-control" id="naslov">
</div>
</form>
And this is JS:
<script type="text/javascript">
document.getElementById("slanje").onclick = function (event) {
var slanjeForme=true;
var poljeTitle=document.getElementById("naslov");
var naslov=document.getElementById("naslov").value;
if (naslov.lenght < 5 || naslov.lenght > 30) {
slanjeForme=false;
poljeTitle.style.border="1px dashed red";
document.getElementById("porukaTitle").innerHTML="Naslov vjesti mora imati između 5 i 30 znakova!<br>";
} else {
poljeTitle.style.border="1px solid green";
document.getElementById( "porukaTitle").innerHTML="";
}
if (slanjeForme != true) {
event.preventDefault();
}
}
</script>
Problem is that it always sends data.
Don't use the "click" handler, instead use the FORM's "submit" Event handler!
Create a nifty reusable validate function that will also handle the input style using classList.toggle()
Populate your validate function with the needed validators
Use finally CSS to handle error borders and messages visibility using the class is-error
Always place the error SPAN elements as siblings to a desired action element, that way when an input gets the .is-error we can target it using the CSS's General Sibling Combinator ~
No matter how many inputs you have, you don't need to write extra JS logic. Just validate the desired ones like const has_err = validate(EL("#foo"), "length");
const validate = (el, validatorName = "length") => {
const val = el.value.trim();
const isErr = {
// Basic, validates if there's value
length: () => val.length < 1,
// Validate between 5 and 30 charaters
length_5_30: () => val.length < 5 || val.length > 30,
// Add more validators
}[validatorName]();
el.classList.toggle("is-error", isErr);
return isErr;
};
const EL = (sel, EL) => (EL || document).querySelector(sel);
EL("#my_form").addEventListener("submit", function(event) {
const err_1 = validate(EL("#naslov"), "length_5_30");
const err_2 = validate(EL("#bla"), "length");
if (err_1 || err_2) {
event.preventDefault();
}
});
form .is-error {
outline: 1px dashed red;
}
form .error-message {
display: none;
color: red;
}
form .is-error ~ .error-message {
display: block;
}
<form id="my_form" name="my_form" enctype="multipart/form-data" method="POST" action="skripta.php">
<div class="form-group row">
<div class="col-md-6">
<label for="naslov">Naslov</label>
<input type="text" id="naslov" name="naslov" class="form-control">
<span class="error-message">Naslov vjesti mora imati između 5 i 30 znakova!</span>
</div>
</div>
<div class="form-group row">
<div class="col-md-6">
<label for="naslov">Bla bla</label>
<input type="text" id="bla" name="bla" class="form-control">
<span class="error-message">Ovo polje ne može biti prazno!</span>
</div>
</div>
<button type="submit">Pošalji</button>
</form>
You should use a form validation function instead. In your form, add an attribute called "onsubmit". The form should look similar to this:
<form onsubmit="return checkBeforeSubmitting()"></form>
Then, you can have a function run before data is sent. If you don't want data to be sent, make the "checkBeforeSubmitting()" return false under a certain condition.
Link to more info on how to use this: https://www.w3schools.com/js/js_validation.asp
The best way to stop a form from submitted is to hook into its submit event, and do so in the javascript, rather than add javascript into the html. That would look like this:
var form = document.querySelector('form.myform');
form.addEventListener('submit', e => {
// put your conditional here
if( please_dont_submit == true ) {
e.preventDefault();
}
// else form will submit;
});
<form class="myform">
<!-- form stuff -->
<input type="submit" value="Submit">
</form>
You may also wish to submit the form from within itself, after doing the preventDefault(). You can do that by setting a flag to indicate that the check has already been processed:
const form = document.querySelector('form.myform');
var okToSubmit = false;
form.addEventListener('submit', e => {
// put your conditional here
if( please_dont_submit == true && ! okToSubmit ) {
e.preventDefault();
// do some further processing and submit again.
okToSubmit = true;
e.target.submit();
}
// else form will submit;
});

To take entries in a webform multiple times using Java Script

I have a webform with name 'audit-form' and it has a column in which we have to enter the number of observations.
<form id="audit-form" action="action.php" method="post">
<label for="observ_count">Number of Observations</label>
<textarea id="observ_count" name="Number_of_Obsevations"></textarea>
<input type="submit" value="Add Obsevations" id="audit_form_submit"/>
</form>
<script>
const auditForm=document.getElementById("audit_form");
const auditButton=document.getElementById("audit_form_submit");
auditButton.addEventListener("click",(e) => {
e.preventDefault();
var noo = auditForm.Number_of_Observations.value;
for(i=0;i<noo;i++)
{
if(i<noo-1)
{
window.location.assign('observ.html'); //html page to enter obsevations and next button at bottom
}
else
{
window.location.assign('observ1.html'); //html page to enter obsevations and submit button at bottom
}
}
});
</script>
I tried to do this but directly observ1.html is opening up not observ.html
Please help
You simple wrong here:
Look at name
<textarea id="observ_count" name="Number_of_Obsevations"></textarea>
And now look what you write in js:
var noo = auditForm.Number_of_Observations.value;
Number_of_Obsevations is not equal to Number_of_Observations
const auditForm=document.getElementById("observ_count");
const auditButton=document.getElementById("audit_form_submit");
auditButton.addEventListener("click",(e) => {
e.preventDefault();
var noo = auditForm.value;
for(i=0;i<noo;i++)
{
if(i<noo-1)
{
console.log('1');
}
else
{
console.log('2');
}
}
})
<form id="audit-form">
<label for="observ_count" Number of Obsevations</label>
<textarea id="observ_count" name="Number_of_Obsevations"></textarea>
<input type="submit" value="Add Obsevations" id="audit_form_submit">
</form>

Validate required properties using javascript submit

I submited a form using javascript (must check pre-condition first), and I noticed that I'm not notified about unfilled required properties:
function offerContract() // the function called when deployContractBtn is clicked
{
document.getElementById("CreateContractDialogMessage").innerHTML = "";
ErrorMsg = checkErrors();
if (ErrorMsg != "")
{
$('#CreateContractDialogTitle').text("Error"); //show error headline
document.getElementById("CreateContractDialogMessage").innerHTML = ErrorMsg;
document.getElementById("closeButton").style.display = "block";
$('#dialogOfferContract').modal('show');
return;
}
$("#deployContractBtn").submit() //type = button and not submit
}
#using (Html.BeginForm("DeployContract", "CreateContract", FormMethod.Post, new { #id = "DeployContractForm" }))
{
.....The rest of the form....
<input id="deployContractBtn" onclick="offerContract()" type="button" class="btn btn-success" value="Sign&Deploy Contract" disabled />
}
How to notify about the unfilled requierd properties using javascript as the classic submit does? Is it possible to mark them, so the user will know where he needs to insert values?
If you want to leverage default browser UI, you can just mark the field as required. By default, the form will now allow a user to submit it until the requirements are met.
<form id="myForm">
<input placeholder="this field is required" required />
<button type="submit">Submit</button>
</form>
However, If you want a little more customization you can use JavaScript to do what you want.
const submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', (e) => {
const form = document.getElementById('myForm');
if (form.checkValidity()) {
// TODO: Submit form code here
console.log('Form submitted');
return;
} else {
const nameField = document.getElementById('nameField');
if (!nameField.checkValidity()) {
alert('The Name Field is a required field. Please provude a valid value');
}
}
});
<form id="myForm">
<input placeholder="this field is required" id="nameField" required />
</form>
<button id="submit">Submit</button>

Need to show the thankyou message instead of ajax response

I was trying to do the form submit response, like on submit the form fields should be hidden and to show the thank you message without refreshing the page, but when i click submit the page is getting refreshed and showing the ajax response {"result":"success","data":"{\"message\":[\"sample message\"]}"
tried using Send Email from a Static HTML Form using Google Apps Mail!
(function() {
'use strict';
function getFormData(form) {
var elements = form.elements;
var fields = Object.keys(elements).filter().map(function(k) {
if (elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
} else if (elements[k].length > 0) {
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name) {
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
//formData.formGoogleSend = form.dataset.email || ""; // no email by default
formData.formPage = form.dataset.page || "";
}
function handleFormSubmit(event) {
if (this.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
this.classList.add('was-validated');
} else if (this.checkValidity() === true) {
var form = event.target;
var formData = getFormData(form);
var data = formData.data;
var url = form.action;
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
form.reset();
var formElements = form.querySelector(".form-elements")
if (formElements) {
formElements.style.display = "none"; // hide form
}
var thankYouMessage = form.querySelector(".thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
return;
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
}).join('&');
xhr.send(encoded);
}
}
function loaded() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener("submit", handleFormSubmit, false);
});
}
document.addEventListener("DOMContentLoaded", loaded, false);
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="gform needs-validation" method="POST" data-page="form validation test" action="https://script.google.com/macros/s/AKfycbxXw4fshxotq4vkQ3LUjvBaHhjS2RjFvDvKs5FW4w/exec" novalidate>
<div class="form-elements col-md-6 m-5">
<div class="form-row">
<div class="col-md-12 mb-3">
<textarea id="visitorMessage" class="form-control" name="message" placeholder="Message" required></textarea>
<div class="invalid-tooltip"> Please enter the message </div>
</div>
</div>
<button class="btn btn-primary btn-sm mx-0" type="submit">Submit</button>
</div>
<div class="thankyou_message" style="display: none;">
<h2>Thanks for contacting us! We will get back to you soon!</h2>
</div>
</form>
I expect to show the thankyou message without refreshing the page but the actual result is the page getting refreshed and showing the Ajax response
move event.preventDefault(); out of the if statement so the default submit action of the form is never triggered. You don't want to do an submit when you do an ajax request since the submit action will navigate to the form action url.
$('.needs-validation').on('submit', handleFormSubmit);
function handleFormSubmit(event) {
event.preventDefault();
if (this.checkValidity() === true) {
//Do this in the ajax succes event handler
$('.thankyou_message').show();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="gform needs-validation" method="POST" data-page="form validation test" action="https://script.google.com/macros/s/AKfycbxXw4fshxotq4vkQ3LUjvBaHhjS2RjFvDvKs5FW4w/exec" novalidate>
<div class="form-elements col-md-6 m-5">
<div class="form-row">
<div class="col-md-12 mb-3">
<textarea id="visitorMessage" class="form-control" name="message" placeholder="Message" required></textarea>
<div class="invalid-tooltip"> Please enter the message </div>
</div>
</div>
<button class="btn btn-primary btn-sm mx-0" type="submit">Submit</button>
</div>
<div class="thankyou_message" style="display: none;">
<h2>Thanks for contacting us! We will get back to you soon!</h2>
</div>
</form>

How can I pass the zip to the button function?

I did wrap this in a form with a submit button, but realized that this attempted to go to a new page without performing the logic. How can I pass the zip code to the onclick button event? If this is completely wrong, can you provide guidance onto how to perform this correctly.
<input type="text" placeholder="Zip Code" pattern="[0-9]{5}" name="zip" required />
<button id="checker">Go!</button>
<script>
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip) {
var zipCodes = [26505, 26501, 26507, 26506];
for (i = 0; i <= zipCodes.length - 1; i++) {
if (zip == zipCodes[i]) {
alert("YES");
break;
}
}
}
</script>
You need to get the value of your input and you can do this with document.querySelector('[name="zip"]').value
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip) {
var zip = document.querySelector('[name="zip"]').value;
var zipCodes = [26505, 26501, 26507, 26506];
for (i = 0; i <= zipCodes.length - 1; i++) {
if (zip == zipCodes[i]) {
alert("YES");
break;
}
}
})
<input type="text" placeholder="Zip Code" pattern="[0-9]{5}" name="zip" required />
<button id="checker">Go!</button>
Just use getElementById('ELEMENT_NAME_HERE').value like so:
Go!
<script>
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip){
console.log('Clicked');
var enteredZip = document.getElementById("zip").value;
console.log(enteredZip);
var zipCodes=[26505, 26501, 26507, 26506];
for(i=0; i<=zipCodes.length-1; i++){
if(zip == zipCodes[i]){
alert("YES");
break;
}}});
</script>
https://plnkr.co/edit/ptyUAItwyaSmZXsD81xK?p=preview
You can't pass it in.
basically if this myfunction() will return a false then the form would not be submitted;
Also this would only be performed at the time of submittion of the form
https://www.w3schools.com/jsref/event_onsubmit.asp
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input id='input-id' type="submit">
</form>
<script>
myfunction(){
if(/*some condition*/)
{
return false;
}
</script>
Also few things to consider since you seem new and people here are giving you very correct but specific solutions.
if you add a button to inside tag, that would submit the form on clicking it.
That is why many use a div which looks like a button by css. Mainly a clean solution to override the Button submit and also you can simply submit the form by Javascript.

Categories