Javascript setting value of textbox by function, without getting reset - javascript

My goal is to have a text box and a button. If I enter "Hello" in the text box and press the submit button I would like to have see the text box filled with "World.
For the moment the value of the text box will be changed betweeen the
<html>
<body>
<script>
function validateForm() {
var x = document.forms["myForm"]["Input"].value;
if (x == "Hello") {
alert("test");
document.getElementById("Input").value = "World";
alert("test2");
}
}
</script>
<form name="myForm" action="test.html" onsubmit="return validateForm()" method="post">
Input: <input type="text" id="Input"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

The problem is that the form gets submitted right after the validation. So you are redirected to test.html again.
If you don't want that to happen, add event.preventDefault(); to your Event Handler (check out the fiddle to see it working):
<html>
<body>
<script>
function validateForm(event) {
event.preventDefault();
var x = document.forms["myForm"]["Input"].value;
if (x == "Hello") {
alert("test");
document.getElementById("Input").value = "World";
alert("test2");
}
}
</script>
<form name="myForm" action="test.html" onsubmit="return validateForm(event)" method="post">
Input: <input type="text" id="Input"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
You can learn more about event.preventDefault() at MDN.
Just as a sidenote: It is generally better to use addEventListener instead of the onsubmit attribute (Better separation of concerns, you can add multiple event listeners, etc.).

When you submit your page, then the content in the action page will be loaded.
In your case test.html will be loaded.
If you want the value "World" to be shown in the text box on hitting the submit, then return false on your validateForm() method.

Use return false; to stay on the same page and stop form submission.
function validateForm() {
var x = document.forms["myForm"]["Input"].value;
if (x == "Hello") {
document.getElementById("Input").value = "World";
return false;
}
}

Related

Can't get input validation Javascript to work

Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.

Validate before going to next page

Peeps,
I see this question has been asked but they either don't have validation function right or there are some syntax errors.
Here is my code; it is supposed to check fields are not blank then if they are not blank it passes them to the next page.
What happens with my codes is that it does check the validation but right after the Alert pop-up it goes to the next page. My intention is to not go to the next page unless all fields are filled.
Any hints would be greatly appreciated.
<html>
<head>
<script type="text/javascript">
function RegValidation() {
var txtURL,
if (!txtURL) {
alert("URL is mandatory!");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="RegisterForm" action="RegConfirm.php" method="post">
<p><input type="text" name="txtURL"></p>
<p><input type="submit" value="Register" onclick="Register()"></p>
</form>
</body>
<script type="text/javascript">
function Register() {
if (!RegValidation()) return;
}
</script>
Instead of onclick function on submit button try onsubmit in form tag..
the working code of the jsfiddle is here
<form name="RegisterForm" action="RegConfirm.php" method="post" onSubmit="return Register()">
<p><input type="text" name="txtURL" id="txtURL"></p>
<p><input type="submit" value="Register"></p>
</form>
function Register() {
return RegValidation();
}
function RegValidation() {
var txtURL = document.getElementById('txtURL').value;
if (!txtURL) {
alert("URL is mandatory!");
// txtURLFocus();
return false;
}
return true;
}
you need to assign the value of the field to the var you are testing
You need a focus function that is not defined in the code you gave.
You now only execute a function on click instead of returning it. It is not recommended to assign handlers to a submit button so I have assigned it to the submit event where it belongs
Here is an unobtrusive working version
window.onload = function() {
document.getElementById("RegisterForm").onsubmit = function() {
var txtURL = this.txtURL.valuel
if (!txtURL) {
alert("URL is mandatory!");
this.txtURL.focus();
return false;
}
return true;
}
}
<form name="RegisterForm" id="RegisterForm" action="RegConfirm.php" method="post">
<p><input type="text" name="txtURL"></p>
<p><input type="submit" value="Register"></p>
</form>

PHP form submit button but not leave page

I have a button that links to a php file that tracks user's email when clicked, but I don't want the user to leave the page when button is clicked, I just want to change button's value.
This is the html of the form.
<form action="mysql-query.php" method="post">
<input type="text" name="email" style="display:none;">
<input type="submit" value="Press here" id="test" onclick="Press()">
</form>
And this is the script that handles the form:
<script>
function Press() {
var test= document.getElementById("test");
test.value="Thank you";
localStorage.value=("ok");
}
</script>
I put the display:none; because I don't want to display anything but the button and have a way to connect with my php file.
Any ideas?
You need to use ajax:
html:
<form action="mysql-query.php" method="post" onsubmit="return Press(this)">
<input type="text" name="email" style="display:none;">
<input type="submit" value="Press here" id="test">
</form>
js:
function Press(form) {
$.post($(form).attr('action'), function() {
var test= document.getElementById("test");
test.value="Thank you";
localStorage.value=("ok");
});
return false; // prevent submitting the form
}
or better bind submit event using jQuery:
$('form').submit(function() {
$.post($(this).attr('action'), function() {
var test= document.getElementById("test");
test.value="Thank you";
localStorage.value=("ok");
});
return false; // prevent submitting the form
});
Use:
<form action="javascript:void()">
Ok, this thing prevents the form from sending the data anywhere, unless you use "onclick" event on the submit button.
What you can do is remove the type="submit" on the button and replace it with type="button". Next you can do an ajax call to your php and do your magic.

my jquery form validation is not working as i hope it should

I have some javascipt code here that validates a user form. When the user inputs the correct answer it tells them and gives them the link to the next question. At least, that's what it is supposed to do. When i click the form it reloads the page but it should not because i added return false.
the div tra holds 35
and the div usermsg is the user inputted value.
<script>
$("#submit").click(function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6<>rightanswer)
{
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else
{
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
</script>
Any ideas why this is not working?
It should be
if (clientmsg6 != rightanswer)
not
if (clientmsg6<>rightanswer)
To prevent a form submission, you need to return false on the form itself instead of on the submit button. Your code should become:
HTML
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="submit" value="Submit" />
</form>
JS (please note the line where you have clientmsg6, you have a syntax error)
$("#myform").on('submit', function(){
var clientmsg6 = $("#usermsg").val();
var rightanswer = $("#tra").val();
if (clientmsg6 != rightanswer) { //This line was also wrong, should be != instead of <>
$("#confirm").html("<h2>Sorry, wrong answer.</h2>");
}
else {
$("#confirm").html("<a href='#' onclick='play();' style='font-size:20px;' id='new1'>Click here for Question 2</a>");
}
return false;
});
Alternatively, you can keep your existing code by changing your submit button to be just a plain old button, but you will lose the extra functionality of the user being able to hit the enter key and performing the same action.
<form action="page.php" method="post">
<input id="usermsg" type="text" name="answer" />
<input id="submit" type="button" value="Submit" />
</form>
Instead of using .html(), try using .text()
if #submit is a link tag otherwise use the form ID and the submit event
$("#submit").click(function(e){
e.preventDefault()
...
...
...
});
You need to attach handlers once the document has finished loading.
Wrap your script in the following
<script>
$(function() {
// script
});
</script>

html form with multiple submitbuttons

I have 2 submit buttons in an HTML form.
How can I know which submit button has triggered the JavaScript function?
<script language="javascript" type="text/javascript">
function verifyData(formdata) {
// Here I want to know from which submit button this function is triggered
// I can't use type button instead of submit
// I can't use onclick handler
// I can't use JQuery.. I want to do only with javascript
}
</script>
<form onsubmit="verifyData(this);" method="post">
<input type="submit" value="submit1">
<input type="submit" value="submit2">
</form>
<button value="delete row" id="but1" onclick="disps()">delete row</button>
I want to do different actions based on the different submit buttons clicked.
It is not possible to check the button clicked through the onsubmit event. Instead move the call to verifyData() to the onclick handler of each button. Use return in the onclick call to cancel submission if false is returned by verifyData()
<script language="javascript" type="text/javascript">
function verifyData(button) {
// validate
switch (button.value) {
case "submit1":
// do somehting
break;
case "submit2":
// do somehting
break;
// ...
};
// submit the form
return true;
}
</script>
<form method="post">
<input type="submit" value="submit1" onclick="return verifyData(this);">
<input type="submit" value="submit2" onclick="return verifyData(this);">
</form>
How about putting an onclick event handler on both buttons which will set a variable to say which button was clicked?
like so:
<script language="javascript" type="text/javascript">
function verifyData(formdata) {
alert(btnClicked);
// Here I want to know from which submit button this function is triggered
// I can't use type button instead of submit
}
var btnClicked = 0;
function setSubmit(which) {
btnClicked = which; return true;
}
</script>
<form onsubmit="verifyData(this);" method="post">
<input type="submit" value="submit1" onclick="return setSubmit(1);">
<input type="submit" value="submit2" onclick="return setSubmit(2);">
</form>
Are you allowed to use the jQuery library?
If you can using this you can easily bind to each submit button based on an id.
For example:
<form id="form1" method="post">
<input type="submit" value="submit1" id="submit1">
<input type="submit" value="submit2" id="submit2" >
</form>
<script type="text/javascript">
$("#submit1").click(function(e)
{
// Do stuff when 1 is clicked.
$("#form1").submit();
});
$("#submit2").click(function(e)
{
// Do stuff when 2 is clicked.
$("#form1").submit();
});
</script>
you could also have the buttons as a type of button to avoid any issues, but you should be able to simply return false; to stop the button of type submit from... submitting
Here is how I would do it... Firstly I would use jQuery so you must include that in your document like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
It would also mean your HTML can be simplified to:
<form method="post">
<input type="submit" value="submit1"/>
<input type="submit" value="submit2"/>
</form>
Then you can use jQuery:
<script>
// When the document is ready
$(function(){
// Action performed when a submit button in the form is clicked
$("form[type='submit']").click(function(e){
// Get the value attribute
var val = $(this).val(),
validation_has_passed = false;
// If it is submit1
if(val == "submit1") {
// Validate submit 1
validation_has_passed = true;
// If it is submit2
} else if(val == "submit2") {
// Validate submit 2
validation_has_passed = true;
}
// If all validation is OK submit the form
if(validation_has_passed === true) {
$("form").submit();
}
// Ensure pressing these buttons doesn't submit the form
e.preventDefault();
});
});
</script>

Categories

Resources