Prevent default js for a basic form - javascript

I have a basic html form and when the user is successfully submitting the form I am displaying a pop-up. However, during that time two things occurs:
The popup is only displayed for 1-2 seconds
The page is reloaded and therefore going back to the top of the page
I would like to avoid those 2 events and apparently I have to use event.preventDefault() but I don't know where to use it
const messageSubmitContactForm = () => {
const form = document.getElementById("contact-form");
form.onsubmit = function(){
displayPopUpSent()
};
}
const displayPopUpSent = () => {
const popup = document.getElementById("popup-sent");
popup.style.display="block";
}
const app = () => {
messageSubmitContactForm();
}
app();
form
<form id="contact-form" method="post" action="" enctype="multipart/form-data"> content </form>

You should use it here
form.onsubmit = function(event){
event.preventDefault();
displayPopUpSent()
};
Update:
You need to add the action url too in your <form> element (currently it is an empty string)
I have created a simple snippet to illustrate a little bit, maybe this will clear it up for you.
const messageSubmitContactForm = () => {
const form = document.getElementById("contact-form");
form.onsubmit = function(event) {
event.preventDefault();
displayPopUpSent()
};
}
const displayPopUpSent = () => {
const popup = document.getElementById("popup-sent");
popup.style.display = "block";
}
const app = () => {
messageSubmitContactForm();
}
app();
<html>
<body>
<form id="contact-form" method="post" action="" enctype="multipart/form-data">
<input type="text" name="message" />
<button type="submit">Submit</button>
</form>
<div id="popup-sent" style="display: none">Data is sent</div>
</body>
</html>

Related

How to simulate the Enter button to replicate the submit button?

I am making a weather application with a textarea, if you click "submit" you will see the weather results. Now, I want to make it so you can click enter to see the data. this is some code:
<section class="inputs">
<input type="text" placeholder="Enter any city..." id="cityinput">
<input type="submit" value="Submit" id="add">
<button placeholder="submit" id="add"></button>
</section>
This is some javascript code:
btn.addEventListener('click', function(){
//This is the api link from where all the information will be collected
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputval.value+'&appid='+apik)
.then(res => res.json())
//.then(data => console.log(data))
.then(data => {
//Now you need to collect the necessary information with the API link. Now I will collect that information and store it in different constants.
var nameval = data['name']
var tempature = data['hourly']['pop']
//Now with the help of innerHTML you have to make arrangements to display all the information in the webpage.
city.innerHTML=`Weather of <span>${nameval}<span>`
temp.innerHTML = ` <span>${ tempature} </span>`
})
You need to attach a listener to your textarea, if the user press enter then you execute your call (here simulated by an alert) and you prevent the default in order to don't go in a new line. In any other case, just don't take any action
const textArea = document.querySelector('textarea');
textArea.addEventListener('keydown', e => {
if (e.key === 'Enter') {
window.alert('Sending data...');
e.preventDefault();
}
});
<textarea placeholder="Type and press enter"></textarea>
You can just put the submit code in a function, and call the function in both the cases:
function submitAction() {
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputval.value+'&appid='+apik)
.then(res => res.json())
.then(data => {
const nameval = data['name']
const tempature = data['hourly']['pop']
city.innerHTML=`Weather of <span>${nameval}<span>`
temp.innerHTML = ` <span>${ tempature} </span>`
});
}
Then:
if (e.key === 'Enter') {
submitAction();
e.preventDefault();
}
And:
btn.addEventListener('click', () => submitAction());
You could use a HTML form and use the form submit event:
<form id="form">
<input type="text" placeholder="Enter any city..." id="cityinput" />
<button type="submit">Submit</button>
</form>
Inside the event listener you can then read the value from the input once the submit event is triggered. Alternatively you could go looking for the input value inside the event object.
var form = document.getElementById('form');
form.addEventListener('submit', function(event) {
const inputValue = document.querySelector('input').value;
event.preventDefault();
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputValue+'&appid='+apik)
.then(res => res.json())
.then(data => {
var nameval = data['name']
var tempature = data['hourly']['pop']
city.innerHTML=`Weather of <span>${nameval}<span>`
temp.innerHTML = ` <span>${ tempature} </span>`
})
});
You need to create listener for keydown event and check if clicked key is enter:
const textarea = document.querySelector(".some-class");
textarea.addEventListener("keydown", function(e) {
if(e.key === "Enter") {
// your code
}
});
<textarea class="some-class"></textarea>

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>

Global array remains empty

I am trying to update my global array, but it remains null after I submit a text value(.name) through a submit button.
Please tell me how I can keep track of text values in my global array. Thank you.
var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
document.querySelector("#form1").onsubmit = () => {
let name = document.querySelector(".name").value;
display_name.push(name);
};
});
When the form is submitted, a new page is loaded. It loads the URL in the action property of the form. So, your variable goes away.
If you don't want that to happen, prevent the form from being submitted with preventDefault.
For example ...
const name_list = [];
window.addEventListener('DOMContentLoaded', (e) => {
const names = document.querySelector(`.names`);
const add_button = document.querySelector(`.names--add_button`);
names.addEventListener('submit', e => e.preventDefault());
add_button.addEventListener('click', (e) => {
const name = document.querySelector(`.names--name`);
const collected = document.querySelector(`.names--collected`);
name_list.push(name.value);
collected.innerHTML += `<li>${name.value}</li>`;
name.value = ``;
name.focus();
});
});
body { background: snow; }
<form class="names" action="#" method="post">
<label>Name: <input type="text" name="name" class="names--name"></label>
<button class="names--add_button">Add To List</button>
<div>Names Collected:</div>
<ul class="names--collected">
</ul>
</form>
I am see at the moment it's working perfect. but you want add value every time when you click the button. so just changed the type of your
<button type="submit"> to <button type="button">
because when you click on submit page automatically reload in html, an the 2nd thing you need to change your event from onsubmit to onclick and your button to it instead of your form.
var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
document.querySelector("#button1").onclick = () => {
let name = document.querySelector(".name").value;
display_name.push(name);
};
});

Display textbox multiple times

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>

simple javascript validation in asp.net mvc

I have very very stupid bug in javascript validation
let me i explain in code :
this is my form tag
<form method="post" enctype="multipart/form-data" name="myForm" onsubmit="return validateForm()">
<textarea id="content" name="Body"><%= Model.Body %></textarea>
</form>
and this is my script :
function validateForm(e) {
debugger;
var reviewMessage = $("[name='Body']").attr('value');
//var overallValue = document.getElementsByClassName('checkbox overall icon-checkbox').prop.checked;
if (reviewMessage.length < 100) {
e.preventDefault();
// $("Body").show();
$('#bodyValidation').css({'display' : 'block'});
return false;
}
return true;
}
my problem is that when ever i click the button page will be submited ;
but i want to stop this action with javascript .
how can i do that?
Your selector is wrong.
Change
var reviewMessage = $("Body").val();
to
var reviewMessage = $("[name='Body']").val();
OR
var reviewMessage = $('#content').val();

Categories