This question already has answers here:
Clicking a button within a form causes page refresh
(11 answers)
Closed 1 year ago.
I was just practising HTML DOM and Forms, and I wrote a simple code, in which we take values from the form and display them in a <p> tag :
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
<script>
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
</script>
</body>
</html>
The problem is that when I press submit, the "hi" is replaced by " David Beckham " just for a millisecond, and is again changed to "hi". So by pressing submit continuously, I can see the text being changed again and again.
I don't understand what is happening, It is working, but it is not working. I don't see any errors in the code. Maybe it's code-related, or browser-related, or machine-related.
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I don't why, but it is working in this snippet, but now in my browsers. I am using Macbook Air. I tried running it on both Safari and Chrome. Any help would be appreciated.
That is because onsubmit it will submit the form and refresh the form. So stop the default behaviour using event.preventDefault
function getFormvalue(e) {
e.preventDefault();
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML = text;
}
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue(event)">
First name: <input type="text" name="fname" value="David"><br> Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
You need to prevent form submision
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="event.preventDefault(); getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I am novice in jQuery but trying to learn something very basic. I am just trying to build up auto increment/decrement input fields like this:
<!DOCTYPE html>
<html>
<head>
<link href="stile_prenota.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button class="bottone piu">+</button>
<button class="bottone meno">-</button>
</div>
<script>
$(document).ready(function(){
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
</script>
</body>
</html>
Why if i put the div inside a form it doesn't work?
EDIT Thank you very much
Buttons are submit type by default. So when you put it inside the form and click on button your form gets submitted. Changing the type will solve your problem like this
<!DOCTYPE html>
<html>
<head>
<link href="stile_prenota.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button type="button" class="bottone piu">+</button>
<button type="button" class="bottone meno">-</button>
</div>
</form>
<script>
$(document).ready(function() {
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
</script>
</body>
</html>
The form submites because buttons are `type="submit" by default and submit the form. So set the type to button so they do not submit
<button type="button" ..>
Buttons are by default submit here is a working version:
$(document).ready(function(){
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button type="button" class="bottone piu">+</button>
<button type="button" class="bottone meno">-</button>
</div>
</form>
So the two Functions (chForumular() and validate_user_text()) have both to be true to submit the form. Right now you cant send the form without fil in the username, age(in the code Alter) and your E-Mail. but the second function (validate_user_text) should check if there is any swear word in the message (=Nachricht) right know it submits the form after you fil in the three fields (e-mail, name and age). iven if you type in an swearword in the textarea. (something like: sorry ((asshole)))
If you dont understand a Word you think could be important just write the word to me so I can translate...(German and Swissgerman Words in the Code)
Here is my code so far:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/kontakt.css" media="screen">
<title>Kontaktseite</title>
<meta charset="utf-8">
<script type="text/javascript">
function chkFormular () {
if (document.Formular.User.value == "") {
alert("Enter your Name, Please!");
document.Formular.User.focus();
return false;
}
// if (document.Formular.Ort.value == "") {
// alert("Bitte Ihren Wohnort eingeben!");
// document.Formular.Ort.focus();
// return false;
// }
if (document.Formular.Mail.value == "") {
alert("Enter your E-Mail, please!");
document.Formular.Mail.focus();
return false;
}
if (document.Formular.Mail.value.indexOf("#") == -1) {
alert("No valid E-Mail, address!");
document.Formular.Mail.focus();
return false;
}
if (document.Formular.Alter.value == "") {
alert("Enter your Age, please!");
document.Formular.Alter.focus();
return false;
}
var chkZ = 1;
for (i = 0; i < document.Formular.Alter.value.length; ++i)
if (document.Formular.Alter.value.charAt(i) < "0" ||
document.Formular.Alter.value.charAt(i) > "9")
chkZ = -1;
if (chkZ == -1) {
alert("Your Age is not a Number!");
document.Formular.Alter.focus();
return false;
}
}
</script>
<script language="JavaScript1.2">
// Word Filter
// (c) 2002 Premshree Pillai
// http://www.qiksearch.com
// http://javascript.qik.cjb.net
var swear_words_arr=new Array("arschloch","idiot","terror", "wixer", "wixxer", "hure", "hurensohn", "hurenson", "motherfucker", "neger", "sauhund", "arsch", "fuck", "fucking", "shit", "satan",
"satanus", "figge", "ficken", "scheiss", "drecksjude", "drecksjud", "i hoff du stirbsch", "geh sterben", "verrecken", "verreck doch", "chrüppel", "krüppel", "chrüpel", "krüpel", "saftsack",
"sackratte", "god damit", "goddamit", "godvertammi", "gopfetammi", "chrüzsatan", "gottvertammi", "gottpfertami", "gopfeteckel", "verflucht", "verfluecht", "damisiech", "ich hoffe du stirbst",
"stirb", "geh sterben", "ass", "asshole", "cunt"); //corrected commas
var swear_alert_arr=new Array;
var swear_alert_count=0;
function reset_alert_count()
{
swear_alert_count=0;
}
function validate_user_text()
{
reset_alert_count();
var compare_text=document.Formular.user_text.value;
for(var i=0; i<swear_words_arr.length; i++)
{
for(var j=0; j<(compare_text.length); j++)
{
if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
{
swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var alert_text="";
for(var k=1; k<=swear_alert_count; k++)
{
alert_text+="\n" + "(" + k + ") " + swear_alert_arr[k-1];
}
if(swear_alert_count>0)
{
alert("The following Words are not allwoed:\n_______________________________\n" + alert_text + "\n_______________________________");
document.Formular.user_text.select();
}
else
{
document.Formular.submit();
}
}
function select_area()
{
document.Formular.user_text.select();
}
window.onload=reset_alert_count;
</script>
</head>
<body>
<h1>Kontaktformular</h1>
<nav>
<ul class="nav">
<li>Zurück</li>
</ul>
</nav>
<div id="part1">
<form name="Formular" action="http://www.formular-chef.de/fc.cgi" enctype="multipart/form-data" method="post" onSubmit="return chkFormular()">
<input type="hidden" name="empfaenger" value="benjamin.laubeX§Xbrueggli.ch">
<!--<input type="hidden" name="empfaenger" value="dominik.widmerX§Xbrueggli.ch">-->
</div>
<div id="part2">
<pre>
Name: <input type="text" size="40" name="User"><br>
E-Mail: <input type="text" size="40" name="Mail"><br>
Alter: <input type="text" size="40" name="Alter"><br>
Geschlecht: <select name="geschlecht">
<option selected>-</option>
<option>männlich</option>
<option>weiblich</option>
</select>
</div>
<p id="nachricht">Deine Nachricht:</p>
<div id="part3">
<textarea rows="10" cols="40" name="user_text" onclick="select_area()" placeholder="Ihre Nachricht..."></textarea>
</div>
<div id="part4">
Zum Absenden muss eine Internet-Verbindung bestehen!
<br><br>
<input type="submit" value="Absenden" onclick="validate_user_text();"><input type="reset" value="Abbrechen">
</div>
</pre>
</form>
</body>
</html>
This should do the trick:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/kontakt.css" media="screen">
<title>Kontaktseite</title>
<meta charset="utf-8">
<script type="text/javascript">
function chkFormular () {
if (document.Formular.User.value == "") {
alert("Enter your Name, Please!");
document.Formular.User.focus();
return false;
}
// if (document.Formular.Ort.value == "") {
// alert("Bitte Ihren Wohnort eingeben!");
// document.Formular.Ort.focus();
// return false;
// }
if (document.Formular.Mail.value == "") {
alert("Enter your E-Mail, please!");
document.Formular.Mail.focus();
return false;
}
if (document.Formular.Mail.value.indexOf("#") == -1) {
alert("No valid E-Mail, address!");
document.Formular.Mail.focus();
return false;
}
if (document.Formular.Alter.value == "") {
alert("Enter your Age, please!");
document.Formular.Alter.focus();
return false;
}
var chkZ = 1;
for (i = 0; i < document.Formular.Alter.value.length; ++i)
if (document.Formular.Alter.value.charAt(i) < "0" ||
document.Formular.Alter.value.charAt(i) > "9")
chkZ = -1;
if (chkZ == -1) {
alert("Your Age is not a Number!");
document.Formular.Alter.focus();
return false;
}
return true;
}
</script>
<script language="JavaScript1.2">
// Word Filter
// (c) 2002 Premshree Pillai
// http://www.qiksearch.com
// http://javascript.qik.cjb.net
var swear_words_arr=new Array("arschloch","idiot","terror", "wixer", "wixxer", "hure", "hurensohn", "hurenson", "motherfucker", "neger", "sauhund", "arsch", "fuck", "fucking", "shit", "satan",
"satanus", "figge", "ficken", "scheiss", "drecksjude", "drecksjud", "i hoff du stirbsch", "geh sterben", "verrecken", "verreck doch", "chrüppel", "krüppel", "chrüpel", "krüpel", "saftsack",
"sackratte", "god damit", "goddamit", "godvertammi", "gopfetammi", "chrüzsatan", "gottvertammi", "gottpfertami", "gopfeteckel", "verflucht", "verfluecht", "damisiech", "ich hoffe du stirbst",
"stirb", "geh sterben", "ass", "asshole", "cunt");
var swear_alert_arr=new Array;
var swear_alert_count=0;
function reset_alert_count()
{
swear_alert_count=0;
}
function validate_user_text()
{
reset_alert_count();
var compare_text=document.Formular.user_text.value;
for(var i=0; i<swear_words_arr.length; i++)
{
for(var j=0; j<(compare_text.length); j++)
{
if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
{
swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
swear_alert_count++;
}
}
}
var alert_text="";
for(var k=1; k<=swear_alert_count; k++)
{
alert_text+="\n" + "(" + k + ") " + swear_alert_arr[k-1];
}
if(swear_alert_count>0)
{
alert("The following Words are not allwoed:\n_______________________________\n" + alert_text + "\n_______________________________");
document.Formular.user_text.select();
}
else
{
return true;
}
}
function select_area()
{
document.Formular.user_text.select();
}
window.onload=reset_alert_count;
</script>
</head>
<body>
<h1>Kontaktformular</h1>
<nav>
<ul class="nav">
<li>Zurück</li>
</ul>
</nav>
<div id="part1">
<form id="frmFormular" name="Formular" action="http://www.formular-chef.de/fc.cgi" enctype="multipart/form-data" method="post">
<input type="hidden" name="empfaenger" value="benjamin.laubeX§Xbrueggli.ch">
<!--<input type="hidden" name="empfaenger" value="dominik.widmerX§Xbrueggli.ch">-->
</div>
<div id="part2">
<pre>
Name: <input type="text" size="40" name="User"><br>
E-Mail: <input type="text" size="40" name="Mail"><br>
Alter: <input type="text" size="40" name="Alter"><br>
Geschlecht: <select name="geschlecht">
<option selected>-</option>
<option>männlich</option>
<option>weiblich</option>
</select>
</div>
<p id="nachricht">Deine Nachricht:</p>
<div id="part3">
<textarea rows="10" cols="40" name="user_text" onclick="select_area()" placeholder="Ihre Nachricht..."></textarea>
</div>
<div id="part4">
Zum Absenden muss eine Internet-Verbindung bestehen!
<br><br>
<input type="submit" id="sendButton" value="Absenden">
<input type="reset" value="Abbrechen">
<script>
document.getElementById('sendButton').onclick = function() {
if (chkFormular() && validate_user_text()) {
document.formular.submit();
return true;
} else {
return false;
}
}
</script>
</div>
</pre>
</form>
</body>
</html>
Just change the submit part.
onSubmit="return chkFormular() && validate_user_text()"
I want to use jquery to fadein a div, but it's not working. If I set the visibility to hidden of 'fout' (thats the element I want to fadein) then it doesn't show aything, although the messages are still there, since I can see the scrollbar moving. Any idea why they are not fading in?
So again, I want the 'fout' div to fadein after submit.
The code I have right now.
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
<title>Form</title>
</head>
<script type="text/javascript" src="js/validate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
// initialisatie formulier validatie. (zie http://rickharrison.github.io/validate.js)
var validator = new FormValidator('form', [{
name: 'voornaam',
display: 'Voornaam',
rules: 'required'
}, {
name: 'achternaam',
display: 'achternaam',
rules: 'required'
},{
name: 'telefoonnummer',
display: 'telefoon',
rules: 'required|numeric'
},{
name: 'email',
display: 'email',
rules: 'required|valid_email'
}], function(errors, event) {
var berichten = document.getElementById('fout');
$("#fout").css("display","none");
$("#fout").css("display","block").fadeIn('slow');
berichten.innerHTML = '';
// als er fouten zijn:
if (errors.length > 0) {
for (var i = 0, l = errors.length; i < l; i++) {
berichten.innerHTML += errors[i].message + '<br>';
}
// als de validatie goed gegaan is:
} else {
var voornaam = $('#voornaam').val();
var achternaam = $('#achternaam').val();
var telefoonnummer = $('#telefoonnummer').val();
var email = $('#email').val();
$.post('action.php',{action: "button", voornaam:voornaam, achternaam:achternaam, telefoonnummer:telefoonnummer, email:email},function(res){
$('#result').html(res);
});
$('#insert').remove();
document.getElementById('goed').innerHTML = 'Verstuurd!';
}
// voorkom ten allertijde dat het formulier daadwerkelijk ge-submit wordt!
event.preventDefault();
});
});
</script>
<body>
<div id="wrap">
<table>
<td>
<form name="form">
<tr>
<p class="names">Voornaam:</p> <p><input type="text" name="voornaam" id="voornaam"></p>
</tr>
<tr>
<p class="names">Achternaam:</p> <p><input type="text" name="achternaam" id="achternaam"></p>
</tr>
<tr>
<p class="names">Telefoonnummer:</p> <p><input type="text" name="telefoonnummer" id="telefoonnummer"></p>
</tr>
<tr>
<p class="names">Emailadres:</p> <p><input type="text" name="email" id="email"></p>
</tr>
<tr>
<input class="knop" type="submit" name="insert" value="Opsturen" id="insert">
</tr>
</form>
</td>
</table>
<br>
<div id="fout"></div>
</div>
<div id="goed"></div>
</div>
</body>
</html>
My css properties of fout:
#fout
{
visibility:hidden;
margin-left:-75px;
display:block;
font-size:15px;
background-color:#D73033;
width:350px;
font-family:"Myriad Pro";
color:#FFFFFF;
text-align:center;
border-radius:2px;
}
That's because fadeIn() works with the property display not with visibility. Then you may need to set in your div:
display:none
Then if you have this lines of code are worng:
$("#fout").css("display","none");
$("#fout").css("display","block").fadeIn('slow');
Change it just to make the FadeIn work :
$("#fout").fadeIn('slow');
Check this http://jsfiddle.net/hGu4E
my intension is to send a hidden count value form view to controller in spring mvc,everything is working but iam not getting the count in the controller,plese do some favour
my view is
<HTML>
<HEAD>
<script type="text/javascript" src="resources/js/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var i = 1;
//var c = 0;
$("#AddSection").click(function() {
i++;
$("<div />").append($("<input />", {
type: "text",
name: "Section" + i
})).appendTo("#someContainer");
//c = i;
document.getElementsByName("Count").Value = i;
alert(i);
});
$("input").live("click", function() {
$("span").text("Section: " + this.name);
});
});
</SCRIPT>
</HEAD>
<BODY>
<form method="get" action="addProfile">
ProfileName<input type="text" name="pname"><br />
SectionName<input type="text" name="Section1">
<input type="button" id="AddSection" value="AddSection">
<div id="someContainer"></div>
<input type="hidden" id="hiddenSection" name="Count" />
<span></span> <input type="submit" value="save">
</form>
</BODY>
</HTML>
You have a typo:
document.getElementsByName("Count").Value = i;
// ^----Typo!
value is lowercase:
document.getElementsByName("Count")[0].value = i;
// ^----Fixed!
// ^-------- return HTML Collection, take first.
Better use id:
document.getElementById("hiddenSection").value = i;
You're using jQuery, so you can use one of the following:
$("#hiddenSection").val(i);
$('input[name="Count"]').val(i);