I have written the following form in my html file.
<form name = "myForm" method="post" action="" id="comment_form" class="comment_form" onsubmit="return validateForm()" >{% csrf_token %}
<div class="row-fluid">
<div class="span6">
<input type="text" id="email" name="email" placeholder="Email*">
</div>
<div class="span6">
<input type="text" id="name" name="name" placeholder="Name*">
</div>
</div>
<div class="row-fluid">
<div class="span8">
<textarea name="message" id="txt_message" placeholder="Message*" cols="30" rows="10"></textarea>
</div>
<div class="span4">
<button class="btn " type="button"><i class="li_paperplane"></i>Send message</button>
</div>
</div>
</form>
And I have added this javascript function inside my HTML file
<script>function validateForm()
{
var x=document.forms["myForm"]["name"].value;
var y=document.forms["myForm"]["email"].value;
var a=document.forms["myForm"]["message"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (x==null || x=="" ||y==null||y==""||a==""||a==null)
{
alert("All fields must be filled out");
return false;}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Please enter a valid e-mail address");
return false;
}
else{
alert("Thank you for your response");
return true;
}
}</script>
On click of Send Message button I am not getting any response from the javascript. The code looks fine and the same code is working on another HTML file. What seems to be the problem?
Your "Send Message" button is just a button -- it doesn't submit the form. You can either use an <input type="submit"> or use JavaScript on your <button> to submit the form.
You need to add an onclick event to your button. Add the following attribute to the button
Syntax:
onclick="document.NameOfTheForm.submit();"
So in this syntax you have to add following
onclick="document.myForm.submit();"
Related
I have to do the validation of the input text field.
I would like Js to show an error message through the setCustomValidity() method.
Is it possible?
function checkName() {
var x = document.formUser;
var input = x.name.value;
if (input.length < 3) {
input.setCustomValidity('This field is invalidate');
return false;
}
}
<form name="formUser" id="formUser" action="#" method="POST" onsubmit="return validateForm();">
<div class="section">
<label for="fname">Nome</label>
<input class="form-control" type="text" id="name" required>
</div>
<input type="submit" class="btn btn-primary" value="Invia" onclick="validateForm();">
</form>
You need to call reportValidity() on the input after setting the custom validity message.
Additionally you must call the reportValidity method on the same element or nothing will happen.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity#examples
function checkName() {
const inp = document.getElementById('name');
const val = inp.value;
if (val.length < 3) {
inp.setCustomValidity('This field is invalidate');
inp.reportValidity();
return false;
}
}
<form name="formUser" id="formUser" action="#" method="POST" onsubmit="return checkName();">
<div class="section">
<label for="fname">Nome</label>
<input class="form-control" type="text" id="name" required>
</div>
<input type="submit" class="btn btn-primary" value="Invia" onclick="checkName();">
</form>
I would like to control more text input with javascript.
The setCustomValidity() method means that it will have to show an error message if input has less than three characters.
it doesn't always work.
Eg. If I put a string of one character in the first field and a string of four in the second field; it sends without showing the error. If I repeat the same test, it works.
Why?
window.onload = function() {
const field = document.getElementsByClassName("input-field");
for (let i = 0; i < field.length; i++) {
field[i].addEventListener('input', function() {
const val = field[i];
if (val.length < 3) {
field[i].setCustomValidity('Field is invalid');
}
})
}
}
<form name="formUser" id="formUser" action="#">
<div class="section">
<label for="fname">First name</label>
<input class="form-control input-field" type="text" id="fname" required>
<label for="lname">Last name</label>
<input class="form-control input-field" type="text" id="lname" required>
</div>
<input type="submit" class="btn btn-primary" value="Send">
You could add a <p class="error">...</p> inside your section div.
Hide it with css (display: none) and when you get an error in your validation add a class to that like "show" to show it (display: unset).
You can do custom form validation using Javascript like this.
Here I have just added a div with a warning and alert box. You can do whatever you want.
It will alert a warning if you will click on submit when fields were empty.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
let alertBox = document.getElementById("alert-box");
// Here instead of checking (x == " "), you can use your custom validations
if (x == "") {
alertBox.innerHTML = `<p>Form input are empty</p>`; // appends a div with warning
alert("Name must be filled out"); // alert box
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<div id="alert-box"> </div>
<form name="myForm" action="#" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
I am planning to display a Success message when clicked on the Submit button.
However, I would like to disable or hide the Success message whenever the form is required to fill.
So how can I do it by changing the code in script?
Please help me, I really appreciate your support!
This is my code:
<div class="contact-wrapper">
<main class="flex-container">
<section class="main-content">
<form class="contact-form" action="index.html" method="post" onsubmit="return false">
<input type="text" class="contact-form-text" placeholder="Name" id="name" required/>
<input type="email" class="contact-form-text" placeholder="Email" id="email" required/>
<input type="text" class="contact-form-text" placeholder="Title">
<textarea class="contact-form-text" placeholder="Type your message..."></textarea>
<button>Send</button>
<div class="alert">
<span class="message">Success: You Message Sent Successfully!</span>
</div>
</form>
</section>
<script>
function validateForm() {
var name = document.getElementById('name').value;
var name = document.getElementById('email').value;
}
$('button').click(function(){
$('.alert').addClass("show");
$('.alert').addClass("showAlert");
$('.alert').removeClass("hide");
setTimeout(function(){
$('.alert').addClass("hide");
$('.alert').removeClass("show");
},3000);
});
</script>
Consider hiding the message initially and display it only on successful submission
<div class="alert hide">
<span class="message">Success: You Message Sent Successfully!</span>
</div>
you should show the alert only if the form validation returns true.
function validateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
if(name == '' || name == null || email == '' || email == null){
alert("Please Fill All Required Field");
return false;
}
return true;
}
$('button').click(function(){
if(validateForm()){
// your code for submission
// after successful submission display the alert message
$('.alert').removeClass("hide");
$('.alert').addClass("show");
$('.alert').addClass("showAlert");
}
});
I would suggest you to follow the standard format for form validation and form submission. link here
i want to submit a form with and enter key stroke when the user enters a username and password.I get an alert coming back from my function when the enter key is pressed.But after that it doesnt submit the form. What am i doing wrong?
<form id="myForm" action="#" onsubmit="return false;" >
<div>
<input type="text" id="username" />
</div>
<div>
<input type="password" id="password" />
</div>
<div>
<button type="submit" id="btnLogin" onclick="myFunction(0)">Log in</button>
</div>
<script type="text/javascript">
function myFunction(e) {
if ((e && e.keyCode == 13) || e == 0) {
alert("The form was submitted"); // this alert gets called,but my form doesnt get submitted
document.forms.myForm.submit();
}
}
You can use like this.(Use jquery)
1.Change Input type submit to button
2.Change the code for submitting form
3.Write a keyPress event for the form
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="test.html" >
<div>
<input type="text" id="username" />
</div>
<div>
<input type="password" id="password" />
</div>
<div>
<button type="button" id="btnLogin" onclick="myFunction(0)">Log in</button>
</div>
</form>
<script type="text/javascript">
function myFunction() {
alert("form submitted");
document.getElementById("myForm").submit();
}
$('#myForm').on('keydown', function (e) {
if (e.which === 13) {
myFunction();
}
});
</script>
1) Remove return false from the form onsubmit event.
2) Remove onclick event from the button.
3) Using JS, bind a submit event to the form and do what you need in the event handler, as below:
var loginForm = document.getElementById('myForm');
loginForm && loginForm.addEventListener('submit', myFunction);
function myFunction(event) {
event.preventDefault();
alert("form is about to be submitted...");
loginForm.submit();
}
<form id="myForm">
<div>
<input type="text" id="username" />
</div>
<div>
<input type="password" id="password" />
</div>
<div>
<button type="submit" id="btnLogin">Log in</button>
</div>
</form>
Even better, remove all the JS and keep only the form as in my answer. It would submit the form on enter as that's the default behaviour when there is a button/input with type submit!
You can try this without checking keyCode. You can enter key from any input fields or button inside the form.
function myFunction(e) {
var username = e.target.querySelector('#username');
var password = e.target.querySelector('#password');
if(username.value && password.value){
alert("The form was submitted");
return true;
}
return false;
}
<form id="myForm" action="#" onsubmit="return myFunction(event)">
<div>
<input type="text" id="username" />
</div>
<div>
<input type="password" id="password" />
</div>
<div>
<button type="submit" id="btnLogin">Log in</button>
</div>
</form>
I dont think you really need javascript for this as realistically pressing enter inside a form will usually submit the form.
Notice in the example below that all we are really doing is targeting
the submit event for the form and this also includes hitting the enter
key.
However to satisfy your question
Using jQuery you could try binding the keypress event to the button click submit event.
Something like this:
$("#btnLogin").blur();
$('#btnLogin').focus().click();
p.s. remember to close your <form> tag with </form>
Example
$('#myForm').submit(function() {
var confirmSubmit = confirm("Submit the form?");
if(confirmSubmit)
{
$("#btnLogin").blur();
$('#btnLogin').focus().click();
}
else
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="yourPage.html">
<div>
<input type="text" id="username" />
</div>
<div>
<input type="password" id="password" />
</div>
<div>
<button type="submit" id="btnLogin">Log in</button>
</div>
</form>
I have a little form in my modal which looks like this:
<form name="form" action="" method="post">
<div class="modal-body">
<input type="text" name="edited_id" value="" id="edited_id" class="hidden"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="edited_name" class="form-control" id="edit_name" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="edited_email" class="form-control" id="edit_email" value="">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="edit_submit" class="btn btn-primary" value="Edit user"/>
</div>
</form>
and I want to prevent the form to submit if the user enters an email that it is already in my database. I have the following script:
$("#check_email").click(function() {
var email = $(this).parent().siblings().find("#email").val();
var that = $(this);
$(this).parent().parent().submit(function( event ) {
$.get("php/verify_email.php", {email: email}, function(data){
if(data === "")
{
that.parent().parent().unbind('submit').submit();
}
else {
alert(data);
event.preventDefault();
}
});
});
});
The problem is that if I put the even.preventDefault() in that else condition, the $.get() seems to not trigger, because I guess that the form submits faster. Otherwise if I put the event.preventDefault() right after the .submit(function( event ) { then I can't unbind the submit to work after the user changes the email.
What I am doing wrong?
P.S.
My php file looks like this:
<?php
include "connect.php";
if(isset($_GET['email']) && !empty($_GET['email'])){
$sql = "SELECT * FROM users WHERE email='".$_GET['email']."';";
$result = $conn->query($sql);
if ($result->num_rows > 0){
echo "The email is already in our database. Please try another one!";
}
}
?>
I understand you would like to avoid form sending if email is already used.
At first, where is your magic button to do this :D ?
I added button in example.
You must be sure that your "this" is element you want, creating structure like .parent().parent().parent() everywhere is stupid - one change and everything not work.
Next thing to avoid form submit you must return false; inside submit function, preventDefault() work with <a> or other events like click
And next.. if you send ajax your callback function can back to your browser after your submit click.
For example checkClick -> sendAjax -> submitClick -> ajaxBack
And next :D - PHP: Your form have method="post" but server use $_GET
So.. if you send post you must use $_POST if get than $_GET
This time you used $.get so i dont know your ajax configuration but this can cause errors.
Here is some code but im sure this is not final implementation you want, but it should help :)
sorry for english btw.
html:
<form name="form" action="" method="post">
<div class="modal-body">
<input type="text" name="edited_id" value="" id="edited_id" class="hidden"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="edited_name" class="form-control" id="edit_name" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="edited_email" class="form-control" id="edit_email" value=""> <button type="button" id="check_email" data-dismiss="modal">check</button>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="edit_submit" class="btn btn-primary" value="Edit user"/>
</div>
</form>
javascript:
$("#check_email").click(function() {
var email = $(this).parent().find("#email").val();
var that = $(this);
alert(email);
console.log($(this).parent().parent().parent())
$(this).parent().parent().parent().submit(function( event ) {
$.get("php/verify_email.php", {email: email}, function(data){
if(data === "")
{
that.parent().parent().unbind('submit').submit();
}
else {
alert(data);
event.preventDefault();
}
});
return false;
});
});
I want to valid some fields and I want to show success message $('.alert-success').show(); after user entered all values.
I tried here jsfiddle Now I am able to validate all fields but I don't know how to show success message if all fields are not null.
Html:
<div class="contentContainer">
<div class="alert alert-success hide">Form submitted successfully</div>
<div id="basicInfo">
<div class="toggleContentInnerSec">
<div class="row-fluid">
<div class="span7">
<label>First Name</label> <br>
<p class="hide firstNameErrorMsg error">Please enter first name</p>
<input type="text" name="borrowerBasicDetail.firstName" value="" id="addBorrowers_borrowerBasicDetail_firstName" class="access required" placeholder="Example: 'Sachin' " data-errormsg="firstNameErrorMsg"> <br>
<label>Last Name</label> <br>
<p class="hide lastNameErrorMsg error">Please enter last name</p>
<input type="text" name="borrowerBasicDetail.lastName" value="" id="addBorrowers_borrowerBasicDetail_lastName" class="access required" placeholder="Example: 'Tendulkar' " data-errormsg="lastNameErrorMsg"> <br>
<label>Date Of Birth</label> <br>
<p class="hide birthDayErrorMsg error">Please enter date of birth</p>
<input type="text" name="borrowerBasicDetail.age" value="" id="addBorrowers_borrowerBasicDetail_age" class="access required" placeholder="DD/MM/YYYY" data-errormsg="birthDayErrorMsg"> <br>
</div>
</div>
</div>
</div>
<div class="row-fluid pull-left">
<div class="form-actions">
<a class="btn btn-success btn-large" id="tabOneSubmit">Submit</a>
</div>
</div>
</div>
Script:
submit();
function submit(){
$('#tabOneSubmit').click(function(){
$('.required').each(function(){
var element=$(this);
var elementVal=$(this).val();
var errorMsgId=element.attr('data-errorMsg');
if(elementVal==''){
$('.'+errorMsgId).show();
element.addClass('errorField');
}
else{
$('.'+errorMsgId).hide();
element.removeClass('errorField');
}
});
});
}
Here is the solution, just set a status variable.
submit();
function submit(){
$('#tabOneSubmit').click(function(){
var status=true;
$('.required').each(function(){
var element=$(this);
var elementVal=$(this).val();
var errorMsgId=element.attr('data-errorMsg');
if(elementVal==''){
$('.'+errorMsgId).show();
element.addClass('errorField');
status=false;
}
else{
$('.'+errorMsgId).hide();
element.removeClass('errorField');
}
});
if(status) {
$('.alert-success').show();
}
});
}
Demo
$("#msg").html("Form was submitted");
First, using validator is a good thing but I suggest you check inputs in server side too, because it's easy to hack javascript code.
Secondly you need the encapsulate that your input fields via;
<form method="POST or GET" action="foo.html"> </form>
Then you can use jQuery submit() method to submit via javascript:
$(form).submit(function(){
$('.alert-success').show();
event.preventDefault(); // if you want to send data only, do not reload page.
});
$(form) can be like if form has id or class: $('.myForm') , $('#myForm')