I've seen this appear in a lot of places; however, after several hours, I still can't figure this simple thing out. Could someone verify my syntax is correct here?
$(document).ready(function(){
$("#login-form").on('submit', "#logout-btn", function() {
alert("The logout button was clicked.");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<input placeholder="Username" id="formUsr" required>
<input type="password" placeholder="Password" id="formPwd" required>
<input id="logout-btn" type="submit" value="Login">
<input id="login-btn" type="submit" value="Logout">
</form><!-- login form -->
The submit event is triggered when a submit button is clicked, and there could be more than one, a button element without type="button|reset" is clicked. It can also be triggered by the Enter key.
You can use this to determine if the logout button was clicked. However, for form submission purposes, the submit event is by far the most reliable.:
$("#logout-btn").on('click', function(e) {
e.preventDefault(); //prevents default action.
alert("The logout button was clicked.");
});
$(function() {
$("#logout-btn").on('click', function(e) {
e.preventDefault(); //prevents default action.
alert("The logout button was clicked.");
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<input placeholder="Username" id="formUsr" required/>
<input type="password" placeholder="Password" id="formPwd" required/>
<input id="login-btn" type="submit" value="Login"/>
<input id="logout-btn" type="submit" value="Logout"/>
</form><!-- login form -->
Another approach:
$(function() {
$(':submit').on('click', function(e) {
e.preventDefault();
if( $(this).is('#login-btn') ) {
alert('login-btn clicked');
} else if( $(this).is('#logout-btn') ) {
alert('logout-btn clicked');
} else {
alert('some other submit button clicked');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<input placeholder="Username" id="formUsr" required/>
<input type="password" placeholder="Password" id="formPwd" required/>
<input id="login-btn" type="submit" value="Login"/>
<input id="logout-btn" type="submit" value="Logout"/>
</form><!-- login form -->
Try this:
$("#login-form").submit(function() {
alert("The logout button was clicked.");
});
Store the value of the last clicked button and in the .submit() event, make sure the last clicked button was the logout button. This works because the .click() event is fired before the .submit() event:
$(document).ready(function() {
//The logout button:
var logoutButton = $("#logout-btn");
//This variable holds the button in #login-form that the user last clicked:
var lastClicked = null;
//When the user clicks a button in #login-form, set it equal to lastClicked:
$("#login-form input[type=submit]").click(function() {
lastClicked = $(this);
});
//When the form is submitted, if it was the logout button, call the alert:
$("#login-form").on('submit', function() {
if (lastClicked.is(logoutButton)) {
alert("The logout button was clicked.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<input placeholder="Username" id="formUsr" required>
<input type="password" placeholder="Password" id="formPwd" required>
<input id="login-btn" type="submit" value="Login">
<input id="logout-btn" type="submit" value="Logout">
</form><!-- login form -->
you have two submit button in your form, you can detrmine which was clicked like this.
$(document).ready(function() {
$("#login-form input[type=submit]").click(function() {
var clickedId = $(this).attr('id');
if(clickedId=="logout-btn")
alert("The logout button was clicked.");
else if(clickedId=="login-btn")
alert("The login button was clicked.");
});
});
Note that your Login button has the ID of the logout button and the other way around.
I'm gonna add an alternative to Peters answer, just for the sake of having an alternative.
Using onclick in the markup
function logOutClicked() {
alert("Logout button clicked!");
return true;
}
<form id="login-form">
<input placeholder="Username" id="formUsr" required>
<input type="password" placeholder="Password" id="formPwd" required>
<input id="login-btn" type="submit" value="Login">
<input id="logout-btn" type="submit" onclick="return logOutClicked();" value="Logout">
</form>
Using .bind()
Since we have a linear compilation of JavaScript, the first event that will be bound to the logout button in this case is the click event.
$(document).ready(function() {
$('#logout-btn').bind('click', function() {
alert('Logout clicked click');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<input placeholder="Username" id="formUsr" required>
<input type="password" placeholder="Password" id="formPwd" required>
<input id="login-btn" type="submit" value="Login">
<input id="logout-btn" type="submit" onclick="return logOutClicked();" value="Logout">
</form>
Related
I have already seen this answer, but I want to disable the submitting of the form when pressing enter only for 1 input.
<form>
<input type="text" name="enterNotDisabled">
<input type="text" name="enterDisabled">
<button type="submit">
</form>
For example, I want that when the focus is on the first input, you can submit the form by pressing enter, but this feature would be disabled for the second input.
Thank you for your help.
just catch the "Enter" key event on that field.
Simple example :
<form>
<input type="text" name="enterNotDisabled">
<input type="text" name="enterDisabled" id="input2">
<button type="submit">
</form>
JS
function catchSubmit(evt) {
if (evt.code === 'Enter') {
evt.preventDefault();
}
}
document.getElementById('input2').addEventListener('keypress', catchSubmit, false);
Javascript
<form id="form">
<input type="text" name="enterNotDisabled">
<input type="text" name="enterDisabled">
<button type="submit">
</form>
<script type="text/javascript">
document.querySelector("#form").addEventListener("submit", function(e){
console.log('event')
e.preventDefault();
});
</script>
jQuery
<form id="form">
<input type="text" name="enterNotDisabled">
<input type="text" name="enterDisabled">
<button type="submit">
</form>
<script type="text/javascript">
$('#form').submit(function(ev) {
console.log('event')
ev.preventDefault();
});
</script>
I can't seem to get my form to validate when the button is outside the <form></form> tag. Any ideas how I can achieve this? I can't place it inside the form for technical reasons (it's inside a sticky navbar).
My HTML markup:
<form id="frm-shipping" class="frm-shipping" method="post">
<input type="text" name="contact_phone" class="has_validation"
placeholder="Contact phone" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
<input type="text" name="first_name" class="has_validation"
placeholder="First Name" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
</form>
<button class="btn" onclick="nextStep();">Next</button>
And the jQuery code:
function nextStep()
{
$.validate({
form : '#frm-shipping',
borderColorOnError:"#FF0000",
onError : function() {
},
onSuccess : function() {
var params = $( "#frm-shipping").serialize();
// AJAX call here
}
});
}
When I click the button, nothing happens. Simply nothing :( Any suggestions?
You can assign the button to the form with form attribute. See W3Schools example.
<button class="btn" form="frm-shipping" onclick="nextStep();">Next</button>
function nextStep()
{
$.validate({
form : '#frm-shipping',
borderColorOnError:"#FF0000",
onError : function() {
console.log('error')
},
onSuccess : function() {
console.log('te3st')
var params = $( "#frm-shipping").serialize();
// AJAX call here
}
});
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<form id="frm-shipping" class="frm-shipping" method="post">
<input type="text" name="contact_phone" class="has_validation"
placeholder="Contact phone" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
<input type="text" name="first_name" class="has_validation"
placeholder="First Name" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
</form>
<button class="btn" form='frm-shipping' onclick="nextStep();">Next</button>
Try this
$('.btn').click(function(){
Validate method
});
I'm trying to make a login page and have the following:
<div id="loginField">
<input id="username" type="text" name="user" required></input>
<input id="password" type="password" name="password" required></input>
<input id="submit" type="submit" name="submit" value="Login"></input>
</div>
I made sure that the username and password fields are required. When the login is successful (for this sake, let's just say that both fields are not empty) a login disappears and another view appears. Anyway, I checked to see if the login button is pressed with JQuery:
$(function(){
$('#submit').on('click', function(){
$('#loginField').hide();
$('#differentView').show();});
The problem is that when the login button is clicked, the required attributes gets ignore and the next view is shown. How do I make sure that the required attributes are not ignored when the login button is clicked?
A crude way of doing it...
<div id="loginField">
<input id="username" type="text" name="user" class="required">
<input id="password" type="password" name="password" class="required">
<input id="submit" type="submit" name="submit" value="Login">
</div>
$('#submit').on('click', function(e){
e.preventDefault();
var isReady = true;
$('.required').each(function(){
if (this.value === '') {
isReady = false;
return;
};
});
if (isReady) {
// submit form
};
});
You can use this library: Parsley. It is a javascript form validation library and it is very easy to use and you can customize it for your own means. Good luck!
Instead of handling onclick on button, you can put input fields into the form...
<form action="post" method="post" id="loginField">
<input id="username" type="text" name="user" required></input>
<input id="password" type="password" name="password" required></input>
<input id="submit" type="submit" name="submit" value="Login"></input>
</form>
... and in jQuery you can handle on submit action like this:
$(document).ready(function(){
$('#loginField').on('submit', function(event){
event.preventDefault();
var [username password] = $(this).serializeArray(),
username = username.value,
password = password.value;
/* some validations */
});
});
event.PreventDefault prevents browser from subbmiting so your page won't be refresh. serializeArray returns an array of objects (key-value) that's why you have to use .value
The required attributes are ignored because the input elements are not inside an html form element
To use the HTML5 input valuation attributes (required, minlength... etc)
The inputs should be grouped inside a form element, and you can listen for the form submit event, that is triggered by default when the user press enter (while focus is on a field inside the form) or clicks the submit button (input or button with type="submit") that is also wrapped inside the form
HTML
<form id="loginForm">
<input id="username" type="text" name="user" required />
<input id="password" type="password" name="password" required />
<input id="submit" type="submit" name="submit" value="Login" />
</form>
Javascript
$(function(){
$('#loginForm').on('submit', function (event) {
event.preventDefault(); // prevent default form submit page reload
console.log('I will enter this handler only on valid form')
$('#loginForm').hide();
$('#differentView').show();
})();
Here is a basic plunker with 2 examples https://plnkr.co/edit/I0vUMSeOlrjlYYu4VofU?p=preview
using the default html5 validation
using Parsley
How can I know which form I clicked? Is it possible with a button class instead of buttons with id?
$(document).ready(function () {
$(".form-buttons").click(function () {
//I only want the form which corresponds to the button I clicked
var formDates = $(form).serialize()
alert ("You clicked "+formDates)
})
})
<form id="form1">
<input type="text" value="date1" name="name1"/>
<input type="text" value="date2" name="name2"/>
<input type="text" value="date3" name="name3"/>
<button type="button" class="form-button"></button>
</form>
<form id="form2">
<input type="text" value="date4" name="name1"/>
<input type="text" value="date5" name="name2"/>
<input type="text" value="date6" name="name3"/>
<button type="button" class="form-button"></button>
</form>
Yes use class instead of id for similar elements. Please try this.
Note: form-button is the class name in your HTML and not form-buttons
$(document).ready(function () {
$(".form-button").click(function () {
var formDates = $(this).closest('form').serialize();
alert ("You clicked "+formDates)
})
})
I think you be looking for
$('.form-button').on('click', function () {
alert($(this).parents('form').attr('id')); // Check the ID of the form clicked
});
something Maybe Like mentioned above.
You can get the name of the element by using the this keyword which refer, in a DOM event, to the cibled element :
$(document).ready(function () {
$(".form-buttons").click(function () {
alert('You clicked the form' + this.parentElement.getAttribute('id'));
})
})
You can do this in a few different ways. You can traverse up the DOM and see which form is used or -and this is my favorite- you can submit the form!
Solution 1: Traversing up the DOM
<script>
$(document).ready(function () {
$(".form-button").click(function () {
var clicked_form = $(this).parent();
var formDates = clicked_form.serialize();
alert ("You clicked "+formDates);
})
})
</script>
</head>
<body>
<form id="form1">
<input type="text" value="date1" name="name1"/>
<input type="text" value="date2" name="name2"/>
<input type="text" value="date3" name="name3"/>
<button type="button" class="form-button"></button>
</form>
<form id="form2">
<input type="text" value="date4" name="name1"/>
<input type="text" value="date5" name="name2"/>
<input type="text" value="date6" name="name3"/>
<button type="button" class="form-button"></button>
</form>
</body>
Solution 2: Submit the form
You already are using the form, so why not submit it? Change the buttons to input elements with type submit and intercept the submit event, like this. This is how I think it should be done. It is also better for user experience because the user can just submit the form by pressing enter.
<script>
$(document).ready(function () {
$("form").on('submit', function (e) {
e.preventDefault();
var formDates = $(this).serialize()
alert ("You clicked "+formDates)
})
})
</script>
</head>
<body>
<form id="form1">
<input type="text" value="date1" name="name1"/>
<input type="text" value="date2" name="name2"/>
<input type="text" value="date3" name="name3"/>
<input type="submit" class="form-button"></input>
</form>
<form id="form2">
<input type="text" value="date4" name="name1"/>
<input type="text" value="date5" name="name2"/>
<input type="text" value="date6" name="name3"/>
<input type="submit" class="form-button"></input>
</form>
</body>
Check this fiddle on how I would do it.
https://jsfiddle.net/xtfeugav/
Simple use
$("form").submit(function(e) {
to listen for every submit on all the forms you have. To get the ID of the form you use
var formid = $(this).attr('id');
I used e.preventDefault(); to prevent the form don't update the page.
Remember to use <input type="submit" value="Submit"> on your forms to make this work.
Its a simple code, hope it helps.
I am trying to handle form validation on button click. It is validating the form but not showing error.
can anyone help me in this?
<form id="the-form" action="#">
<input type="text" required="required" placeholder="Required text" />
<input type="email" required="required" placeholder="email" />
<button id="btn" type="button">Submit</button>
</form>
JavaScript:
$("#btn").on("click", function(){
if($("#the-form")[0].checkValidity())
{
alert('validated');
}
else
{
//show errors
return false;
}
});
http://jsfiddle.net/5ycZz/
Try
reportValidity()
So you'd have
$("#btn").on("click", function(){
if($("#the-form")[0].checkValidity()) {
alert('validated');
}
else {
$("#the-form")[0].reportValidity();
}
});
I've achieved this by doing steps below:
1) I'm having form:
<form>
<textarea required></textarea>
<input type="submit" style="display:none;"/>
</form>
<a>Some other button to trigger event</a>
2) Now we have to check if the form is filled correctly:
//this is <a> click event:
if (!$('form')[0].checkValidity()) {
$('form').find('input[type="submit"]').click();
return false;
}
This will trigger form sending but won't send because there are errors ;)
It appears that html5 validation errors are displayed on input[type="submit"] click :)
Hope will work for You too! :)
here is the perfect answer
<form id="the-form" action="#">
<input type="text" required="required" placeholder="Required text" />
<input type="email" required="required" placeholder="email" />
<button id="btn" type="submit">Submit</button>
$("#btn").on("click", function(){
if($("#the-form")[0].checkValidity())
{
alert('validated');
}
else
{
return 0;
}
});
Remove the else statement. (Update)
$("#btn").on("click", function(){
if($("#the-form")[0].checkValidity())
{
alert('validated'); //will appear if name and email are of valid formats
}
});
You should be able to simply add onclick="return validateForm()".
<button id="btn" onclick="return validateForm()" type="button">Submit</button>