I have added Address,city and locality using jQuery in a dynamic added div element where the binding event is not working as expected:
I have below jQuery code:
<script type="text/javascript">
$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
if (counter > 19) {
alert("Only 20 Address allowed");
return false;
}
e.preventDefault();
var elems = '<div class="col-lg-5" id="Address' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group" id="city' + counter + '">' +
'<select name="city_name[]" id="city_name' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" id="removeButton' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';
//('#addressDiv').append(elems);
$('#addressDiv').append(elems);
$.ajax({
type: "Post",
url: "city_load.php",
success: function (html) {
$('#city_name' + counter).html(html);
}
});
$(document).on('change', '#city_name' + counter, function (ev) {
ev.preventDefault();
$city_id = $(this).val();
$.ajax({
type: "Post",
url: "ajax-dd3ck.php",
data: "city_id=" + $city_id,
cache: "false",
success: function (html) {
$('#locality_name' + counter).html(html);
}
});
});
//counter++;
return false;
});
$(document).on('click', '.removebtn', function () {
if (counter == 0)
{
alert("No more textbox to remove");
return false;
}
counter--;
$("#Address" + counter).remove();
$("#removeButton" + counter).remove();
});
});
</script>
My PHP Code for adding city in dropdown
city_load.php:
<?php
include("db.php");
$sql = "select * from city";
echo "<select name='city_name[]' id='city' class='city1'><option value='' selected ='selected'>Select City</option>";
$res = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($res)) {
echo "<option value='$row[city_id]'>$row[city_name]</option>";
}
echo "</select>";
?>
locality_load.php
<?php
include("db.php");
$city_id = $_POST['city_id'];
$sql = "select locality_id,locality_name,city_id from locality where city_id=$city_id";
$res = mysqli_query($con, $sql);
$result = mysqli_query($con, $sql) or die("query error");
while ($rows = mysqli_fetch_array($result)) {
$locality_id = $rows['locality_id'];
$locality_name = $rows['locality_name'];
echo "<option value=" . $locality_id . ">" . $locality_name . "</option>";
//echo '<option value="'.$locality_id.'">'.$locality_name.'</option>';
}
?>
The issue I am getting is that the first dynamic div is getting added and data is loading properly but for 2nd dynamic div it is not working.
Please have a look on screenshot:
save the counter value as a data-attr
eg
var elems = '<div class="col-lg-5 Address" data-id="' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group city" data-id="' + counter + '">' +
'<select name="city_name[]" data-id="' + counter + '" class="form-control city_name"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" data-id="' + counter + '" class="form-control locality_name"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" data-id="' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';
use a class for each element , bind events on class .
like
$(document).on('change','.city_name', function (ev) {
counter_id = $(this).attr('data-id');
}
so you will get the counter value and hope it will work for every div you created. (code not tested )
$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
if (counter > 19) {
alert("Only 20 Address allowed");
return false;
}
e.preventDefault();
var $elems = $('<div class="col-lg-5" id="Address' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group" id="city' + counter + '">' +
'<select name="city_name[]" id="city_name' + counter + '" data-index="' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" id="removeButton' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>');
//('#addressDiv').append(elems);
$('#addressDiv').append($elems);
$.ajax({
type: "Post",
url: "city_load.php",
success: function (html) {
$elelms.find('select').html(html);
}
});
counter++;
return false;
});
$(document).on('change', 'select', function (ev) {
var cc = $(this).attr('data-index');
ev.preventDefault();
$city_id = $(this).val();
$.ajax({
type: "Post",
url: "ajax-dd3ck.php",
data: "city_id=" + $city_id,
cache: "false",
success: function (html) {
$('#locality_name' + cc).html(html);
}
});
});
$(document).on('click', '.removebtn', function () {
if (counter == 0)
{
alert("No more textbox to remove");
return false;
}
counter--;
$("#Address" + counter).remove();
$("#removeButton" + counter).remove();
});
});
There are maybe some problem!
Related
I have a select list and I want to set the selected option based on the value from ajax call, but the select list is not appearing, but everything else will be rendered to the view. The problem is with my if-else statement. Is there a way I can set the selected option based on ajax value without if-else
here is my javascript function:
function FillUserTable() {
$.ajax({
url: "/Home/GetAllUsers",
type: 'GET',
dataType: "json",
traditional: true,
success: function (data) {
$("#EditUserDiv").css("display", "block");
$("#MainPage").css("display", "none");
$("#AllUsersTable2").dataTable().fnDestroy();
$('#AllUsersTable2').DataTable({
paging: true,
processing: true, // control the processing indicator.
retrieve: true,
LengthMenu: false,
responsive: true,
aaData: data,
columns: [
{ "data": "NationalID" ,"title": "هوية المستخدم" },
{ "data": "username", "title": "اسم المستخدم" },
{ "data": "FullName", "title": "الاسم" },
{ "data": "MobileNumber","title": "رقم الهاتف" },
{ "data": "Email","title": "البريد الالكتروني" },
{ "data": "RoleName", "title": "صلاحية المستخدم" },
{ "data": "IsActiveText", "title": "حالة المستخدم" },
{
data: null,
render: function (data, type, row) {
console.log(data.IsActive);
var htmlData= '<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#a'+data.NationalID+'">عرض</button>'+
'<div class="modal fade" id="a'+data.NationalID+'" tabindex = "-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">'+
'<div class="modal-dialog modal-lg" role="document">'+
'<div class="modal-content">'+
'<div class="modal-header">'+
'<h1 class="modal-title" id="test2" style="text-align: right;"> بيانات المستخدم</h1>'+
'<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'</div>' +
'<div class="modal-body">' +
'<form action="" method="post">'+
'<div class="row">' +
'<div class="col-md-6">' +
'<div class="form-group">' +
'<label for="Email" class="control-label">البريد الإلكتروني</label>' +
'<input type="text" id="Email' + data.NationalID + '" name="Email" value="' + data.Email + '" class="control-label"><br />' +
'<label id="lblError'+data.NationalID+'" style="color:red;margin-right: -250px"></label>' +
'</div >' +
'</div >'
if (data.IsActive == 1) {
htmlData = htmlData + '<div class="col-md-6">'
'<div class="form-group">' +
'<label for="IsActive" class="control-label">حالة المستخدم</label>' +
'<select name="IsActive" id="IsActive' + data.NationalID + '">' +
'<option value="2">...</option>' +
'<option selected value="1">نشط</option>' +
'<option value="0">غير نشط</option>' +
'</select>' +
'</div >' +
'</div >'
} else if (data.IsActive == 0) {
htmlData = htmlData + '<div class="col-md-6">'
'<div class="form-group">' +
'<label for="IsActive" class="control-label">حالة المستخدم</label>' +
'<select name="IsActive" id="IsActive' + data.NationalID + '">' +
'<option value="2">...</option>' +
'<option value="1">نشط</option>' +
'<option selected value="0">غير نشط</option>' +
'</select>' +
'</div >' +
'</div >'
}
else {
htmlData = htmlData + '<div class="col-md-6">'
'<div class="form-group">' +
'<label for="IsActive" class="control-label">حالة المستخدم</label>' +
'<select name="IsActive" id="IsActive' + data.NationalID + '">' +
'<option value="2">...</option>' +
'<option value="1">نشط</option>' +
'<option selected value="0">غير نشط</option>' +
'</select>' +
'</div >' +
'</div >'
}
htmlData = htmlData + ' </div > ' +
'<div class="row">' +
'<div class="col-md-6">' +
'<div class="form-group">' +
'<label for="RoleId" class="control-label">صلاحية المستخدم</label>' +
'<select name="RoleId" id="RoleId' + data.NationalID + '">' +
'<option value="0">...</option>' +
'<option value="1">رئيس جهة</option>' +
'<option value="2"> ممثل لجنة</option>' +
'<option value="3">رئيس أو موظف لجنة</option>' +
'<option value="4"> عضو لجنة</option>' +
'</select>' +
'</div >' +
'</div >' +
' </div > ' +
'</form >'+
'</div > ' +
'<div class="modal-footer">'+
'<button id="close' + data.NationalID + '" type="button" class="btn btn-secondary" data-dismiss="modal">إغلاق</button>'+
'<button type="button" onclick="UpdateUserBtn(' + data.NationalID + ')" class="btn btn-primary">تعديل المستخدم </button>'+
'</div>'+
'</div>'+
'</div>'+
'</div >'
return htmlData;
}
},
],
});
},
error: function (xhr, status, thrownError) {
e.preventDefault();
$.notify(
"حدث خطأ أثناء تحميل البيانات, الرجاء المحاولة مرة أخرى",
{
globalPosition: 'top center',
className: 'error'
}
);
}
});
}
when I use console.log(data.IsActive); the values will be correct it is 0 or 1
in your if, else if and else blocks for showing this select, each line like this:
htmlData = htmlData + '<div class="col-md-6">'
you miss a + operator at the end of it! so it's not adding the rest of your html code to the htmlData, just add these +s and it will work fine ...
However, I'd like to recommend you to re-restructure your code and have more small composed pieces instead of doing all of this in one place, also, when you create large strings on multiple lines, consider using (`) backticks instead of (' or ") quotations, it will enable you to get rid of all these +s
I want to SUM the price of all dynamically created rows and display into total input field..I have tried some things but not working for me.I have posted my script and image that explains how it should works. Everything is working and saving in database just want total amount of all items. Please see image for clear concept. Total of 1st row is saving in total but not working for dynamically created rows.
Image:
It should work like this
Html:
<div class="form-group">
<label>Total</label>
<input readonly type="text" id="total_amount" class="form-control"
name="total_amount">
</div>
Script:
<script>
var counterr = 1;
$(document).ready(function () {
$('#unit_price,#item_quantity').change(function () {
// alert();
var unitPrice = $('#unit_price').val();
// console.log(unitPrice);
var quantity = $('#item_quantity').val();
// console.log(quantity);
var total = (unitPrice * quantity).toFixed(0);
$('#total_price').val(total);
$('#total_amount').val(total);
});
// Input Fields
var maxField = 100; //Input fields increment limitation
var addButton = $('#add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
$(addButton).click(function (e) {
e.preventDefault();
counterr++;
//Check maximum number of input fields
if (counterr < maxField) {
fieldHTML = makeNewRow(counterr);
$(wrapper).append(fieldHTML); //Add field html
// $('#department-'+counterr).select2();
// console.log("Unit price", counterr);
$('.unit_price' + counterr).change(function () {
// console.log("hello");
var unitPrice = $('.unit_price' + counterr).val();
// console.log(unitPrice);
var quantity = $('#item_quantity' + counterr).val();
// console.log(quantity);
var total = (unitPrice * quantity).toFixed(0);
$('#total_price' + counterr).val(total);
$('#total_price').each(function() {
subtotal += parseFloat($(this).val());
console.log('test',subtotal);
});
$('#total_amount').val(subtotal);
});
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('#newrow').remove(); //Remove field html
counterr = counterr--; //Decrement field counter
})
});
function makeNewRow(counterr) {
return '<div class="row" id="newrow">' +
'<div class="col-md-4">' +
'<div class="form-group">' +
'<select onChange="getPurchasePrice(this.value);" style="background-color: #f5f6f9" id="item_name' + counterr + '" class="form-control dep"' +
'placeholder="Enter Item" name="testing[]"' + '>' +
'<option value = "">Select Item</option>' + '>' +
'#foreach($items as $item)' + '>' +
'<option value = "{{$item->id}}">{{$item->item_name}}</option>' + '>' +
'#endforeach' + '>' +
'</select>' +
'</div>' +
'</div>' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<input style="background-color: #f5f6f9" type="number" id="item_quantity' + counterr + '" class="form-control"' +
'placeholder="Enter.." name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<input style="background-color: #f5f6f9" type="number" id="unit_price' + counterr + '" class="unit_price' + counterr + ' form-control"' +
'placeholder="Enter.." name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<div class="col-md-3">' +
'<div class="form-group">' +
'<input value="0" style="background-color: #f5f6f9" disabled type="text" id="total_price' + counterr + '" class="form-control"' +
'placeholder="Total" name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<a style="height:40px;margin-left:25px" href="javascript:void(0);" class="btn btn-danger remove_button">X</a>' +
'</div>'; //New input field html
}
/*function removeDiv(no){
$("#testingrow-"+no).remove();
x--;
}*/
</script>
Add a function to recalculate the grand total 'recalcGrandTotal'
var recalcGrandTotal = function() {
var grandTotal = 0; // Declare a var to hold the grand total
$("[id^=total_price]").each(function() { // Find all elements with an id that starts with 'total_price'
grandTotal += parseInt($(this).val()); // Add the value of the 'total_price*' field to the grand total
})
$('#total_amount').val(grandTotal); // append grand total amount to the total field
}
Then, hook this function up to the 'total price' recalculation function:
Find
$('#total_price' + counterr).val(total);
Add after:
recalcGrandTotal();
To substract from grand total upon removal of an item, hook this function up to the item removal function. Find:
counterr = counterr--; //Decrement field counter
Add after:
recalcGrandTotal();
after a long search i can't find a way to call an autocomplete function when the document is ready passing a specific variable.
So i got this function that works fine when i select element from autocomplete:
var option_row = <?php echo $option_row; ?>;
$('input[name=\'option\']').autocomplete({
'source': function(request, response) {
$.ajax({
url: 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(request),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
category: item['category'],
label: item['name'],
value: item['option_id'],
type: item['type'],
option_value: item['option_value']
}
}));
}
});
},
'select': function(item) {
html = '<div class="tab-pane" id="tab-option' + option_row + '">';
html += ' <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';
etc etc......
after many research i'm thinking to switch to another possible solution...
I wish to call this directly without select item but passing a variable to the function...
i'm trying doing this:
$(document).ready(function(e){
var option_row = <?php echo $option_row; ?>;
var req = 'item';
setOptions(req);
});
function setOptions(req){
$.ajax({
url: 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(req),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
category: item['category'],
label: item['name'],
value: item['option_id'],
type: item['type'],
option_value: item['option_value']
}
}));
}
});
'select': function(item) {
html = '<div class="tab-pane" id="tab-option' + option_row + '">';
html += ' <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';
etc, etc...
}
Now, i don't know what i should use instead of 'select': function(item) { to make it works.
Thanks in advance, any help is appreciated.
Well, i have finally make it... it was more simple than i thought
this is the code:
$(document).ready(function(e) {
var data = 'Adulti';
addOptions(data);
});
var option_row = <?php echo $option_row; ?>;
function addOptions(data){
var base_url = 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(data);
var n='';
$.ajax({
url: base_url,
dataType: 'json',
success: function(json) {
$.map(json, function(item) {
category = item['category'];
label = item['name'];
value = item['option_id'];
type = item['type'];
option_value = item['option_value'];
html = '<div class="tab-pane" id="tab-option' + option_row + '">';
html += ' <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['name'] + '" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][option_id]" value="' + item['value'] + '" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][type]" value="' + item['type'] + '" />';
etc, etc....
I use below code for dynamic textbox. When I will change ID=iuname1 it has to show result in FffinalResult1. Then when I will change ID=iuname2 it has to show result in FffinalResult2. but it don't.
<script type="text/javascript">
var counter = 0;
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
});
function GetDynamicTextBox() {
counter++;
return 'Item Code : <select name="iuname" id="iuname" rel="' + counter + '" class="iuname" >'+
<?php foreach($tItem as $row) : ?>
'<option value="<?php echo $row->ProductID;?>"><?php echo $row->ProductID;?></option>'+
<?php endforeach;?>
'</select>'+
' Batch : <input id="buname" name="buname" rel="' + counter + '" class="buname">'+
</div>');
'<div rel="' + counter + '" class="FffinalResult" id=FFinalResult" ></div>'+
'<br/>'
}
</script>
And document on change function is below.
<script>
$(document).on('change', $(".iuname[rel='"+ counter + "']"), function(){
var val = $(this).val();
var text = $(this).find('option:selected').text();
$(".FFffinalResultt[rel='"+ counter + "']").text(val);
});
</script>
How it will works?
Your code will always give values for last inserted elements as counter will be increasing each time you add elements! So I would suggest to use class here instead of id!
var counter = 0;// You can keep this to generate unique `id` but bind events to class
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
});
function GetDynamicTextBox() {
counter++;
return
'Item Code : <select name="iuname" id="iuname_'+counter+'" rel="' + counter + '" class="iuname" >'+
<?php foreach($tItem as $row) : ?>
'<option value="<?php echo $row->ProductID;?>"><?php echo $row->ProductID;?></option>'+
<?php endforeach;?>
' </select>'+
' Batch : <input id="buname_'+counter+'" name="buname" rel="' + counter + '" class="buname">'+
'<div rel="' + counter + '" class="FffinalResult" id="FFinalResult_'+counter+'" ></div>'+
'<br/>';
}
And event binding to class
$(document).on('change', ".iuname", function(){
var val = $(this).val();
var text = $(this).find('option:selected').text();
$(this).siblings(".FffinalResultt").text(val); //get its sibling element
});
how to check multiple field using ajax & mysql
for example, I Want to check or validate if an email exist in my database
my code is
jquery_append.js
$(document).ready(function() {
var count = 0;
$("#add_btn").click(function(){
count += 1;
$('#container').append(
'<div class="s"><tr class="records">'
+ '<td ><div id="'+count+'">No : ' + count + '</div></td></tr>'
+ '<tr class="records"><td><label>Email</label><input id="email_' + count + '" name="email_' + count + '" type="text" class="email" required><label>Nama Depan</label><input id="nama_depan_' + count + '" name="nama_depan_' + count + '" type="text"><label>Nama Belakang</label><input id="nama_belakang_' + count + '" name="nama_belakang_' + count + '" type="text"></td></tr>'
+ '<tr class="records"><td><label>Tipe Operasi</label><select name="tipe_operasi_' + count + '"><option value="0">-Pilih-</option></select></td><tr>'
+ '<tr class="records"><td><label>Lokasi</label><select name="lokasi_' + count + '"><option value="0">-Pilih-</option></select></td><tr>'
+ '<tr class="records"><td><label>Alamat</label><input id="alamat_' + count + '" name="alamat_' + count + '" type="text"></td><tr>'
+ '<br><tr class="records"><td><a class="remove_item" href="#" >Delete</a>'
+ '<input id="rows_' + count + '" name="rows[]" value="'+ count +'" type="hidden"></td></tr><tr><td><hr></td></tr></div>'
);
});
$(".remove_item").live('click', function (ev) {
if (ev.type == 'click') {
$(this).parents(".s").fadeOut();
$(this).parents(".s").remove();
}
});
});
Write a function and trigger it on blur of your email field. Pass your email as a parameter of your function and check it into your database.
This is your email field:
<input type="text" class="form-control" name="email" id="email" value="" />
This is your JavaScript code:
$(document).ready(function() {
$("#email").blur(function(){
var email = $("#email").val();
if(email != ""){
$.ajax({
url: 'ajax_function_url',
data: {email:email},
type: 'post',
complete: function(output) {
var isExist = output.responseText;
if(isExist === '1'){
alert('This email is already in use.');
}else{
alert('success!!');
}
}
});
}else{
alert('Email should not be empty');
}
});
}
This is your PHP function which is called by Ajax:
function CheckEmailExist() {
$conn = new mysqli($servername, $username, $password, $dbname);
if (isset($_POST['email']) && $_POST['email'] != "") {
$sql = "SELECT id FROM `table` WHERE `email` = '" . $_POST['email'] . "'";
$result = $conn->query($sql);
echo mysql_num_rows($result);
}
exit();
}
This way you can check if your data exists in your database or not via ajax.