Dynamic form input fields and autocomplete using AJAX - javascript

I have a working code where I can dynamically add input fields which can be used for auto-completion using AJAX. Though working, there are limitations. After adding more fields, placement of the autofill is incorrect, as demonstrated in this image:
The results are not showing under the current input field but rather under the last one. Lastly, once the user adds too many input fields and starts removing them, the autocomplete feature stops working altogether.
HTML Code:
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Case Category <button style="margin-top: 5px;" id = "add_field" class="add_field btn btn-primary btn-xs">+</button></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="search_keyword_idd" class="search_keywordd form-control col-md-5 col-xs-12" name="category[]" required="required" type="text">
<input type="hidden" name="catID[]" id="catID"/>
<div id="resultd"></div>
</div>
</div>
<div class = "t"></div>
Javascript/jQuery Pt. 1: (on the first input field)
<script type="text/javascript">
$(function(){
$(".search_keywordd").keyup(function()
{
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "../resources/ajax-search/case_category.php",
data: dataString,
cache: false,
success: function(html)
{
$("#resultd").html(html).show();
}
});
}
return false;
});
jQuery("#resultd").on("click", ".show", function(e){
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_idd').val(showName);
$('#catID').val(showId);
});
jQuery(document).on("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keywordd")){
jQuery("#resultd").hide();
}
});
$('#search_keyword_idd').click(function(){
jQuery("#resultd").show();
});
});
</script>
Javascript/jQuery Pt. 2: (on the input fields that the user want to add)
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper3 = $(".t"); //Fields wrapper
var add_button3 = $("#add_field"); //Add button ID
var z = 1; //initlal text box count
$(add_button3).click(function(e){ //on add input button click
e.preventDefault();
if(z < max_fields){ //max input box allowed
z++; //text box increment
$(wrapper3).append('<div class="item form-group"><label class="control-label col-md-3 col-sm-3 col-xs-12"></label><div class="col-md-6 col-sm-6 col-xs-12"><input id="search_keyword_idd'+z+'" class="search_keywordd'+z+' form-control col-md-5 col-xs-12" name="category['+z+']" required="required" type="text"><input type="hidden" name="catID['+z+']" id="catID'+z+'"/><div id="resultd'+z+'"></div><button class="remove btn btn-dark">Remove</button></div></div>'); //add input box
$("#resultd"+z+"").css({"margin-top": "40px", "position": "absolute", "display": "none", "border-top": "0px", "overflow": "visible", "border": "1px #F0F0F0 solid", "float": "left", "padding": "0"});
//$(".show"+z+"").css("cursor:", "default", "margin:", "0", "display:", "none", "background:", "#F7F7F7", "width:", "548px", "border-bottom:", "#F0F0F0 1px solid", "position:", "relative", "z-index:", "10");
}
$(".search_keywordd"+z+"").keyup(function() {
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='') {
$.ajax({
type: "POST",
url: "../resources/ajax-search/case_category.php",
data: dataString,
cache: false,
success: function(html)
{
$("#resultd"+z+"").html(html).show();
}
});
}
return false;
});
jQuery("#resultd"+z+"").on("click", ".show", function(e){
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_idd'+z+'').val(showName);
$('#catID'+z+'').val(showId);
});
jQuery(document).on("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keyword"+z+"")){
jQuery("#resultd"+z+"").hide();
}
});
$('#search_keyword_idd'+z+'').click(function(){
jQuery("#resultd"+z+"").show();
});
$(wrapper3).on("click",".remove", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').parent('div').remove(); y--;
});
});
});
PHP:
<?php
include('config.php'); //working just fine
if($_POST)
{
if($_POST['search_keyword']) // returns an error from answer 1
{
$similar = mysql_real_escape_string($_POST['search_keyword']);
$result=mysqli_query($conn, "SELECT * FROM casecategory WHERE (caseCategoryName like '" . $_POST["search_keyword"] . "%')");
if (mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_array($result))
{
?>
<div class="show" align="left">
<span class="returnName"><?php echo $row["caseCategoryName"] ?></span>
<span class="returnID" style="display:none"><?php echo $row['idCaseCategory'];?></span>
</div>
<?php
}
}
else {
?>
<div class="show" align="left">
<span class="returnMessage">No matching records found.</span>
</div>
<?php
}
}
mysqli_close($conn);
}
?>
I am at a loss as to which part(s) are not working and how to fix it so that:
The auto-complete box displays under the current onfocus input
When max-amount of inputs are added and then removed, that the auto-complete feature still works

See if this is what you are looking for. The HTML appears to be correct when looking at the console, but I don't have your css, so it's hard to say. The changes:
1) I have removed all the id values in favor of using just classes. That way you don't have to worry about id values...what works for a static block of html, will work for a dynamic block so note all the changes in the html
2) I have consolidated all js to just what I have pasted below
3) There is only one instance of ajax
4) All clicks are relegated to one if/else/else if condition:
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Case Category <button style="margin-top: 5px;" class="add_field btn btn-primary btn-xs">+</button></label>
<div class="col-md-6 col-sm-6 col-xs-12 search_wrap">
<input class="search_keyword form-control col-md-5 col-xs-12" name="category[]" required="required" type="text">
<input type="text" name="catID[]" />
<div class="resultd"></div>
</div>
</div>
<div class = "t"></div>
Javascript
<script type="text/javascript">
// I have created an ajax instance incase you want to use ajax else where
// You just make a new instance instead of copy/pasting same scripts
var AjaxEngine = function()
{
$ = arguments[0];
var url = '../resources/ajax-search/case_category.php';
// Allows you to use a different destination for the call
this.useUrl = function()
{
if(arguments.length === 1) {
url = arguments[0];
}
return this;
};
this.ajax = function(data,userFunc)
{
$.ajax({
type: "POST",
url: url,
// Send data object instead of string
data: data,
cache: false,
// Not hardcoding a response will allow
// for flexibility
success: function(response) {
userFunc(response);
}
});
}
}
// I just created a php-like empty function
function empty(val)
{
return (val !== null && val !== false && val !== '')? false : true;
}
// Group everything into one document ready
$(function(){
// Hide dropdown
$(this).click(function(e) {
var target = $(e.target);
if(!target.hasClass('resultd')) {
$('.resultd').hide();
}
});
// Create ajax engine
var Remote = new AjaxEngine(jQuery);
// run the keyword search, I would use this here so you can
// get all instances of keyup, both dynamic and static instances
$(this).on('keyup',".search_keyword",function(e){
var sTerm = $(this).val();
var thisWrap = $(this).parents('.form-group').find('.resultd');
if(!empty(sTerm)) {
Remote.ajax({ search_word:sTerm },function(response) {
thisWrap.html(response).show();
});
}
});
// Create the copy-to function
function copyTo(thisShow)
{
var showName = thisShow.find('.returnName').text();
var showId = thisShow.find('.returnID').text();
var thisWrap = thisShow.parents('.search_wrap').find('input[name=category\\[\\]]');
thisWrap.val(showName);
thisWrap.next().val(showId);
};
// Create the add field function
function addNewField(obj,max_fields,z)
{
if(z < max_fields){
obj.append('<div class="item form-group"><label class="control-label col-md-3 col-sm-3 col-xs-12"></label><div class="col-md-6 col-sm-6 col-xs-12 search_wrap"><input class="search_keyword search_keywordd form-control col-md-5 col-xs-12" name="category[]" required="required" type="text"><input type="text" name="catID[]" /><div class="resultd"></div><button class="remove btn btn-dark">Remove</button></div></div>'); //add input box
var lastRes = obj.find(".resultd");
lastRes.last().css({"margin-top": "40px", "position": "absolute", "display": "none", "border-top": "0px", "overflow": "visible", "border": "1px #F0F0F0 solid", "float": "left", "padding": "0"});
z++;
// return the auto-increment count
return z;
}
// return the max count
return max_fields;
}
var settings = {
z: 1,
max_fields: 10
}
$(this).on("click", '.show,.search_keyword,.add_field,.remove', function(e) {
// Target the click
var clicked = $(this);
// Hide by default
$(".resultd").hide();
// Run the copyto
if(clicked.hasClass("show")) {
copyTo(clicked);
}
// Show the search window
else if(clicked.hasClass("search_keyword")) {
clicked.parents('.search_wrap').find('.resultd').show();
}
// Add fields
else if(clicked.hasClass("add_field")) {
settings.z = addNewField($(".t"),settings.max_fields,settings.z);
}
// remove fields
else if(clicked.hasClass("remove")) {
e.preventDefault();
clicked.parent('div').parent('div').remove();
settings.z--;
}
});
});
</script>

Related

Java script validation issues

I have a bug that I could not figure out in my validation method. I have a function that validate the "code" table in my database to make sure the user can not input duplicate data. It is all working as expected and here is the code:
function validateCode() {
$('#code-error').html('')
if ($('#code').val() != '') {
$.ajax({
url: '${createLink(action:'checkCode')}',
type: 'GET',
data: {
'code': $('#code').val(),
},
// dataType:'json',
success: function (data) {
if (data == 'true') {
$('#code-error').html('Code already exist')
$(':input[type="submit"]').prop('disabled', true);
} else {
// $('#code-error').html('Code not exist')
$(':input[type="submit"]').prop('disabled', false);
}
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
}
}
But it is not stable.First the message and the button are disabled in the first couples of tried but if I continue to test it by re-enter the code that exist and the code that does not exist the button disabled however the error message is not showing under the input box.
Here is my html code :
<div class = "row" style = "margin-top:15px;">
<div class = "col-md-12">
<div class = "row">
<div class = "col-md-5 text-right" style = "font-weight: bold"><span class="placeholder">Code</span></div>
<div class = "col-md-7">
<div class="form-group">
<input style = "width: 50%"type="text" class="form-control" onkeyup="validateCode()" id="code" placeholder="Enter code" name="code">
<input type="hidden" name="current-code" id = "current-code">
<div class = "row">
<div id = "code-error" class = "col-md-12" style ="color:red"></div>
</div>
</div>
</div>
</div>
</div>
</div>
And here is my controller function for validating the code:
def checkCode() {
def allow
String compareCode = params?.code
def customer = Customer.findByCode(compareCode)
if (customer == null) {
allow = false //not exist
} else if (customer != null) {
allow = true //exist
}
render allow
}

jQuery validate , how to make validation rules for dynamically generated fields?

I have an HTML form with dynamically add more fields. For example company name. I am trying to use the jQuery validate method to validate. It is working fine with the existing company name field. Here is the code.
<script>
$("#company_creation_form").validate({
rules:{
company_name: {
required: true,
minlength: 3
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize()+"&company_count="+company_count,
success: function () {
alert("thanks");
}
});
return false; // required to block normal submit since you used ajax
}
});
</script>
When I click on add more button another company name field will create on the form. The below code is failed to validate the dynamically generated field. Here I am getting the field count globally in this variable company_count
<script>
$("#company_creation_form").validate({
rules:{
company_name: {
required: true,
minlength: 3
},
I tried like below, but this is giving me error
if(company_count> 0){
var new_field = jQuery("#company_name"+company_count);
new_field : {
required: true,
minlength: 3
},
}
The above block code is showing error in the text editor it self
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize()+"&company_count="+company_count,
success: function () {
alert("thanks");
}
});
return false; // required to block normal submit since you used ajax
}
});
</script>
Can anyone help me with how to make validation for these dynamically generated fields? Any help would be greatly appreciated. I am using form submission by using Ajax.
Code to add company fields dynamically
var company_room = 0;
var company_room1 = 0;
function add_another_company() {
company_room++;
company_room1++;
var objTo = document.getElementById('company_field')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass2" + company_room);
//var rdiv = 'removeclass2' + company_room;
divtest.innerHTML = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="company_name" name="company_name" placeholder="Company Name"></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button" onclick="remove_another_company(' + company_room + ');"> <i class="fa fa-minus"></i> </button> </div></div></div>';
objTo.appendChild(divtest);
var E_fields = $('.aj4');
var E_count = 1;
$.each(E_fields, function() {
jQuery(this).attr('id','company_name' + E_count);
jQuery(this).attr('name','company_name' + E_count);
E_count++;
});
}
function remove_another_company(rid2) {
company_room1--;
$('.removeclass2' + rid2).remove();
var E_fields = $('.aj4');
var E_count = 1;
$.each(E_fields, function() {
jQuery(this).attr('id','company_name' + E_count);
jQuery(this).attr('name','company_name' + E_count);
E_count++;
});
}
OK, so I didn't have your HTML so I had to mock some up. You will obviously have to tweak this a little to work with your ID's. I tried to keep it as close as possible to the ID's/classes you were already using.
I removed the pure javascript functions and the onclick events in favor of jquery since you were already using it. Hopefully this kind of simplifies things a bit and makes it more manageable.
NOTE: I added a hidden input field to keep track of company count. This way it will be included when you $(form).serialize in your ajax options (as you are adding it with a variable now). I included code to preserve the company_count variable also, so basically you will have 2 company counts. I did this just to show you an easier way to keep track of this without having to micro manage it. :)
Try out this code and let me know what your getting in console if it is not working. Thanks
MOCK HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form-wrapper">
<p>Dynamic Form</p>
<button id="addField">Add Dynamic Field</button>
<form id="dynForm">
Static Field: <input id="company_name" name="company_name" minlength="3" type="text" value="Static Company Name" required>
<br>
<input type="hidden" id="companyCount" name="companyCount" value="1">
<div id="company_field">
</div>
</form>
</div>
JQUERY/JS
$(function() { // <---- Document Ready!
$("#addField").on("click", () => {
var count = parseInt($("#companyCount").val(), 10);
count += 1;
$("#companyCount").val(count.toString());
var thisId = "company_name" + count.toString();
var html = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="'+thisId+'" name="'+thisId+'" minlength="3" placeholder="Company Name" required></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button"> <i class="fa fa-minus"></i> </button> </div></div></div>';
var ele = $.parseHTML(html);
$("#company_field").append(ele);
});
$("#company_field").on("click", "button", () => $(this).closest(".form-row").remove());
$("#company_creation_form").validate({
submitHandler: function(form) {
var company_count = parseInt($("#companyCount").val(), 10);
$.ajax({
type: "POST",
url: "<?php echo BASE_URL;?>crm/thankyou/",
data: $(form).serialize() + "&company_count=" + company_count,
success: function() {
alert("thanks");
}
});
return false;
}
});
});

When the cursor leaves the input box #select-or-enter-category, this code checks whether the given input exists in the dropdown or not

I have this code I use for showing a warning message:
<div class="row clearfix">
<div class="col-sm-8 col-sm-offset-2">
<div>
<div class="form-line focus">
<span class="category-status" style="color: red;">
This entered category is not found in the category list.<br>
Press button on the right to save this new category.
</span>
</div>
</div>
</div>
</div>
Then, I have another code use for typeahead dropdown:
<div class="row clearfix">
<div class="col-sm-7 col-sm-offset-2">
<div class="form-group form-float">
<div class="form-line focus">
<input type="hidden" id="cat-id" name="category_id" value="">
<input type="text" id="select-or-enter-category" name="category" data-provide="typeahead"
placeholder="Enter/Select a category" value="" required="required" class="form-control">
</div>
</div>
</div>
<div class="col-sm-1">
<button type="button" id="save-category" data-toggle="tooltip" data-placement="top" title=""
class="btn btn-warning" data-original-title="Save this input as New Category">
<i aria-hidden="true" class="fa fa-bookmark-o" style="display: inline;"></i>
</button>
</div>
</div>
And this is my javascript/jquery code:
When the user types keyword in an input box #select-or-enter-category,
this javascript code will give a dropdown as typeahead for the given keyword.
/**
* Autocomplete for category - ADD TASK MODAL
* #return {[type]} [description]
*/
$(document).ready(function(){
axios_get('/axiosCategory', function(data) {
var cat = [];
var $input = $("#select-or-enter-category");
let temp;
data.forEach(function(item) {
temp = {
id: item.id,
name: item.categoryName
}
cat.push(temp);
});
$input.typeahead({
source: cat,
autoSelect: true
});
$input.change(function() {
// console.log($input);
var current = $input.typeahead("getActive");
if (current) {
$('#cat-id').val(current.id);
}
});
});
});
When the cursor leaves the input box #select-or-enter-category, this code checks whether the given input exists in the dropdown or not. If not, the warning message will show up that will ask the user to save the input as a new category.
/**
* Display the message asking the user to save the
* new category
*
* #return void
*/
$('#select-or-enter-category').focusout(function() {
let val = $(this).val();
axios_get('/axiosCategory', function(data) {
let search = false;
data.forEach(function(item) {
if (val == item.categoryName) {
search = true;
}
});
if (search == false) {
$('.category-status').removeAttr('hidden');
} else {
$('.category-status').attr('hidden', true);
}
});
});
Then problem is that when the user clicks an item from the dropdown using the mouse, the error message shows up which is not what I want to happen.
I want the error message to show up only when the cursor actually leaves the input box #select-or-enter-category.
But if the user only uses keyboard for choosing an item from the dropdown and enter it, there is no problem.
Do you have any suggestions?
Try this one
$(document).ready(function(){
axios_get('/axiosCategory', function(data) {
dataGlobal = data;
var cat = [];
var $input = $("#select-or-enter-category");
let temp;
data.forEach(function(item) {
temp = {
id: item.id,
name: item.categoryName
}
cat.push(temp);
});
$input.typeahead({
source: cat,
autoSelect: true
});
$input.change(function() {
var current = $input.typeahead("getActive");
if (current) {
$('#cat-id').val(current.id);
}
});
$input.focusout(function() {
let val = $('#select-or-enter-category').val();
let current = $input.typeahead("getActive");
let search = false;
let str = current.name.substring(0,val.length);
if (str == val) {
val = current.name;
}
dataGlobal.forEach(function(item) {
if (val == item.categoryName) {
search = true;
}
});
if (search == false) {
$('#category-status').removeAttr('hidden');
} else {
$('#category-status').attr('hidden', 'hidden');
}
});
});
});

Adding Jquery UI to UL in HTML

I want to be able to add jquery UI to the list on GoalNotes This table gets populated by what the user enters in the "name1" and "data1" input fields. Every time I give the an id, the program breaks and I get no errors. Any ideas on how I could apply animations to the table rows that get added after the user inputs data?
html
<section class="section section--active color1" data-letter="M">
<article class="section__wrapper">
<h1 class="section__title">Monday</h1>
<div id="Monday" class="tabcontent">
<form name="goalsList1" action = "/created" method="POST">
<div id="tab1">
<table>
<tr>
<td><b>New Goal:</b><input type="text" name="name1" id="name1"></td>
<td><b>Notes:</b><input type="text" name="data1" id="data1"></td>
<td>
<input type="submit" value="Save" onclick="SaveItem(1)">
</td>
</tr>
</table>
</div>
<div id="items_table1">
<h2>List of goals</h2>
<table id="list1" contenteditable> </table>
<p>
<label><input type="button" value="Clear" onclick="ClearAll(1)"></label>
</p>
</div>
</form>
</div>
</article>
</section>
javascript
function doShowAll(numOfWeek) {
if (CheckBrowser()) {
var key = "";
var list = "**<tr><th>Goal</th><th>Notes</th></tr>**\n";
var i = 0;
var goals = localStorage[numOfWeek] ? JSON.parse(localStorage[numOfWeek]) : {};
var goalsKeys = Object.keys(goals);
for (i = 0; i < goalsKeys.length; i++) {
key = goalsKeys[i];
list += "<tr><td>" + key + "</td>\n<td>"
+ goals[key] + "</td></tr>\n";
}
if (list == "<tr><th>Goal</th><th>Notes</th></tr>\n") {
list += "<tr><td><i>nothin' here</i></td>\n<td><i>nothin' here either</i></td></tr>\n";
}
document.getElementById('list'+numOfWeek).innerHTML = list;
} else {
alert('Cannot store list as your browser do not support local storage');
}
}
$(document).ready(function(e) {
$('#due-date').datepicker();
$('#add-todo').button({
icons: {
primary: "ui-icon-circle-plus"
}
}).click(function() {
$('#new-todo').dialog('open');
}); // end click
$('#new-todo').dialog({
modal: true,
autoOpen: false,
close: function() {
$('#new-todo input').val(''); /*clear fields*/
},
buttons : {
"Add task" : function() {
var taskName = $('#task').val();
var dueDate = $('#due-date').val();
var beginLi = '<li><span class="done">%</span><span class="delete">x</span>';
var taskLi = '<span class="task">' + taskName + '</span>';
var dateLi = '<span class="due-date">' + dueDate + '</span>';
var endLi = '</li>';
$('#todo-list').prepend(beginLi + taskLi + dateLi + endLi);
$('#todo-list').hide().slideDown(250).find('li:first')
.animate({
'background-color': '#ff99c2'
},250)
.animate({
'background-color': '#d9b3ff'
},250).animate; // end animate
$(this).dialog('close');
},
"Cancel" : function() {
$(this).dialog('close');
}
}
});
$('#todo-list').on('click','.done',function(e) {
var $taskItem = $(this).parent("li");
var $copy = $taskItem.clone();
$('#completed-list').prepend($copy);
$copy.hide().slideDown();
$taskItem.remove();
}
); // end on
$('#todo-list, #completed-list').on('click','.delete',function(e) {
$(this).parent("li").slideUp(250, function() {
$(this).remove();
}); // end slideup
}); // end on
$('#todo-list').sortable();
}); // end ready
http://jsbin.com/digefufeca/edit?html,css,js,console,output
The problem
The form with nane goalsList1 is sending whenever you click on the button.
Why? because the button is submit button.
The solution(s)
Replace the button's type to button. (link)
Prevent the form submission by event.preventDefault(). (link)
There are more ways but those are the major.
Note: your code still not working but now you can see the error message.

Validation in Jquery ajax form submission

I am trying to validate user to enter a unique mobile number and email id.
It is checking and showing result mobile/email exist or not but if it exists still the form is submitting. Since I am new to jQuery validation I am not able to figure out how I should do it correctly nor can I find a perfect tutorial to do it in a right way.
Here is my code, I know lots of mistakes would be there and I apologize for those small mistakes.
On my form I have given On blur function to check mobile number and email
From these two functions I am checking in database if exist or not
function check_availability() {
//get the mobile number
var main = $('#main').val();
//use ajax to run the check
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
}
});
}
function email_availability() {
//get the email
var main = $('#email_tuitor').val();
//$email = urldecode("[email]")
//use ajax to run the check
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
}
});
}
This is the jquery ajax form submission is it possible to do every validation on blur ?
$(document).ready(function() {
$('.error').hide();
$("#next_tutor").click(function() {
$('.error').hide();
var main = $("#main").val();
if (main == "") {
$("label#main_error").show();
$("input#main").focus();
return false;
}
var name = $("#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email_tuitor = $("#email_tuitor").val();
if (email_tuitor == "") {
$("label#email_tuitor_error").show();
$("input#email_tuitor").focus();
return false;
}
var password_tuitor = $("#password_tuitor").val();
if (password_tuitor == "") {
$("label#password_tuitor_error").show();
$("input#password_tuitor").focus();
return false;
}
var tutor = $("#tutor").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'main=' + main + '&name=' + name + '&email_tuitor=' + email_tuitor + '&password_tuitor=' + password_tuitor + '&tutor=' + tutor;
// AJAX Code To Submit Form.
//alert(dataString);
//die;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tutor/tutor_sub_ses",
data: dataString,
cache: false,
success: function(result) {
//alert(result);
$("#abc").hide();
$("#tutorreg2").slideToggle("slow").show();
}
});
return false;
});
});
<form class="form-horizontal" action="#">
<div class="form-group">
<div class="col-sm-8 text-center">
<h2 class="text-warning">Tutor Registration</h2>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" value="tutor" style="display:none" id="tutor">
<input type="text" class="form-control" id="name" placeholder="Name">
<label id="name_error" class="error" for="name"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control phone" id="main" placeholder="Mobile Number *This will be the key to your account*" onBlur="check_availability()">
<span id="mobile_availability_result"></span>
<label id="main_error" class="error" for="main"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control" id="email_tuitor" placeholder="Email" onBlur="email_availability()">
<span id="email_availability_result"></span>
<label id="email_tuitor_error" class="error" for="email_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="password" class="form-control" id="password_tuitor" placeholder="Password">
<label id="password_tuitor_error" class="error" for="password_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 text-right">
<button type="submit" class="btn btn-warning" id="next_tutor">Next</button>
</div>
</div>
</form>
The quick way will be to use a global switch to enable sending the form. I would to it this way:
Create global variables with default values
var mobileApproved = false, emailApproved = false;
Check status and prevent sending if value is false in click handler
$(document).ready(function() {
...
$("#next_tutor").click(function() {
if (!mobileApproved || !emailApproved) {
return false;
}
...
})
...
})
In your check functions manage approved status after each ajax response
...
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
mobileApproved = true;
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
mobileApproved = false;
}
});
...
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
emailApproved = true;
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
emailApproved = false;
}
});
In order to stop the form from submission. You can keep a flag lets say formvalid.
Keep formValid as false initially. Based on your blur function, make it true if email and mobile are available else keep it false. In your form submission, put an if condition to check , if formvalid is true or not. If true then process with form submission else stop and throw error.

Categories