I have a delete button that I use globally in many areas of my site. Here is the code for it.
public function delete_button($id_to_be_deleted, $form_to_post_to, $button_name){
return form_open($form_to_post_to, array('class'=>'table_form spanFormat')) .
form_hidden(array('id'=>$id_to_be_deleted)) .
form_submit(array('class'=>'btn btn-sm btn-danger','name'=>$button_name, 'value'=>'Delete', 'onclick'=>'confirmDelete();return false;')) .
form_close();
}
This piece of code, 'onclick'=>'confirmDelete();return false;' is what should temporarily stop the form from submitting and the run my function here,
function confirmDelete() {
var d = confirm("Are you sure you want to delete this?");
if (d) return true;
else return false;
}
and if true, then submit the form.
For some reason it opens the popup but does not submit the form after because return false has already fired. But if I remove return false then the form will just submit and never pop open the popup.
Can anybody help me out?
Note: I want it done like this if possible. I do not want an on form submit, I want my handler from the button. This is because my delete forms all have different names but my buttons should all pop up this confirm dialog.
Onclick is the wrong event to use. You want to hook the submit event, so let´s start with
<input type='submit' onclick="
Then you want to actually use the result of the confirmation, so return it directly:
<input type='submit' onclick="return confirm('sure?')"/>
Related
Imagine this :
<form id="form">
<input type="text">
<button type="submit" name="submit1" value="1">something1</button>
<button type="submit" name="submit2" value="2">something2</button>
<button type="submit" name="submit3" value="3">something3</button>
</form>
First of all when I write $('#form').submit() which submit value will be sent? the first one?
Second of all How can I submit the form without the click trigger event with the value I want? Is it possible at all? For example submitting the form with the 2 submit value.
The reason I want do this is to have confirmation popup with sweetalert before sending my form so here it is :
$('form').on('submit',function(e){
form = $(this);
e.preventDefault();
swal({'some dialog'},function(isConfirm)
{
if(isConfirm)
form.submit;
\\If I use the click trigger I will get stuck in here again.
})
});
There is an alternative - use the FormData You can create an instance of a FormData, add your html form, modify entries, and send it. Everything is under your control here then.
EDIT: Based on your edit, it seems you have the problem of resubmitting the form. You can handle it like this.
var form = document.querySelector('form');
form.addEventListener('submit', {
confirmed: false,
handleEvent: function (event) {
if (this.confirmed)
return;
event.preventDefault();
doconfirm((confirmed) => {
if (confirmed) {
this.confirmed = true;
form.submit();
}
})
}
}, false);
Or you can solve your problem by unbinding the submit handlers after validation and submit it again: $('form').off('submit').submit()
As #Scott Marcus explained, the value of named buttons will be submitted when the form is sent to the server. However in your case, this won't help because you want to perform some logic before submitting it to the server.
The issue is that jQuery has no way to determine which button was clicked because it doesn't provide the submit button values when you look at the form data via $.serialize(), and there is no easy cross-browser friendly way to check the button that triggered the $.submit() event without using click.
So, the only workaround would be to handle the click event of the 3 buttons and store some value that is checked before you submit the form as described in this answer: How can I get the button that caused the submit from the form submit event?
Example: http://codeply.com/go/Wj85swRyfX
Let's take your questions one at a time...
First of all when I write $('#form').submit() which submit value will
be sent? the first one?
When a form is submitted, ALL form elements that nave a NAME attribute will submit their value (even if the value is an empty string) to the form's ACTION destination. So, in your case, all 3 of your buttons have a name attribute and so all 3 buttons will submit their name/value pairs.
Usually, we don't put a name attribute on the submit button because we only want it to trigger the submit, not actually use it as a data container. And, we usually include only a single submit button under most circumstances.
Second of all How can I submit the form without the click trigger
event with the value I want? Is it possible at all? For example
submitting the form with the 2 submit value
You would use:
$('#form').submit()
to manually cause the submit, but you'd need to have an if() statement that has logic that determines which value is appropriate to submit. Instead of the value being stored in a button, you could use a hidden form field, like this:
<form id="form">
<input type="text">
<input type="hidden" name="hidden" value="">
<button type="submit">something3</button>
</form>
JavaScript:
$("#form").on("submit", function(evt){
// Stop the form submission process
evt.preventDefault();
// Logic that sets hidden input field to correct value:
if(condition1){
$("input[type=hidden]").attr("value", "1");
} else if(condition2) {
$("input[type=hidden]").attr("value","2");
} else {
$("input[type=hidden]").attr("value","3");
}
// Manually submit the form
$("#form").submit();
});
I suggest to use hidden input tag to make the logic clear.
I noticed one pecular thing. When there are several submit buttons in your HTML form like so:
<button type="submit" name="submit_button", value="b1"></button>
<button type="submit" name="submit_button", value="b2"></button>
<button type="submit" name="submit_button", value="b2"></button>
..and you do this:
var $form = $('#my_html_form');
$form.submit(function() {
if (!checkPassed && !hasRequiredValue) {
bootbox.confirm('Are you sure that you don\'t need <strong>{requiredValue}</strong> parameter?', function(result) {
if (result) {
checkPassed = true;
$form.submit();
}
});
return false;
}
});
the field submit_button does not get submitted at all, it's just not present in the request data.
Would there be a way to force JS to submit data together with the value of the submit button clicked?
I will only add that if the form is submited with PHP and not JS, the submit_button field is present and has the value of b1, b2, or b3 - depending on which button was clicked.
P.S. I just thought that the source of the problem might be that I'm using <button> instead of <input>. However, as I said, it's all good with PHP.
Only a successful submit button will be included in the form data.
A successful submit button is one that is used to submit the form.
Your JavaScript runs on the submit event and:
Always cancels the submission of the form
Sometimes submits the form with JS
Since you are submitting the form with JS instead of the submit button, none of the submit buttons are successful.
Change your JS so that it:
Sometimes cancels the submission of the form
Such:
$form.submit(function() {
// Add a NOT condition here
if (!<someCondition>) {
return false;
}
return true;
});
Regarding the update:
OK, so you are always canceling the submission, and using a DOM based widget to ask for confirmation.
In that case, you need to capture the value of the submit button separately.
The information isn't exposed to the submit event so you need to do it on the click event of the submit button.
Add a hidden input to your form:
<input type="hidden" name="submit_button">
Then add another event handler:
$form.on("click", '[name="submit_button"]', function (event) {
$form.find('[type="hidden"][name="submit_button"]').val(
$(this).val()
);
});
Yes you can get the value of the button
$('button').click(function(event) {
var button = $(this).data('clicked', $(event.target));
var value = button.val();
});
Here you go.
$("button[name=submit_button]").click(function() {
alert($(this).val());
});
Fiddle: http://jsfiddle.net/tw698hvs/
I have a form that I want to use jquery for validation of the form before I submit. If I click on one of the buttons, I have it save the data via an ajax call. For the other button I want to submit the form, but not have it go through ajax, just do a submit the old fashioned way and go to that page.
I had the submitHandler in my validate() function, which works great for doing the ajax stuff, but what about for the other button where I don't want to use ajax? Do I remove the submitHandler portion from the validate() function? If so, then how should I set up for using ajax? Do I put it in the event handler for the click on that button? If so, how should I set it up?
Can't you just create 2 different functions or just one parameterized with a boolean to indicate whether to send ajax request or just submit the form? the latter may be done using the JQuery submit function.
I think the best way is to bind a personal event
$('form').on('submitajax submit', function(e){
if(e.type === 'submitajax'){
//ajaxstuff
}
else{
//classic stuff
}
})
And your ajax button will trigger the submitajax event
Your validation function can be like this:
function bar( ajax )
{
var valid = true, fooForm = $('#fooForm');
// do validation stuff
if( !valid ) return;
if( ajax ){
$.post(fooForm.attr('action'), fooForm.serialize());
}else{
fooForm.submit();
}
}
And your buttons:
<input type="button" value="With Ajax" onclick="bar( true )" />
<input type="button" value="Old Fashion" onclick="bar( false )" />
You need check JavaScript events on submitting form.
Just consider form:
<form class="js-form">
<a class="js-save">Save</a>
<input type="submit" value="Submit"/>
</form>
$('.js-from').on('click', function(event){
if (event.target === event.currentTarget){
# Triggers on click submit input that triggers as part of form and target same
# Call ajax stuff
} else {
# Triggers on click link witch is fired as click as not a part of form
# Call other ajax or link stuff
}
});
One function for cheching if form submit on submit button or link that can do any thing other
I figured it out. In my ajax button click event handlers, I needed to add
event.preventDefault();
Then I could add the $.ajax() call to the one where I wanted to call ajax, and to the other one just did the submit normally.
Thank you for all of your responses, it was an interesting exercise and I learned a bit more about the intricacies of this type of coding.
I have a partial view in MVC2:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<div class="uploader">
<form action="/media/uploader" method="post" enctype="multipart/form-data">
<input id="File1" type="file" name="upfile" />
<input type="submit" value="Upload" />
</form>
</div>
enter code here
I dont know how to do next:
after user press submit button, I would like to validate extension of uploaded file. If extension is valid, I would post uploaded file, but if extension is not suported, I would like to alert user somehow (popup?) and abort submit. I tried some things with jquery, but I just dont understand it enough so I cant make it work.
Thank you for any advice.
I'm not an MVC guy but I know that you have two options that should work here just from the strict JS/FORMS perspective...
The form has an event - onsubmit - if you have an event handler that returns false to the onsubmit event, the submit won't happen. Similarly, if you have an event handler on the submit button's onclick event, returning false will cancel the click, hence, the form post as well.
Here's an example relying on the form's onsubmit:
<form action="/myDir/myPage.ext" method="post" onsubmit="return validForm(window.event);">
....
</form>
If you implement the method validForm it might look something like:
function validForm(e) {
var fullPath = document.getElementById('File1').value;
if (validateFileExtension(fullPath)) {
return true;
} else {
alert('Invalid extension for this file!');
return false;
}
}
function validateFileExtension(fullPath) {
var isValid = false;
// some logic to parse and validate extension
// if the logic passes, we set isValid to true.
return isValid;
}
With the above methods fully implemented, your two options are to use the method in either the submit button's onclick event or in the form's onsubmit event. Either way, you'll want to check the value of the File Input, ensure the extension is what you want, and return false if the extension violates whatever your business rules are. If you return true, the button click/form submit will proceed. If you return false, the form submit or button click (depending on which event you've wired to) will cancel - either way, same result - no form submission without what you want in the file field.
Happy coding.
B
You could use the Ajax Upload plugin which allows you to do this.
I have an ASP.NET page which has a button it it. The button click launches a modal dialog box using JavaScript. Based on the value returned by the modal dialog box, I want to proceed with, or cancel the post back that happens. How do I do this?
Adding "return false;" to the onclick attribute of the button will prevent the automatic postback.
Is this what you are trying to do?
<input type="button" id="myButton" value="Click!" />
<script type="text/javascript">
document.getElementById('myButton').onclick = function() {
var agree = confirm('Are you sure?');
if (!agree) return false;
};
</script>
function HandleClick()
{
// do some work;
if (some condition) return true; //proceed
else return false; //cancel;
}
set the OnClientClick attribute to "return HandleClick()"
Basically what Wayne said, but you just need to put 'return false;' in the function that presents the modal. If it's the value you want, let the postback happen. If not, have the function return false and it will stop the submit.