In my semantic UI form (<div class="ui form">) it appears every button triggers the form validation, even if it is not a submit button.
Two different kind of buttons below:
<button class="ui blue right labeled icon primary submit button">
<i class="right arrow icon"></i>
Submit
</button>
and
<button class="ui blue button">
Something Else
</button>
both of these are inside the semnatic UI form element. both trigger my validation rules (standard setup rules) :
$('.ui.form')
.form({
fields: {
example:: {
identifier: 'example',
rules: [
{
type : 'empty',
prompt : 'Please enter at least one thing'
}
]
}
}
}
)
;
Only "Solution" I could find online was creating a button like this:
<input type="button" class="ui blue button">
Test
</input>
but this doesn't put the text ("test") inside the button, also couldnt get the size of the button to be same as other ones.
Is there a way to get it to not trigger my validation? Pretty stumped on why a non submit button is doing it.
Simply define the type of the button. Default type is submit:
<Button type="button" />
Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Attributes
I was able to implement this in a different way, as the button type=button control while ignoring the validations, did not submit, and if I did submit manually the default event handler of semanticui would intervene and show the validation errors.
My use case two buttons, one a save draft and the other a finalize (final save). The first one had to save the data as is, without triggering the validations, while the other would trigger validations and then save.
I am also implementing all the validators using data attributes that I custom implemented for this project, hence the form validator is inside a JS file.
In my form validation's failure method, I included a delegate function which I could set on my page and depending on which button clicked it, then be able to return true or false.
My form validator inside a JS file
$('.ui.form').form({
inline: true,
on: 'submit',
fields: formFields,
transition: 'fade',
keyboardShortcuts: false,
onFailure: function () {
var returnValue = false; //Default to false, since validations failed
//If the delegate is present, fire it to evaluate
if (typeof window.delegValidate == 'function') {
returnValue = window.delegValidate();
}
//Ignore the toast if the delegate evaluated to TRUE
if (!returnValue) {
$('body')
.toast({
title: 'Unable to save',
message: 'Please enter all required field data before saving.',
classProgress: 'red',
showProgress: 'top',
progressUp: true,
position: 'bottom right',
showIcon: 'red exclamation triangle'
});
}
return returnValue; // false is required if you don't want to let it submit
}
});
and on my page I attached a function to the window, since my form validation is inside a JS file.
Page function
//For all postback buttons, save the id value in a hidden field for use in the delegate
$('.postbackButton').bind('click', function (e) {
$('#ButtonClicked').val(this.id); // a hidden field on the page
});
//setting the delegate for use in the form validations
window.delegValidate = function () {
//For the save button, just ignore the validations and return true
//This in turn is invoked by the failure method of the form validation that is
//dynamically attached to the page, and hence this return value is respected
//over the false that is otherwise sent back for when we want to interrupt the page
//since there are errors normally.
if ($('#ButtonClicked').val() == 'Save')
return true;
else // if value is finalize, let it return false
return false;
}
For other pages where I don't want this functionality, I can simply not write the delegate method and the default validation fires as expected on the submit button.
Hope this helps someone still looking for a way to do this. :)
Related
So by default Semantic-ui doesn't have any way to prevent clicks which trigger the validation, once the form has been setup, as the validation is handled onsubmit directly. This is important if you have multiple buttons on the page and only want some to trigger the validation and the rest perhaps to be able to postback, or do other things minus triggering the form validation.
I checked some answers that talk about changing the input from a type=submit to a type=button, but you lose the design ability especially the ability to add an icon and is not the ideal solution.
Am posting this question, since my answer to this question, got deleted by the moderator, even though I have a working fiddle and a detailed answer on how to achieve this.
Reposting the entire answer here, incase anyone needs help on this.
I was able to implement this in a different way, as the button type=button control while ignoring the validations, did not submit, and if I did submit manually the default event handler of semanticui would intervene and show the validation errors.
My use case two buttons, one a save draft and the other a finalize (final save). The first one had to save the data as is, without triggering the validations, while the other would trigger validations and then save.
I am also implementing all the validators using data attributes that I custom implemented for this project, hence the form validator is inside a JS file.
In my form validation's failure method, I included a delegate function which I could set on my page and depending on which button clicked it, then be able to return true or false.
My form validator inside a JS file
$('.ui.form').form({
inline: true,
on: 'submit',
fields: formFields,
transition: 'fade',
keyboardShortcuts: false,
onFailure: function () {
var returnValue = false; //Default to false, since validations failed
//If the delegate is present, fire it to evaluate
if (typeof window.delegValidate == 'function') {
returnValue = window.delegValidate();
}
//Ignore the toast if the delegate evaluated to TRUE
if (!returnValue) {
$('body')
.toast({
title: 'Unable to save',
message: 'Please enter all required field data before saving.',
classProgress: 'red',
showProgress: 'top',
progressUp: true,
position: 'bottom right',
showIcon: 'red exclamation triangle'
});
}
return returnValue; // false is required if you don't want to let it submit
}
});
and on my page I attached a function to the window, since my form validation is inside a JS file.
Page function
//For all postback buttons, save the id value in a hidden field for use in the delegate
$('.postbackButton').bind('click', function (e) {
$('#ButtonClicked').val(this.id); // a hidden field on the page
});
//setting the delegate for use in the form validations
window.delegValidate = function () {
//For the save button, just ignore the validations and return true
//This in turn is invoked by the failure method of the form validation that is
//dynamically attached to the page, and hence this return value is respected
//over the false that is otherwise sent back for when we want to interrupt the page
//since there are errors normally.
if ($('#ButtonClicked').val() == 'Save')
return true;
else // if value is finalize, let it return false
return false;
}
For other pages where I don't want this functionality, I can simply not write the delegate method and the default validation fires as expected on the submit button.
Also posted here Ignore SemanticUI validation on some buttons
Hope this helps anyone looking for a better way of handling this scenario.
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'm still a newb when it comes to MVC, Ajax and JavaScript. I have an application where I have to make a change. Right now, when a change is made and the Save, the spinner displays as the info saves and the page loads. The code for the Save looks like this:
$('#SaveButton').on('click', function () {
navParams.isDirty = false;
});
HTML looks like this:
<input type="submit" value="Save" class="btn btn-block btn-primary user-action" name="action:Save" id="SaveButton" />
Just a note there multiple buttons on the screen so it is using the "Multiple Button" solution from How do you handle multiple submit buttons in ASP.NET MVC Framework?
The following code was added:
$('#SaveButton').on('click', function () {
navParams.isDirty = false;
displaySavePromptMessage();
});
function displaySavePromptMessage() {
if (isModalOpen == false) {
bootbox.dialog({
closeButton: false,
title: "",
message: "<strong>Warning: </strong>Changes have been made, ensure corresponding dates have been updated on the screen",
buttons: {
success: {
label: "Ok",
callback: function () {
navParams.userAction = false;
}
}
}
});
}
}
Now what's happening is the save button is clicked, the spinner starts running, the dialog box loads, but before the OK button is clicked the dialog button closes and the spinner stops. The changes are saved.
What needs to happen is the spinner starts, the dialog box loads and everything stays as is until the user clicks OK. Then the processing continues. I'm not sure how to make this happen. Any thoughts?
Basic concept. You need to listen to submit event and prevent it:
$('.some-form').on('submit', function(submitEvent) {
submitEvent.preventDefault();
});
Then in your handler, you need to submit your form on success:
// Inside your success handler
$('.some-form').get(0).submit();
You have input type="submit" which will submit the form when this button is clicked. Either change this to type="button" or as #Lesha Ogonkov said
$('#yourFormID').on('submit', function (e) {
e.preventDefault();//it will stop loading page on form submission
});
in ajax inside you success handler function
$('.myFromID').get(0).submit();
I'm simply trying to find a way to create a confirm dialog in jquery to use in place of the default confirm function in javascript. I have a confirm dialog that's used to decide if I want to proceed without a given value in a form. The whole program is here:
http://nowlin.com/testpop.php
The button code that's giving me a headache looks like this, but it may not be the button code. I'm just learning jquery:
buttons: {
'Yes': function() {
document.getElementById("clicked").value = "true";
creturn = true;
$(this).dialog('close');
},
'No': function() {
document.getElementById("clicked").value = "false";
creturn = false;
$(this).dialog('close');
}
}
This program works fine except for the confirm dialog. I've tried setting a variable that has a global scope (creturn), and a DOM element from a hidden input (clicked.value), so that when the dialog closes I can tell which button was chosen. The values both get set, but not until after the form Send button, where the onclick event is located, is hit a second time:
<button type=submit name=clicked value=true onclick='return chkreq("cfbform")'>Send</button>
The behavior is, if you enter an email address and no name, and hit the Send button, the confirm dialog pops up. If you select Yes the dialog closes, but the form isn't submitted. If you click the Send button a second time, the dialog pops up again, immediately closes on its own, and the form is submitted. Clearly I'm missing something.
Thanks for any insights.
I would switch the button from type=submit to type=button (we can also drop the return)
<button type=button name=clicked value=true onclick='chkreq("cfbform")'>Send</button>
and then use jQuery to submit the form when it passed validation.
function chkreq(fid) {
// both values are set return true
if (document.getElementById(fid).elements.namedItem("name").value.length > 0 &&
document.getElementById(fid).elements.namedItem("email").value.length > 0) {
document.getElementById("clicked").value = "true";
$('#' + fid).submit();
}
...
}
And
buttons: {
'Yes': function() {
document.getElementById("clicked").value = "true";
$('#' + fid).submit();
$(this).dialog('close');
},
'No': function() {
document.getElementById("clicked").value = "false";
creturn = false;
$(this).dialog('close');
}
}
For more info see https://api.jquery.com/submit/
The other option used on that page is binding to the submit event. With your override-able validation via the popup, I think the above code will be easier to implement.
using Submit buttons and binding click events to them and handling the click in jQuery could cause issues like your jquery gets called then the post pack gets called because of the submit.
I suggest change the type of the button from "submit" to "button" and give it a try.
I have a save button that triggers a jquery prompt (click the save button, and then I prompt the user: "Are you sure you want to save updates?" The problem is that a user can click the prompt multiple times, causing the same data to save multiple times. How can I disable the prompt save button on the first click?
I am using knockout js. Here is the code in my viewmodel:
$.prompt("Are you sure you want to save? You will not be able to change your decision after it's been saved.", {
title: "Save?",
buttons: { "Save": true, "Cancel": false },
submit: function (e, v, m, f) {
if (v) {
e.disabled = true;
response = saveUpdates(LoanDetails);
}
}
}
});
You can disable the button after saving data for the first time. You can use different jquery selector for your button.
$('button[type=submit], input[type=submit]').attr('disabled',true);
Try disabling the button itself when you do the save. Then the button
wont be clickable and you wont get the prompt.
If you want to disable a button using jQuery, you should have a look at $('#elem').prop(property,value), which will allow you to do something like this...
$("input").prop("disabled",true);