Validate form and some inputs at same time - javascript

Here I have a form and I need to validate form. I have select2 input fields and this fields I cant validate with parsley plugin so I write my code...
Problem is how to at same time check if validate = true and select2 inputs ===null...
I write:
$(function() {
$('#myForm').submit(function(e) {
e.preventDefault();
if ( $(this).parsley('validate') ) {
if ($("#parcele").select2("data")== null || $("#vrsta_rada").select2("data")== null) {
$('#parerror').show();
console.log('nema dalje');
} else {
var zemljiste = $("#parcele").select2("data").naziv;
var id_parcele = $("#parcele").select2("data").id;
var vrsta_rada = $("#vrsta_rada").select2("data").text;
$.ajax({
url: "insertAkt.php",
type: "POST",
async: true,
data: { naziv:$("#naziv").val(),parcele:zemljiste,vrsta_rada:vrsta_rada,opis:$("#opis").val(),pocetak:$("#pocetak").val(),zavrsetak:$("#zavrsetak").val(),status:$("#status").val(),id_parcele:id_parcele,}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#myModal').modal('hide');
drawVisualization();
console.log('USPEH');
console.log(data);
},
error: function (data) {
console.log(data);
console.log('GRESKA NEKA');
}
});
}
}
});
});
but as you can see my code first check form validation after that select2 inputs so how I can at same time check form and select2 inputs fields?

By using && operator you can check both condition at the same time
if ( ($(this).parsley('validate')) && ($("#parcele").select2("data") === null)) {
}

Related

jQuery ajax input field event, options list and setting a value

I am trying to create an AJAX function to autocomplete the input field.
The user starts typing in location/city name, and it should trigger an AJAX call for lookup, presenting suggestions of matching city names list to the input field. Then the user selects one value and that is set to that input field. The below code doesn't even trigger events, I do not see request activity on the network. How to accomplish this?
$(function() {
$('#locationName').keyup(function() { //tried keyup, input
alert('Ok'); // to test event
$.ajax({
type: 'POST',
url: '/locationsearch',
data: {
'search_text': $('#locationName').val()
},
success: searchSuccess,
dataType: 'text'
});
});
});
function searchSuccess(data) {
locationName.val = 'data';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="locationName" id="locationName">
Your example does not seem complete. It's not clear where locationName is defined. Consider the following snippet.
$(function() {
function searchLoc(txt) {
var result = "";
$.post("/locationsarch", {
"search_text": txt
}, function(data) {
result = data;
});
return result;
}
$('#locationName').keyup(function() {
var q = $(this).val();
if (q.length >= 3) {
$(this).val(searchLoc(q));
}
});
});
It's not clear what the resulting data will be, I am assuming text or HTML.

Unable to prevent form when a condition is met

I am working on a form I wish to validate via jQuery $.ajax. The form should only be submitted if a certain condition, data == 1
var preventSubmit = function() {
return false;
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// if data is equal to 1,
// submit form
if (data == 1) {
return true;
}
}
});
};
$("#comment_form").on('submit', preventSubmit);
The submit happens regardless if the condition is met or not.
Where is my mistake?
If I use e.preventDefault();, how can I "undo" it in case if data is equal to 1?
You won't be able to allow the submission of the form with a return value of true because the ajax is happening asynchronously (by the time it completes the function has already finished executing). What you can do is always prevent the form from submitting in the preventSubmit function, then submit it programmatically.
var preventSubmit = function() {
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// if data is equal to 1,
// submit form
if (data == 1) {
form.off();//remove bound events (this function)
form.submit();//manually submit the form
}
}
});
return false;//the return needs to be at the end of the function and will always prevent submission
};
$("#comment_form").on('submit', preventSubmit);
Anything after the return false; will never be executed.
Also, you should be doing form validation on the front-end rather than the back-end. With that being said, you should not remove the validation from the back-end.
One more thing, try doing HTML5 form validation first as that's your first line of defence.
You're looking at something on the lines of:
var validateForm = function(e) {
// prevent the default form action to allow this code to run
e.preventDefault();
var isValid = false,
form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
// Validation goes here
// ...
// isValid = true;
if (isValid) {
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// do something with the response. Maybe show a message?
form.submit();
}
});
}
};

Jquery : Want to disable all the input fields if editqastatus value = 1 or 2

Jquery : Want to disable all the input fields in the modal form if input field editqastatus value = 1 or 2.
function editMember(id = null) {
if(id) {
// remove the error
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
// empty the message div
$(".edit-messages").html("");
// remove the id
$("#member_id").remove();
// fetch the member data
$.ajax({
url: 'php_action/getSelectedMember.php',
type: 'post',
data: {member_id : id},
dataType: 'json',
success:function(response) {
$("#editqastatus").val(response.qastatus);
$("#editdisqreason").val(response.disqreason);
$("#editcampaignname").val(response.campaignname);
$("#editassettitle").val(response.assettitle);
// here update the member data
$("#updateMemberForm").unbind('submit').bind('submit', function() {
I'm not really sure if you are talking about this:
if ($("#editqastatus").val() == 1 || $("#editqastatus").val() == 2) {
$(".modal").find('input').attr('disabled', 'disabled')
} else {
$(".modal").find('input').removeAttr('disabled')
}
replace the ".modal" with the class wrapping your inputs in the modal.

Passing variable from a function into submit function

$('.report_filter input') get value of selected radio box sending the variable to function report_operation, from there on I hide some fields based on the selection
$(".js-ajax-php-json") ajax form submission, I want to get inside the .submit the var value. There I could do some if empty field return false to stop the form from submitting. For instance if field name="number" is empty and the var value is 1 return false; This can't be made by a simple form validator, its a quite dynamic form.
I just have no idea how to do that
$('.report_filter input').on('ifChecked', function(event){
var val = $(this).val();
raport_operation(val);
});
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "test1"
};
data = $(this).serialize() + "&" + $.param(data);
alert(raport_operation());
// if ($("#number").val() == "" and val == 1) {
// alert('you did not fill out one of the fields');
// return false;
// }
$.ajax({
type: "POST",
dataType: "json",
url: "api/response.php",
data: data,
success: function(data) {
draw_graph(data);
$(".the-return").html(data);
//alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
function raport_operation(query){
//alert(val);
if(query==1){ //number
//alert(1);
$('#segment_optional').hide('slow');
$('#segment_number').show('slow');
$('#segment_optional').show('slow');
$('#segment_customer').hide('slow');
$('#segment_listType').hide('slow');
$('#segment_customer').val('');
$('#reportdate_to').val('');
$('#reportdate_from').val('');
// $('#segment_general').hide();
}
}

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});

Categories

Resources