Webpage reloading in every form submit - javascript

I have a problem of page reloading.
HTML
<form onsubmit="return commentForm()">
<input type="text" id="text">
<input type="checkbox" id="check" name="check">
<input type="submit" value="Comment" class="txt2">
</form>
<p id="demo"></p>
Javascript
function commentForm() {
var x = document.getElementById('check').checked;
var y = document.getElementById('text').value;
if (y == null || y == "") {
alert('please enter some value');
return false;
}
if (x == false) {
alert('Please check the checkbox')
return false;
}
else {
document.getElementById('demo').innerHTML += document.getELementById('text').value + "<br>";
return true;
}
}
My problem is that when i submit the page it is reloading instead of copying the text.
Please help me with that.

Try this. I changed the button from a submit input to just a button input so that it only runs the script. You don't want the form to submit, that requires a reload of the page to "submit" the form to the sever. Also you need to get the value from the text input:
document.getElementById('demo').innerHTML += document.getElementById('text').value + "<br>
But since you already put that value into var text you can just reuse that variable. Additionally you weren't checking if if the checkbox was checked because it was looking at the variable x for both inputs. Try running this:
function commentForm() {
var checkBox = document.getElementById('check').checked;
var text = document.getElementById('text').value;
if (!text) {
alert('please enter some value');
return false;
}
if (!checkBox) {
alert('Please check the checkbox')
return false;
} else {
document.getElementById('demo').innerHTML += text + "<br>";
return true;
}
}
<form>
<input type="text" id="text">
<input type="checkbox" id="check" name="check">
<input type="button" value="Comment" class="txt2" onclick="return commentForm()">
</form>
<p id="demo"></p>

function commentForm() {
var checkbox = document.getElementById('check').checked;
var text = document.getElementById('text').value;
if (!text) {
alert('please enter some value');
return false;
}
if (!checkbox) {
alert('Please check the checkbox');
return false;
}
else {
document.getElementById('demo').innerHTML += text + "<br>";
return false;
}
}
<form onsubmit="return commentForm()">
<input type="text" id="text">
<input type="checkbox" id="check" name="check">
<input type="submit" value="Comment" class="txt2">
</form>
<p id="demo"></p>
If you want the page not to be redirected you can use the return false in the else statement.

Related

How would you make an iframe if the value is true in javascript?

I have a javascript login page (I know it's not secure!) How would I make the website create an iframe if the value is correct?
I have already tried window.location.assign but doesn't work! When you add any code it deletes the values in the inputs and puts the values you inserted in the url?
<div class="box" id="loginbox">
<h2>Login</h2>
<form id="form1" name="form1" action="" onsubmit="return checkDetails();">
<div class="inputBox">
<input type="text" name="txtusername" id="txtusername" class="info" required />
<label>Username</label>
</div>
<div class="inputBox">
<input type="password" name="txtpassword" id="txtpassword" class="info" required/>
<label>Password</label>
</div>
<input type="submit" name="Login" id="Login" value="Login"/>
</form>
</div>
<script>var remainingAttempts = 3;
function checkDetails() {
var name = form1.txtusername.value;
var password = form1.txtpassword.value;
console.log('name', name);
console.log('password', password);
var validUsername = validateUsername(name);
var validPassword = validatePassword(password);
if (validUsername && validPassword) {
alert('Login successful');
document.getElementById("loginbox").remove();
var next = document.createElement("IFRAME");
next.src = 'https://codepen.io';
next.classList.add("codepen");
document.body.appendChild(next);
} else {
form1.txtusername.value = '';
form1.txtpassword.value = '';
remainingAttempts--;
var msg = '';
if (validPassword) {
msg += 'Username incorrect: ';
} else if (validUsername) {
msg += 'Password incorrect: ';
} else {
msg += 'Both username and password are incorrect: ';
}
msg += remainingAttempts + ' attempts left.';
alert(msg);
if (remainingAttempts <= 0) {
alert('Closing window...');
window.close();
}
}
return validUsername && validPassword;
}
function validateUsername(username) {
return username == 'GG';
}
function validatePassword(password) {
return password == '123';
}</script>
I want the page to create the iframe and remove the login box.
The problem is that you are triggering a form submission when your login button is clicked, which triggers a page load.
<input type="submit" name="Login" id="Login" value="Login"/>
The submit input type type triggers this behaviour. To avoid this, bind to the submit event in the javascript rather than the HTML and use preventDefault() to prevent the page from reloading.
var ele = document.getElementById("loginbox");
if(ele.addEventListener){
ele.addEventListener("submit", checkDetails, false); //Modern browsers
} else if(ele.attachEvent){
ele.attachEvent('onsubmit', checkDetails); //Old IE
}
function checkDetails(e) {
e.preventDefault();
// rest of your code
Code taken from this answer, which you should read for more information about form submission events and how to handle them.

How to check calculation answer of 2 input fields before submitting form

I have a register form with 2 fields includes random int and a result input field for the answer
there's a Javascript code to check fields are not empty when submitting
I'm trying also to calculate the 2 fields and compare it with the result value
Here's the HTML :
<form method="post" id="contactForm" enctype="multipart/form-data" name="q_sign">
<input type="text" name="q_name" id="senderName"/>
<input type="text" name="q_mail" id="senderEmail" />
<input name="val1" type="text" disabled id="val1" value="php random value1" readonly="readonly" />
<input name="val2" type="text" disabled id="val2" value="php random value2" readonly="readonly" />
<input type="text" name="total" id="total" />
<input type="submit" id="sendMessage" name="sendMessage" value="Register" onClick="return check_data(this.form)" />
Javascript part :
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if(document.q_sign.q_name.value==''){
alert("please enter your name");
return false;
}else if(document.q_sign.q_mail.value==''){
alert("please enter your email");
return false;
}else if(document.q_sign.total.value!=(val1+val2)){ //Issue is here
alert("wrong answer");
return false;
}else{
return true;
}}
maybe this is your expect below
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if (document.q_sign.total.value != (eval(val1) + eval(val2))) {
alert("wrong answer");
return false;
} else {
return true;
}
}

onsubmit() form on mobile browser

I current use a javascript function on the onsubmit() event of my form to check if all the input are not empty.
This works fine on computer, but on mobile phone, it changes the background color (as I want to do when the input is empty) but it still submits the form !!!
My form :
<form id="formContact" action="envoi-message.php" method="post" class="normal" onsubmit="return valideChamps();">
<div class="ddl">
<span>VOUS ÊTES...</span>
<div class="ddlOption">
<ul>
<li onclick="ddlContact('entreprise')"><span>UNE ENTREPRISE</span></li>
<li onclick="ddlContact('ecole')"><span>UNE ÉCOLE</span></li>
<li onclick="ddlContact('personne')"><span>UNE PERSONNE</span></li>
</ul>
</div>
</div>
<input class="cache" type="text" name="entreprise" placeholder="NOM DE L'ENTREPRISE" />
<input class="cache" type="text" name="ecole" placeholder="NOM DE L'ÉCOLE" />
<input type="text" name="nom" placeholder="VOTRE NOM" />
<input type="email" name="email" placeholder="VOTRE EMAIL" />
<textarea name="message" placeholder="VOTRE MESSAGE" ></textarea>
<input id="btnEnvoi" type="submit" value="Envoyer">
</form>
My function :
function valideChamps(){
var bResult = true;
if ($("input[name*='nom']").val() == "") {
$("input[name*='nom']").addClass("error");
bResult = false;
} else {
$("input[name*='nom']").removeClass("error");
}
if ($("input[name*='email']").val() == "") {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
var regex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regex.test($("input[name*='email']").val()) == false ) {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
$("input[name*='email']").removeClass("error");
}
}
if ($("#formContact textarea").val() == ""){
$("#formContact textarea").addClass("error");
bResult = false;
}else {
$("#formContact textarea").removeClass("error");
}
if ($("div.ddl > span").text().contains("entreprise")){
if ($("input[name*='entreprise']").val() == "") {
$("input[name*='entreprise']").addClass("error");
bResult = false;
}else {
$("input[name*='entreprise']").removeClass("error");
}
} else if ($("div.ddl > span").text().contains("école")){
if ($("input[name*='ecole']").val() == "") {
$("input[name*='ecole']").addClass("error");
bResult = false;
}else {
$("input[name*='ecole']").removeClass("error");
}
}
return bResult;
}
Do you have any idea about what is wrong...?
Best regards
Audrey
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true
Try registering your submit handler to the form using JS, so you can access the event and call preventDefault() instead of (or in addition to) returning false;
Like so:
document.getElementById('formContact').onsubmit = function(e) {
//your validateChamps stuff goes here
if(!bResult) e.preventDefault();
};
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true

Javascript form validating - how do you show validation errors in a single table rather than using alerts

I am new to .asp and Javascript and wondered if someone was able to advise how to show validation errors for fields below the form in a single table or text field rather than using alerts. Alerts and validation are working.
Here is the table that i plan to put the validation errors into:
<asp:Table ID="StatusTable"
runat="server" Width="100%"><asp:TableRow ID="StatusRow" runat="server">
<asp:TableCell ID="StatusTextCell" runat="server" Width="95%">
<asp:TextBox ID="StatusTextBox" runat="server" Width="100%" />
</asp:TableCell><asp:TableCell ID="StatusPadCell" runat="server" Width="5%">
</asp:TableCell></asp:TableRow></asp:Table>
And here is an example of some the Javascript I am using where i need the validation error messages to show in the table rather than from alerts.
Would be extremely grateful for any advise
< script type = "text/javascript"
language = "Javascript" >
function RequiredTextValidate() {
//check all required fields from Completed Table are returned
if (document.getElementById("<%=CompletedByTextBox.ClientID%>").value == "") {
alert("Completed by field cannot be blank");
return false;
}
if (document.getElementById("<%=CompletedExtTextBox.ClientID %>").value == "") {
alert("Completed By Extension field cannot be blank");
return false;
}
if (document.getElementById("<%=EmployeeNoTextBox.ClientID %>").value == "") {
alert("Employee No field cannot be blank");
return false;
}
if (document.getElementById("<%=EmployeeNameTextBox.ClientID %>").value == "") {
alert("Employee Name field cannot be blank");
return false;
}
return true;
}
< /script>
function ValidateFields() {
//Validate all Required Fields on Form
if (RequiredTextValidate() && CheckDate(document.getElementById("<%=SickDateTextBox.ClientID%>").value) && CheckTime(this) && ReasonAbsent() && ReturnDateChanged() && FirstDateChanged() && ActualDateChanged() == true) {
return true;
}
else
return false;
}
There are many ways that this type of thing can be done, here is one way which I have put together based on what you have so far...
http://jsfiddle.net/c0nh2rke/
function RequiredTextValidate() {
var valMessage = '';
var valid = true;
//check all required fields from Completed Table are returned
if (document.getElementById("test1").value == "") {
valMessage += 'Completed by field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test2").value == "") {
valMessage += 'Completed By Extension field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test3").value == "") {
valMessage += 'Employee No field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test4").value == "") {
valMessage += 'Employee Name field cannot be blank <br />';
valid = false;
}
if (valid) {
return true;
}
else
{
document.getElementById("errors").innerHTML = valMessage;
return false;
}
}
<form >
<input id="test1" type="text" /><br />
<input id="test2" type="text" /><br />
<input id="test3" type="text" /><br />
<input id="test4" type="text" /><br />
<input type="button" value="Submit" onclick="RequiredTextValidate()" />
</form>
<div id="errors"><div>
HTML
<form >
<input id="test1" type="text" /><br />
<input id="test2" type="text" /><br />
<input id="test3" type="text" /><br />
<input id="test4" type="text" /><br />
<input type="button" value="Submit" onclick="RequiredTextValidate()" />
</form>
<div id="errors"><div>
Script
function RequiredTextValidate() {
var valMessage = '';
var valid = true;
//check all required fields from Completed Table are returned
if (document.getElementById("test1").value == "") {
valMessage += 'Completed by field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test2").value == "") {
valMessage += 'Completed By Extension field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test3").value == "") {
valMessage += 'Employee No field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test4").value == "") {
valMessage += 'Employee Name field cannot be blank <br />';
valid = false;
}
if (valid) {
return true;
}
else
{
document.getElementById("errors").innerHTML = valMessage;
return false;
}
}
The best JavaScript is no JavaScript.
To that end, consider:
<form action="javascript:alert('Submitted!');" method="post">
<input type="text" name="someinput" placeholder="Type something!" required />
<input type="submit" value="Submit form" />
</form>
Notice how the browser will render native UI to show that the field was left blank? This is by far the best way to do it because it doesn't rely on JavaScript. Not that there's anything wrong with JS, mind, but far too often a single typo in form validation code has caused hours of debugging!

Basic Validate javascript not working correctly

This is my simple code which I have been working to just show valid or invalid if the wrong text is inserted but the problem I’m having is that when I hit enter the valid and invalid flashes without staying on screen.
Here is my Fiddle
function validate ()
{
var me = document.getElementById("my").value;
if (me == 'my')
{
document.getElementById("Result").innerHTML = "valid";
document.getElementById("Result").style.color = "green";
}
else
{
document.getElementById("Result").innerHTML = "invalid";
document.getElementById("Result").style.color = "red";
}
}
<form>
<button type="button" onclick ="yes" class="fa fa-search"></button>
<input type="text" id="my" onchange="validate()"></input>
<label id="Result"></label>
</form>
What is the mistake i am doing and How can i fix this ?
The problem is that you have your code inside tag. You need to prevent form submission if you want to stay on the page.
I have not included CSS here!!
<div class="container">
<div id="nav">
<div id="search">
<form id="form1">
<button type="button" onclick ="yes" class="fa fa-search"></button>
<input type="text" id="my"></input>
<label id="Result"></label>
</form>
</div>
</div>
</div>
$(document).ready(function(){
$("#form1").submit(function(event){
if ( !validate()) {
alert("Error");
event.preventDefault();
return false;
}
});
});
function validate ()
{
var me = document.getElementById("my").value;
if (me == 'my')
{
document.getElementById("Result").innerHTML = "valid";
document.getElementById("Result").style.color = "green";
return true;
}
else
{
document.getElementById("Result").innerHTML = "invalid";
document.getElementById("Result").style.color = "red";
return false;
}
}
Here is a fiddle. Hope it will help.

Categories