<form id="loginForm">
<p id="usernameLabel">Username:</p>
<input type="text" name="username" id="username" placeholder="username"/><br>
<p id="passwordLabel">Password: </p>
<input type="password" name="password" id="password" placeholder="password"/><br>
<input id="loginButton" type="submit" value="Login!" onsubmit="validateForm()">
</form>
<p id="loginMessage">Please Login!</p>
<script type="text/javascript">
function validateForm() {
var un = document.loginForm.username.value;
var pw = document.loginForm.password.value;
var username = "MitchWardle";
var password = "123abc456";
if ((un == username) && (pw == password)) {
window.location = "content.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
I have created a little login form on Javascript and I want it to navigate to Content.html when username and password are correct but when I click my Login button it just removes the text from the text box's, can anybody see whats wrong?
you need to return false to prevent default action of submitting the form , page gets refresh andyou loss your data, you can set type of submit button to
type="button"
or can change onsubmit to
onclick="validateForm(); return false; "
Just a couple things are off, but it's almost there:
The onsubmit handler is used at the form level. Either move the onsubmit to the <form> element or change it to an onclick event for the <input> element.
In order to reference the text fields the way you are, the <form> element also needs a name attribute. i.e. name="loginForm"
Do this:
Remove onsubmit from button add it to form.
Change id of form to name.
In the onsubmit of form append return false;.
Remove return false; from the if statements.
Change document.loginForm line to this:
document.forms['loginForm'].elements['username'].value //username/password depends.
Hope it works.
I have had the same problem as you before, and I solved it by changing the submit button to <input type="button" onclick="login();" />, and everything worked. However, the user then cannot submit the form with enter key (because there's no submit button in the form).
Related
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.
I have a form with one field that the user needs to type into, and a button underneath that when clicked, does some jQuery and hides the login-form. But when I hit enter after typing something in, the page refreshes...
There's part of me that thinks it doesn't need to be an <input> or a <form>
I don't actually need to post anything. I have tried changing the input to a <button> which completely ruins my styling and still doesn't work. What's the best way of getting round this?
<div class="login-page">
<div class="form">
<form class="login-form" method="POST">
<!-- user inputs -->
<p class="phc">PHC:</p><input type="text" id="username" placeholder="Enter Your PHC Here" />
<!-- your submit button -->
<input class="login" type="button" id="submit" value="login">
</div>
True, Adam. If the form does not contain the type submit button, a keypress event has to be added manually. Otherwise Enter will act as the Accept Button on the form.
You need to attach keypress event to the form or at least the field. For convenience, you also need to combine the callback functions into one.
$('#username').on('keypress', function(event){
var code = event.keyCode || event.which;
if(code == 13){
// submit the form.
}
});
$('#username').on('keypress', function(event){
var code = event.keyCode || event.which;
if(code == 13){
console.log('Submitting form');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="login-form" method="POST">
<p class="phc">PHC:</p><input type="text" id="username" placeholder="Enter Your PHC Here" />
<input class="login" type="button" id="submit" value="login">
</form>
If the enter key is pressed when focused to an input field inside a form that has a submit button, the default browser behaviour is to fire a submit event on that form. You can prevent this happening by either:
return false;
or
e.preventDefault();
Full code:
$('.login-form').on('submit', function() {
return false;
});
Fiddle: https://jsfiddle.net/nc1e2gm6/
Bear in mind that if you go down the route of using e.preventDefault(); instead or return false;, you need to pass the e variable from the function call, like:
$('.login-form').on('submit', function(e) { ...
Don't think i explained it very well but i have fixed it, the enter key now activates the submit button rather than refresh the page.
$("form").submit(function() { return false; });
$(document).ready(function(){
$('#username').keypress(function(e){
if(e.keyCode==13)
$('#submit').click();
});
});
I'm trying to make code for a simple password checker that will be part of a website I give to students for an activity. I don't care if the password is easy to find in the code. I just want the students to be able enter a password, and press enter or click the button to see if the password is correct.
This is the javascript:
<script type="text/javascript">
function isValid(){
var keyvalue = document.getElementById('keyvalue').value;
if (keyvalue == "miranda")
{document.getElementById('welcomeDiv').style.display = "block";}
else
{alert('ACCESS DENIED')}
}
</script>
The HTML
<form name="PasswordField" action="">
Type Password Below:</br>
<input type="text" id="keyvalue" name="keyvalue" onkeydown = "if (event.keyCode == 13) document.getElementById('subPass).click()">
<input type="button" id="subPass" value="ACCESS" onclick="isValid(this);">
</form>
<div id="welcomeDiv" style="display:none;" class="answer_list">
</br>
<p>ACCESS GRANTED</p></br>
Click to go to next stage.
</div>
Clicking the button works well, but if I press enter it will flash the hidden div briefly before reloading the page, thus hiding the div again. I'm trying to figure out how to prevent it from doing this.
Your action="" is probabaly not doing what you what it to.
Use `onsubmit="return false;"' instead:
<form name="PasswordField" onsubmit="return false;">
Type Password Below:</br>
<input type="text" id="keyvalue" name="keyvalue" onkeydown = "if (event.keyCode == 13) document.getElementById('subPass').click()">
<input type="button" id="subPass" value="ACCESS" onclick="isValid(this);">
</form>
Or just make it a <div instead of a <form
The button is submitting the form, reloading the page.
In the onclick attribute of your button you need to return false to override the browser's default behaviour of actually sending the form:
<input type="button" id="subPass" value="ACCESS" onclick="isValid(this); return false">
As Marvin mentioned in a comment you also need to fix the quotes in the onkeydown attribute of your text input and remove some extra spaces:
<input type="text" id="keyvalue" name="keyvalue" onkeydown="if (event.keyCode == 13) document.getElementById('subPass').click()">
I have a form like this
<form action="http://example.com/search" method="get">
<input type="text" name="q">
<input type="submit">
</form>
When I fill parameter q with some text (e.g. 'AAAAA') and submit this form, the url become to http://example.com/search?q=AAAAA.
But, I want add some text to parameter q with other text before submit. For example, if user input 'AAAAA' the parameter become 'AAAAA BBBBB CCCCC'. So the url become to http://example.com/search?q=AAAAA+BBBBB+CCCCC.
Use JavaScript to modify the value before submit. Add an onsubmit event to the form which will get fired when you submit the button. Like this...
<form action="http://example.com/search" method="get" onsubmit="return addText();">
<input type="text" name="q" id="q">
<input type="submit">
</form>
<script>
function addText(){
document.getElementById("q").value += " BBBB CCCC"; // Whatever your value is
return true;
}
</script>
Watch my example on jsFiddle http://jsfiddle.net/ilya_kolodnik/N9gWm/
var text_to_append = "test";
$('form').submit(function(obj) {
obj.preventDefault();
alert($("input[name='q']").val());
$("input[name='q']").val($("input[name='q']").val() + text_to_append);
this.submit();
});
At first we handle 'submit' action on form. To prevent form submit we use preventDefault(); Than we modify our query and submit the form.
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>