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 ...
});
});
}
Related
I am faced with a problem which is a real disaster. After I click the send button to send variables via Ajax to my PHP page, a form reset will get triggered in success response. But the input values are liked to be cached, so when I click the send button while inputs are empty, it resends the previous inserted values.
Moreover, I have disabled the form submission event to prevent submitting the form.
Here is the sample code:
<body>
<form id="myform">
<input class="area" type="text"></input>
<input class="area" type="text"></input>
<input class="area" type="text"></input>
<button id="add">Add</button>
</form>
<div class="response"></div>
</body>
$(document).ready(() => {
$(document)
.off()
.on("click", "#add", function (e) {
e.preventDefault();
var area = $(".area");
area.each(function (i) {
if ($(this).val()) {
var x = $(this).val();
areadim.splice(i, area.length, x);
}
});
$.ajax({
type: "POST",
url: "addsettings.php",
data: {
area: area,
},
beforeSend: function () {
if (areadim.length == 0) {
alert("fill up all inputs");
currentRequest.abort();
} else if (areadim.length <= area.length) {
$.each(area, function () {
if ($(this).val() < 100) {
alert("input is less than 100");
currentRequest.abort();
}
});
}
},
success: function (response) {
$("#myform").trigger("reset");
$(".response").append(response);
$(".area").val("");
},
});
});
});
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>
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
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.
Is there a way to change my input in order to display a succes or error icon at the input? like : http://getbootstrap.com/css/#forms-control-validation
Much appreciated.
and here's my code :
<script>
$(document).ready(function () {
$('input[name=subdomain]').keyup(subdomain_check);
});
function subdomain_check() {
var subdomain = $('input[name=subdomain]').val();
if (subdomain == "") {
$('input[name=subdomain]');
} else {
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: 'subdomain=' + subdomain,
cache: false,
success: function (response) {
if (response == 1) {
$('input[name=subdomain]').html("The URL already exist!");
} else {
$('input[name=subdomain]').html("The URL is Valid!");
}
}
});
}
}
</script>
The HTML code :
<div class="form-group">
<label class="control-label col-md-3" for="install-element-6">
<span class="required">* </span>subdomain</label>
<div class="col-md-6"> //<----- I want it here
<input type="text" class="form-control input-md col-md-6" name="subdomain" placeholder required id="install-element-6"/> // the method.addClass add it here
</div>
</div>
Much appreciated.
It worked now and all by adding the method parent() to get the element div instead of input
if(response == 1){
$('input[name=subdomain]').parent().removeClass("has-success");
$('input[name=subdomain]').parent().addClass("has-error");
}else{
$('input[name=subdomain]').parent().removeClass("has-error");
$('input[name=subdomain]').parent().addClass("has-success");
}