have a button click in a form and have required validation when clicking on that button. I put in
if (!formHandle.valid()) { return; }
in the global site.js file where I want that event to fire first before the event for the actual button. Currently the jquery for the actual button fires first before the global jquery. How can I make sure that the global jquery fires first or is this even possible?
html
<p id="vote-status" class="card-text forum-blue">
#{if (#Model.VoteId != 0)
{
<text>
<br /Text.
<br />Text
</text>
}
else
{
<text><br />Text.</text>
}
}
</p>
#{
if (Model.AvailableVotingOptions != null)
{
#Html.DropDownListFor(m => m.VotingOptionId,
Model.AvailableVotingOptions,
"- Please select -",
new { #class = "form-control", #id = "voting-options" })
}
}
<div class="card-footer">
<div class="row">
<div class="col-sm-12 col-md-3 col-lg-3">
<button type="button"
class="btn btn-success btn-sm col-sm-12"
id="button"
data-action="submit">
<i class="fas fa-vote-yea fa-fw"></i>
#if (#Model.VoteId != 0)
{
<text>Re-Cast Vote</text>
}
else
{
<text>Vote</text>
}
</button>
</div>
</div>
</div>
Site.js (event I want to hit first)
$(document).on("click",
'[data-action="submit"]',
function (e) {
var formHandle = $(this).closest('form');
if (!formHandle.valid()) {
return;
}
if (formHandle.valid()) {
blockUI();
}
});
Document.js
$(document).on("click",
'#button',
function (e) {
e.preventDefault();
var post_url = $("#form-vote").attr("action"); //get form action url
var request_method = $("#form-vote").attr("method"); //get form GET/POST method
var form_data = $("#form-vote");
$.ajax({
url: post_url,
type: request_method,
data: form_data.serialize(),
processData: false,
async: true
}).done(function (objOperations) {
if ($("#validation-error")[0].textContent.trim() === "") {
ShowVoteStatus(true, "Your document is submitted successfully.");
}).fail(function (error) {
ShowVoteStatus(false,
"Your document was not submitted successfully.");
}).always(function (jqXHR, textStatus) {
$.unblockUI();
});;
});
https://codepen.io/bootsy1974/pen/ExggoQg
why do different functions? you can make a check before sending in the second function.
if its possible and this same one button
if its not possible to try after validation use
$("#button").trigger("click");
$(document).on("click",
'[data-action="submit"]',
function (e) {
e.preventDefault();
var formHandle = $(this).closest('form');
if (!formHandle.valid()) {
return;
}
if (formHandle.valid()) {
blockUI();
$("#button").trigger("click");
}
});
but formHandle.valid is not a function
need changed '#button' from button and created another element to binding this function. in another to try sending without validation. need do dependeces sending from validating. but you have to parallel working.
<div class="col-sm-12 col-md-3 col-lg-3">
<div id="button"></div>
<button type="button"
class="btn btn-success btn-sm col-sm-12"
data-action="submit">
<i class="fas fa-vote-yea fa-fw"></i>
#if (#Model.VoteId != 0)
{
<text>Re-Cast Vote</text>
}
else
{
<text>Vote</text>
}
</button>
</div>
and this have not '}'
$(document).on("click",
'#button',
function (e) {
e.preventDefault();
var post_url = $("#form-vote").attr("action"); //get form action url
var request_method = $("#form-vote").attr("method"); //get form GET/POST method
var form_data = $("#form-vote");
$.ajax({
url: post_url,
type: request_method,
data: form_data.serialize(),
processData: false,
async: true
}).done(function (objOperations) {
if ($("#validation-error")[0].textContent.trim() === "") {
ShowVoteStatus(true, "Your document is submitted successfully.");
}}).fail(function (error) {
ShowVoteStatus(false,
"Your document was not submitted successfully.");
}).always(function (jqXHR, textStatus) {
$.unblockUI();
});;
});
https://codepen.io/romanown/pen/QWKKERZ
deleted not worked validating
https://codepen.io/romanown/pen/zYKKKqv
Related
I am trying to submit a form with a little error handling. when the fields are empty there will be a warning and it shouldn't be saved on DB. if the fields are filled there should be a success alert. My case is still the empty value is being saved.
HTML
<input type="submit" id="add" onclick="emptyHandling();" name="_add" class="btn btn-primary btn-size" value="Add"/>
//FORM SUBMIT
$(document).ready(function(){
$("#form").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'add.php',
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
async: false,
autoUpload: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#form')[0].reset(); //FORM TO RESET AFTER SUBMISSION
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>'); // REPONSE MESSAGE
}else{
$('.statusMsg').html(alert(response.message));
}
$('#form').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
//ERROR HANDLING - TRIGGERED ON CLICK
function emptyHandling(){
var inv = $("#inv").val();
if(inv == ''){
var message = "Field Left Empty";
alertMessage(message);
}else{
successMessage();
}
return false; // THIS IS BEING RETURNED FALSE
}
//WARNING ALERT
function alertMessage(titleMessage){
swal({
title: titleMessage,
text: "Mandatory Fields are Required to be Filled",
type: "warning",
confirmButtonClass: "btn btn-danger"
});
}
The return is made false on error handling which should stop the next processes. I am not really sure of where the mistake is made.
You can remove onclick from your submit button and move that function call inside your form submit handler . Then , inside this check if the validation function return true/false depending on this execute your ajax call.
Demo Code :
$(document).ready(function() {
$("#form").on('submit', function(e) {
e.preventDefault();
//call function..
if (emptyHandling()) {
//your ajax...
console.log("inside ajax....")
}
});
});
//ERROR HANDLING - TRIGGERED ON CLICK
function emptyHandling() {
var flag = true
var inv = $("#inv").val();
if (inv == '') {
var message = "Field Left Empty";
alertMessage(message);
flag = false
} else {
successMessage();
}
return flag; // return flag//
}
//WARNING ALERT
function alertMessage(titleMessage) {
//swal...
console.log(titleMessage)
}
function successMessage() {
console.log("All good...")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<form id="form">
<input type="text" id="inv">
<input type="submit" id="add" name="_add" class="btn btn-primary btn-size" value="Add" />
</form>
Here is the layout of the page I am working on:
I am having an issue on getting the functionality working for the "Close Issue" actions. The "Save" issue performs a submit where the form data is parsed and the record is saved. If the data model fails validation, the form is reshown with the model errors, otherwise it redirects back to the index page. I want the "Close Issue" to do a submit as well. I want it to save the data (including a validation check) and then display a pop-up asking the user if they are sure they want to close the issue. I've tried numerous approaches but none are working. I can do a submit without any javascript/ajax intercept and get the form data, but can't get the modal to display. I can do the intercept of the submit, but I can't get all of the form data. I'm sure I am overlooking something. Here is the code:
The partial view I want displayed in the Modal:
#model EDAD.ViewModels.IssueViewModel
<!--Modal Body Start-->
<div class="modal-content">
<input name="IsValid" type="hidden" value="true" />
<!--Modal Header Start-->
<div class="modal-header">
<h4 class="modal-title">Close Issue</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!--Modal Header End-->
<form asp-action="ClosetheIssue" method="post" enctype="multipart/form-data" asp-controller="Issue">
#Html.AntiForgeryToken()
<div class="modal-body form-horizontal">
<div class="form-group row">
Are you sure you want to close this issue? Once you close this issue you will no longer be able to make any changes to the issue.
</div>
<div class="form-group row">
<input id="issueid" type="hidden" asp-for="#Model.IssueData.issueId" class="form-control" value="#ViewBag.id" />
</div>
<!--Modal Footer Start-->
<div class="modal-footer">
<button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">No</button>
<input type="submit" class="btn btn-success closeissue" id="btnSubmit" data-save="modal" value="Yes">
</div>
<div class="row">
</div>
</div> <!--Modal Footer End-->
</form>
</div>
<script type="text/javascript">
$(function () {
});
</script>
<!--Modal Body End-->
Here is the code for the "Close Issue" Button (and the Form action for both the "Save Issue" and "Close Issue":
<form asp-action="Edit">
<div id="closecontent">
<div id="modal-container3" class="modal fade" tabindex="-1">
<div class="modal-dialog modal-lg">
<div id="modal-content3" class="modal-content">
</div>
</div>
</div>
<input type="submit" asp-route-saveClose="close" class="btn btn-success closeissue" id="btncloseissue" data-save="modal" value="Close Test">
</div>
Here is the code for the Edit action:
public ActionResult Edit(IFormCollection collection, string saveClose)
{
if(saveClose is null || saveClose == "")
{
saveClose = "save";
}
IssueDataModel issue = new IssueDataModel();
try
{
ValidateData(collection);
if (ModelState.IsValid)
{
//Do stuff to save the data
if (saveClose == "save") {
return RedirectToAction(nameof(Index));
}
else
{
TempData.Remove("ID");
TempData["ID"] = collection["IssueData.issueId"].ToString();
TempData.Keep();
return RedirectToAction(nameof(CloseIssue));
}
}
else
{
return View(IVM);
}
Here is the CloseIssue code:
[HttpGet]
public ActionResult CloseIssue()
{
ViewBag.id = TempData["ID"].ToString();
return PartialView("_CloseIssue");
}
I've tried variations of the following (note that these don't represent the code snippets above) but can't get the form data submitted as well as showing the modal:
$('body').on('click', '.clse', function () {
var actionUrl = $(this).attr('href');
$.get(actionUrl).done(function (data) {
$('#closecontent').find('#modal-content3').html(data);
});
$(this).attr('data-target', '#modal-container3');
$(this).attr('data-toggle', 'modal');
});
$('#closecontent').on('click', '.closeissue', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
form.submit();
$('.modal').show();
})
$('#closecontent').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
//Some action after data is posted
});
})
$(function () {
$('#DisplayFileContent').on('click', '.fileupload', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var fdata = new FormData();
$("form input[type='text']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$("form input[type='hidden']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$.ajax({
url: actionUrl,
method: "POST",
contentType: false,
processData: false,
data: fdata
}).done((response, textStatus, xhr) => {
//Some action to show modal
});
})
});
The last one above sends some of the form's data but not all of it.
So to sum up, I need the ability to send the entire form's data on a "Close Issue" button click, and then display a confirmation dialog box once the form data is successfully saved.
Update 11/4
Let me clarify. I tried each of the different javascript options above to try and send the form data. The only one that partially worked was a modification of the last one. Here is what I have at this point on that modification:
$(function () {
$('#closecontent').on('click', '.closeissue', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = "/Issue/Edit/?saveClose=close"//form.attr('action');
var fdata = new FormData();
$("form input[type='text']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$("form input[type='hidden']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
for (var pair of fdata.entries()) {
alert(pair[0] + ', ' + pair[1]);
}
alert(actionUrl);
$.ajax({
url: actionUrl,
method: "POST",
contentType: false,
processData: false,
data: fdata
}).done((response, textStatus, xhr) => {
//Do something
});
})
});
It is not setup to iterate through and determine if a checkbox is selected (It returns all of them as FALSE.
It does not iterate any of the Multi-select controls to show the selected items.
It does not iterate any dropdown controls to identify what is selected.
If I can get that working then the form data will be posted properly. I would want the multi-selects to be formatted the SAME way the FormCollection object formats them. i.e. the formcollection formats the multi-selected values like this: [Users,{L012,L013}]
I wouldn't want it to be formatted as [Users,{L012}],[Users,{L013}]
Assuming this can get worked out, the next step would be to alter what happens in the following code:
$.ajax({
url: actionUrl,
method: "POST",
contentType: false,
processData: false,
data: fdata
}).done((response, textStatus, xhr) => {
//Do something - If model didn't validate then do NOT show _Close partial view in modal
//Do Something - If model validates them display _close Partial in a modal
});
I have an input field and "Add" button to store. While clicking the Add button another input field with the same class name should be created. But before creating there is a validation check. But the validation is only hitting first time. There is no validation check in the second time.
Below is my Code.
$('#add').click(function (e) {
e.preventDefault();
if ($('.js-user-email').val()) {
debugger;
$("#divSpecificToUserError span").text("");
$('#divSpecificToUserError').addClass("d-none");
if (ValidateEmailformat($('.js-user-email').val())) {
//debugger;
$.ajax({
type: "POST",
url: "Stepup.aspx/Exists",
data: JSON.stringify({ emailId: $('.js-user-email').val() }),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
if (response != null && response.d != null) {
var data = response.d;
if (data > 0) {
addDynamicTextboxes();
}
else {
$("#divSpecificToUserError span").text("not a valid user");
$('#divSpecificToUserError').removeClass("d-none");
}
}
},
failure: function (response) {
alert(response.d);
}
});
}
else {
$("#divSpecificToUserError span").text("Please enter email id in valid format");
$('#divSpecificToUserError').removeClass("d-none");
}
}
else {
$("#divSpecificToUserError span").text("No E-mail has been entered ");
$('#divSpecificToUserError').removeClass("d-none");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field form-group form-group-padding">
<label class="col-form-label">User E-mail(s) to Notify:</label>
<input type="text" id="field1" name="userEmail1" class="input form-control js-user-email" placeholder="example#domain.com" autofocus />
<button id="add" class="btn-sm btn-secondary add-more-specific pull-right btn-user-email" title="Add" type="button">+</button>
<div class="col-md-3 d-none alert-danger" id="divSpecificToUserError" style="margin-top: 6px">
<span></span>
</div>
</div>
$('.btn-user-email') if this is multiple elements you need to loop it and add click events to all elements in the jQuery list.
Oh, I see what your problem is.
// Your Add Button Function
// to insert another input here
function add(){
// Your Add Button Code Here
refreshValidate();
}
// Validate Function
function refreshValidate(){
$('.btn-user-email').each(function() {
$(this).unbind();
$(this).click(function (e) {
e.preventDefault();
// Your Validate Code HERE ...
});
});
}
I am trying to upload an image to database from html page in a form in a modal through php & ajax,but it doesn't work i don't know why,anyone can help me?
HTML Page
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-sm-4">
<label class="Modallabel">Photo:</label>
</div>
<div class="col-sm-8">
<div class="input-group input-group-sm" style="margin-top: -5px;">
<input type="file" id="fileUpload" name="fileUpload" style="color: #ffffff;"/>
</div><br>
</div>
</div>
</form>
<button type="button" class="btn btn-success btn-md" style="margin:0;width: 75px;" onclick="AddNewCustomer()">Add</button>
Javascript Function
function AddNewCustomer()
{
//Image upload
$(document).ready(function()
{
$(document).on('change', '#fileUpload', function() //NOT WORKING HERE
{
var property = document.getElementById("fileUpload").files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if (jQuery.inArray(image_extension, ['gif','png','jpg','jpeg']) == -1)
{
alert("invalid Image File");
}
var image_size = property.size;
if(image_size > 2000000)
{
alert("Image File Size is very big");
}
else
{
var form_data = new FormData();
form_data.append("fileUpload", property);
$.ajax
({
type:"POST",
url:"addNewCustomer.php",
processData: false,
cache: false,
contentType: false,
data:
{
'form_data':form_data
},
success: function(data){
if (data == "Success!")
{
sweetAlert("Data entered successfully!");
}
else if(data == "Exist")
{
sweetAlert("","Customer already exists!","error");
return false;
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ERROR', textStatus, errorThrown);
}
})
}
})
})
}
change event would be attached after click at <button> at onclick="AddNewCustomer().
You can remove AddNewCustomer function and call change on #fileUpload element at click of .btn element.
$(document).ready(function() {
$(document).on('change', '#fileUpload', function() {//do stuff})
$(".btn").on("click", function() {
$("#fileUpload").trigger("change");
});
});
You want to upload the image immediately after it's chosen, but you only run the function when the 'Add' button is clicked.
You need to take your change code out of the function, or invoke the function when the page is loaded to add the listeners to the form.
I have a form with two submit buttons, one for create, one for edit
<div class="modal-footer">
<button name="add" class="companyCreateSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" onclick="CompanyCreate()">Add</button>
<button name="edit" class="companyEditSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" onclick="CompanyEdit()">Save</button>
</div>
Here are my onclick functions:
function CompanyCreate() {
//work experience create
$("#companyForm").submit(function (event) {
//validate form
if (!$(this).valid()) {
return;
}
//serialize the form
serializedForm = $(this).serializeArray();
cvId = $("#CVId").val();
serializedForm.push({ name: "cvId", value: cvId });
//ajax post
$.ajax({
url: "#Url.Action("CompanyCreate", "CV")",
type: "POST",
data: serializedForm,
beforeSend: function () {
l.ladda("start");
},
success: function (result) {
if (result.success) {
//add row to table
cTable.fnAddData([
result.id,
result.name,
result.title,
result.city,
result.country,
$.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.startdate.substr(6)))),
$.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.enddate.substr(6)))),
result.description,
"<button class='companyEditBtn btn'' title='Edit Work Experience'><i class='icon-pencil'></i></button>" + " " + "<button class='companyDeleteBtn btn'><i class='icon-trash'></i></button>"
]);
//success
toastrSuccess(result.message);
} else {
//fail
toastrError(result.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
//fail
toastrError(textStatus);
},
complete: function () {
//stop ladda button loading
l.ladda("stop");
//hide modal
$(".modal").modal("hide");
}
});
//prevent default submit behaviour
event.preventDefault();
event.stopImmediatePropagation();
});
}
function CompanyEdit() {
//work experience edit
$("#companyForm").submit(function (event) {
//validate form
if (!$(this).valid()) {
return;
}
//serialize the form
serializedForm = $(this).serialize();
//ajax post
$.ajax({
url: "#Url.Action("CompanyEdit", "CV")",
type: "POST",
data: serializedForm,
beforeSend: function () {
l.ladda("start");
},
success: function (result) {
if (result.success) {
//update row of table
cTable.fnUpdate([
result.id,
result.name,
result.title,
result.city,
result.country,
$.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.startdate.substr(6)))),
$.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.enddate.substr(6)))),
result.description,
"<button class='companyEditBtn btn'' title='Edit Work Experience'><i class='icon-pencil'></i></button>" + " " + "<button class='companyDeleteBtn btn' title='Delete Work Experience'><i class='icon-trash'></i></button>"
], position);
toastrSuccess(result.message);
} else {
toastrError(result.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
toastrError(textStatus);
},
complete: function () {
//stop ladda button loading
l.ladda("stop");
//hide modal
$(".modal").modal("hide");
}
});
//prevent default submit behaviour
event.preventDefault();
event.stopImmediatePropagation();
});
}
Every time i click the Save button, it goes to the CompanyCreate() function instead of the CompanyEdit() function, what am i doing wrong?
You can do something as follows:
$('#companyForm').on('submit', function(e) {
e.preventDefault(); // stops form from being submitted
// get the clicked button name
var clickedButton = $(document.activeElement).attr('name');
if (clickedButton === 'edit') {
companyEdit();
}
if (clickedButton === 'add') {
companyAdd();
}
});
function companyEdit() {
// your code to edit company
alert('editing company');
}
function companyAdd() {
// your code to add company
alert('adding company');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-footer">
<form id="companyForm">
<button name="add" class="companyCreateSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Add</button>
<button name="edit" class="companyEditSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Save</button>
</form>
</div>
UPDATE
If you do not wish to use the former example, you can simply do the following. Not that using events like onclick in the dom is considered as bad practice and should be done in javascript.
$('.companyEditSubmitBtn').on('click', function(e) {
e.preventDefault(); // stops form from being submitted
alert('editing company');
});
$('.companyCreateSubmitBtn').on('click', function(e) {
e.preventDefault(); // stops form from being submitted
alert('creating company');
});
Here is working js-fiddle
<div class="modal-footer">
<button type="button" id="CompanyCreate" name="add" class="companyCreateSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Add</button>
<button type="button" id="CompanyEdit" name="edit" class="companyEditSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Save</button>
</div>
Jquery code is
$(document).ready(function () {
$("#CompanyCreate").click(function () {
//your code here
});
$("#CompanyEdit").click(function () {
//your code here
});
});
Simple pattern I use (MVC based):
1. Create custom attribute
[AttributeUsage(AttributeTargets.Method)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
public string Name { get; set; }
public string Argument { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
var isValidName = false;
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
isValidName = true;
}
return isValidName;
}
}
2. Controller
MultipleButton(Name = "action", Argument = "Action1")
public ActionResult Action1(MyModel model)
{...}
[MultipleButton(Name = "action", Argument = "Action2")
public ActionResult Action2(MyModel model)")]
{...}
3. View
#using (Ajax.BeginForm("Action1", "Search", new AjaxOptions { }))
{
<button type="submit" name="action:Action1" >Action1</button>
<button type="submit" name="action:Action2" >Action2</button>
}
Prevent using .submit function inside .click, it will not work, instead you have to grab the form and post it.
NO
$("#companyCreateSubmitBtn").click(function () {
$("#companyForm").submit(function (event) {
//validate form
if (!$(this).valid()) {
return;
}
//prevent default submit
event.preventDefault();
//ajax post etc...
YES
$("#companyCreateSubmitBtn").click(function () {
//get the form
var form = $("#companyForm");
//validate form
if (!form.valid()) {
return;
}
//ajax post etc..
Remember your button type has to be type="button" instead of the default type="submit"
<button id="companyCreateSubmitBtn" name="add" class="ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" type="button">Add</button>