I'm creating a blog with bootstrap and I have a form to submit categories:
<form action="categories.php" id="category-form" class="form-horizontal" role="form" method="post">
<div class="form-group">
<label for="category" class="col-sm-2 control-label">Category</label>
<div class="col-sm-10">
<input type="text" name="category" class="form-control" id="category" placeholder="Category">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" name="submit" id="btn-submit" class="btn btn-primary" value="Add Category">
</div>
</div>
</form>
When I press the form button "Add Category" the dialog appears but after a few seconds it submits itself immediately and the dialog disappears without clicking the buttons "yes" or "no", searching the web I found some solutions but doesn't work for me. The code I use for Alertify JS is the following:
$("#btn-submit").on("click", function(){
alertify.confirm("This is an alert dialog?", function(e){
if (e) {
alertify.success("Category was saved.")
} else {
alertify.error("Category not saved.");
}
});
return false;
});
I also try event.preventDefault();:
$("#btn-submit").on("click", function(event){
event.preventDefault();
alertify.confirm("This is an alert dialog?", function(e){
if (e) {
$("#category-form").submit();
alertify.success("Category was saved.")
return true;
} else {
alertify.error("Category not saved.");
return false;
}
});
});
But does not work as well. Any help please... Thank you.
try something like this. i think you want the confirmation before submitting the form so added the confirm message part. hope it will help.
$("#category-form").submit(function (e) {
var result = confirm("Are you sure ?");
if(result){
// do something
} else {
alertify.error("Error mesage.");
e.preventDefault(); // this will prevent from submitting the form.
}
});
Could you please try following code:
You need to remove type="submit" from your button. Otherwise it submits the form by default.
HTML:
<form action="categories.php" id="category-form" class="form-horizontal" role="form" method="post">
<div class="form-group">
<label for="category" class="col-sm-2 control-label">Category</label>
<div class="col-sm-10">
<input type="text" name="category" class="form-control" id="category" placeholder="Category">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="button" id="btn-submit" class="btn btn-primary" value="Add Category">
</div>
</div>
</form>
JQuery Code:
//your button click code
$("#btn-submit").on("click", function(event){
event.preventDefault();
alertify.confirm("This is an alert dialog?", function(e){
if (e) {
$("#category-form").submit();
alertify.success("Category was saved.")
return true;
} else {
alertify.error("Category not saved.");
return false;
}
});
});
alertify basically take 4 arguments in confirm function
alertify.confirm(title, message, onconfirm, oncancel);
You don't have to do if(e)this code
$("#formID").on("click", function(){
alertify.confirm("This is an alert dialog?", function(e){
if (e) {
alertify.success("Category was saved.")
} else {
alertify.error("Category not saved.");
}
});
return false;
});
will now become
$("#formID").submit(function(e){
e.preventDefault();
alertify.confirm('Confirm Title', 'Confirm Message', function(){
// call the function that will handle your form submission may be ajax don't write $('#fomr').submit() becasue it will start an endless loop through this function
}, function(){
// when user click cancel
});
});
Ok, This was posted and answered a long time ago. But as I was developing asp net
core in 2020, I came across AlertifyJS. I like the library. A solution for this
issue is:
1) I used <button>
2) I used e.preventdefault()
3) I used ('#category-form').submit()
4) Make sure you add id='category-form' in your form and also and id for button.
5) Use button and not input type=submit.
There could be a difference in how they work.
The difference is that <button> can have content,
whereas <input> cannot (it is a null element).
$('#btn-submit').on('click', function (e) {
e.preventDefault();
alertify.confirm('Save Category', 'Do you want to proceed?', function (e)
{
if (e) {
$("#category-form").submit();
alertify.success('Category Saved Successfully.');
return true;
}
else {
alertify.error("Category was not saved.");
return false;
}
}, function () { alertify.error('Cancel') });
});
Related
I'm currently creating a subscription form using jQuery. My problem is I want to make this form stay in the same page after user click "SUBSCRIBE" button and when the process is successful, the text on button "SUBSCRIBE" change to "SUBSCRIBED".
Below is the code :
HTML:
<form action="http://bafe.my/sendy/subscribe" class="subcribe-form" accept-charset="UTF-8" data-remote="true" method="post">
<input type="hidden" name="authenticity_token" />
<input type="hidden" name="list" value="ttx7KjWYuptF763m4m892aI59A" />
<input type="hidden" name="name" value="Landing" />
<div class="form-group">
<div class="input-group">
<input type="email" name="email" class="form-control" placeholder="Masukkan email anda" />
<span class="input-group-btn"><button type="submit" class="btn btn-primary">SUBSCRIBE<i class="fa fa-send fa-fw"></i></button></span>
</div>
</div>
</form>
jQuery:
$(".subcribe-form").submit(function(){
var validEmail = true;
$("input.form-control").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("has-error");
validEmail = false;
} else{
$(this).removeClass("has-error");
}
});
if (!validEmail) alert("Please enter your email to subscribe");
return validEmail;
});
You can use event.preventDefault to prevent the form submission but you also need to send the data to the server so for this you can use jQuery ajax ( see below code )
$(".subcribe-form").submit(function(event){
event.preventDefault()
var validEmail = true;
$("input.form-control").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("has-error");
validEmail = false;
}
else{
$(this).removeClass("has-error");
}
});
if (!validEmail) { alert("Please enter your email to subscribe");
}else {
//for valid emails sent data to the server
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $('.subcribe-form').serialize(),
success: function(serverResponse) {
//... do something with the server Response...
}
});
}
return validEmail;
});
Add preventDefault so that form submission is prevented
$(".subcribe-form").submit(function(event){
event.preventDefault()
use serialize and post to send your data to desired url
Just handle the form submission on the submit event, and return false:
if using AJAX : (With ajax you can either do that, or e.prenventDefault (), both ways work.)
$(".subcribe-form").submit(function(){
... // code here
return false;
});
If using simple form :
$(".subcribe-form").submit(function(e){
... // code here
e.preventDefault();
});
In my opinion it would be easier to do it using PHP. If you do not want to use PHP, then you can ignore this answer.
If you want to give it a try, you can do the following:
1. Remove the action attribute from the form tag.
2. Write PHP code similar to:
if (isset($_POST['submit']) { // "submit" is the name of the submit button
onSubmit();
}
function onSubmit() {
/* your code here */
}
This is how I stay on the same page, a minimal example using jQuery:
<form id=f
onsubmit="$.post('handler.php',$('#f').serialize(),d=>r.textContent+=rd.innerHTML=d);return false">
<textarea name=field1 id=t>user input here</textarea>
<input type=submit>
</form>
<textarea id=r width=80></textarea>
<div id=rd></div>
The key is to return false from the form onsubmit handler.
I am creating a comment functionality and below are my code so far.
html
<form action="http://website.com/transaction_items/add_comment" class="" id="form-comment" role="form" method="post" accept-charset="utf-8">
<input type="hidden" name="checklists_item_id" value="6" style="display:none;">
<input type="hidden" name="user_id" value="1" style="display:none;">
<div class="input-group col-xs-12">
<input type="text" name="comment" value="" class="form-control" id="comment-input" placeholder="Enter your comments..">
<span class="input-group-btn">
<button class="btn btn-default" id="doc-comment" type="button">Post</button>
</span>
</div>
</form>
jQuery
This function is called when document is ready.
function comment () {
$('#doc-comment').click(function (e) {
var form_id = '#' + $(this).parents('form').attr('id');
// submit data from the form
submit.send(form_id);
});
}
The problem:
Using the button <button class="btn btn-default" id="doc-comment" type="button">Post</button> to submit data work fine, but
if I use enter in the keyboard, submit.send(form_id); will not do its function, instead the default form submission will execute.
How can I use ajax if use enter in the keyboard to submit form data?
nutshell
$("#form-comment").on('submit', function(evt) {
evt.preventDefault();
// do your ajax stuff here
});
you can then toss the onclick button listener.. as this will handle the button submit as well
There are more ways to submit a form then simply pressing the submit button.
You need to:
Use the forms submit method
Keep the form from doing the full submit.
-
// This will catch the *enter* as well as the submit button
$("#form-comment").on('submit', function(evt) {
evt.preventDefault();
// You can then submit the form via ajax and update things as needed.
});
IF you are going to use a button you should at least do a
<button type="button">...</button>
which behaves differently.
$("#form-comment").keyup(function (e) { // On pressing enter
if (e.keyCode == 13) {
// put your ajax code here
}
});
You may have to disable the default Enter event for the form submit button as well depending on your browser.
So in the Jquery Button click function make sure you have something like
event.preventDefault();
How can i change behaviour of button if form submit was successful?
<form method="post" enctype="multipart/form-data" style="margin: 0;" id="frmGenerate">
<div class="clearfix">
<div class="input-group">
<input type="text" placeholder="Customer Name:" name="CustomerName">
<input type="text" placeholder="Generated Url:" name="CustomerUrl" readonly="readonly" />
</div>
</div>
<div class="clearfix">
<div class="input-group">
<button type="submit" class="btn">Generate</button>
</div>
</div>
</form>
And here is my JS code:
$('#frmGenerate').submit(function(e) {
var clientName = $(this).find('input[name="CustomerName"]').val();
$.ajax(
{
url: '#Url.Action("GenerateToken","Admin")',
type: 'GET',
data: { customerName: clientName },
success: function(response) {
if (response.result) {
$('#frmGenerate').find('input[name="CustomerUrl"]').val(response.message).select();
$('#frmGenerate').find('button.btn').text('Close');
} else {
alert(response.message);
}
}
});
e.preventDefault();
});
This is modal windows, which i open to generate token. When it's generated successful then i set generated token in modal input and change text of button to close, but i don't know how to change button's behaviour.
Better approach would be not to change existing button, but hide it and show another.
HTML:
<div class="clearfix">
<div class="input-group">
<button type="submit" class="btn">Generate</button>
<button type="button" class="btn btn-close hide">Close</button>
</div>
</div>
JS:
$('#frmGenerate').find('.btn').hide();
$('#frmGenerate').find('.btn-close').show();
Depends on what type of button you are using. Button must be used like: <button></button> Not like <button/>
And then use:
$(".btn").html('Close');
you can change attribute of button
$('#frmGenerate').find('button.btn').attr('type', 'button');
and then:
$('#frmGenerate').find('button.btn').on('click', function(){ /*close function */});
I see you have changed the text of your button to 'Close' after the form has been submitted. So the remaining part is the jQuery that handles a click event on the button.
....
$('.btn').click(function(){
var buttonText = $(this).val();
if(buttonText === 'Close'){
//code when close button is clicked
}else if(buttonText === 'Generate'){
//code when Generate button is clicked...
}
});//end button.click function
And I would use input type='button' or button than input type='submit'. Why dont you submit form using ajax as well? much better.
Hope this helps...
I am trying to perform a 'clean' submit, i.e. a submit that is invoked after removing all hidden divs from the form field.
Since this is a feature I am going to use more often, I shifted my code into the extend-part:
$.fn.extend({
bindCleanSubmit: function() {
$(this).submit( function(event) {
event.preventDefault();
$(this).find("div:hidden").remove();
console.log("trying to commit...");
return true;
});
}
});
Now, all divs are removed, the console event is triggered but at the end the submit has not performed.
Do you now the problem here?
I'm not sure what you are trying to do with preventDefault(), but if you remove it from bindCleanSubmit(), hidden divs will be removed from the form and it will be submitted normally. So given the following html:
<form id="myform" method="POST" action="/">
<input type="text" name="displayedInput" value="1"/>
<div style="display: none">
<input type="text" name="hiddenInput" value="1"/>
</div>
<button type="submit">Submit</button>
</form>
...and the updated plugin:
$.fn.extend({
bindCleanSubmit: function() {
$(this).submit( function(event) {
$(this).find("div:hidden").remove();
console.log("trying to commit...");
return true;
});
}
});
$('#myform').bindCleanSubmit();
...only the displayedInput value will be submitted to the server when myform is submitted.
I've got this simple login screen where is has a text box for the name, and a submit button. The jquery script running is this:
$(document).ready(function() {
$('#btnLogin').click( function() { validate() });
$('#loginForm').submit( function() { validate() });
});
function validate() {
if ($('#txtLogin').val() != '') {
document.cookie = 'loginID=' + $('#txtLogin').val();
$('#lblError').hide();
document.location.href = 'mainmenu.aspx';
}
else {
$('#txtLogin').text('');
$('#lblError').show();
}
}
It works when I click the button, but when I press enter, it doesn't navigate to the mainmenu.aspx. I'm following it with Chrome and it does execute the redirect just like when you press the button, but it just stays on the same page. I also put a break point in the Page_Load function (C#) of the mainmenu.aspx, but it never reaches it.
EDIT:: Here's the html
<form id="loginForm" runat="server">
<div>
<div class='theme login'>
<p>Login</p>
<input type='text' id='txtLogin' maxlength='17' />
<div><input type='button' id='btnLogin' class='button' value='Log In' /></div>
<div><span id='lblError' visible='false' text='*You must enter a valid username'></span></div>
</div>
</div>
</form>
In your form submit handler, use preventDefault() to stop the default submit behavior:
$('#loginForm').submit( function(e) {
e.preventDefault(); // swallow regular submit behavior
validate(); // your stuff
// real submit? your option
});
Reference: http://api.jquery.com/event.preventDefault/
Try making the submit element in the form just a regular button element. The browser may be intercepting something.
The reason for that is your submit still happens when you hit enter. You need to cancel the default behavior by returning false in the event handler function.
function validate() {
// ...
return false;
}
$('#loginForm').submit(validate);
$('#btnLogin').click(validate);
Edit: refer to the function directly instead of an anonymous function?
function validate() {
if ($('#txtLogin').val() != '') {
document.cookie = 'loginID='+$('#txtLogin').val();//set expire and path?
$('#lblError').hide();
location.href = "mainmenu.aspx"; //"submit"
}
else {
$('#lblError').show();
return false; //prevent submit
}
}
$(function() {
$('#btnLogin').click(validate);
$('#loginForm').submit(validate);
});
I changed both some of your HTML and jQuery code. Now it will check and submit on both Enter and when the button is clicked.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("form").attr("action","javascript:void();"); // No action on form submission
$("input").keypress(function(e) { // Capture keys pressed
if(e.keyCode==13) { // Enter key?
validate();
}
});
$("input:button").click(function() { // Button clicked?
validate();
});
});
function validate() {
if ($("#txtLogin").val()!='') {
document.cookie="loginID="+$("#txtLogin").val();
$("#lblError").hide();
$("form").attr("action","mainmenu.aspx"); // Change form action
$("form").submit(); // Submit the form
} else {
$("#lblError").show();
}
}
</script>
HTML
<form id="loginForm" runat="server">
<div>
<div class="theme login">
<p>Login</p>
<input type="text" id="txtLogin" maxlength="17" />
<div><input type="button" id="btnLogin" class="button" value="Log In" /></div>
<div id="lblError" style="display: none;">* You must enter a valid username</div> <!-- Error message -->
</div>
</div>
</form>