How to addClass if autocomplete input is empty? - javascript

I would like to know how to add a class if autocomplete input is empty? There's a function which autocompletes the address when putting the post code. If for example address_1 is empty, it adds the class form-control, else it adds the class sem-bordas.
I tried:
$('#input-address-1').on('change', function() {
if ($(this).val() == '') {
$(this).next().removeClass("form-control");
} else {
$(this).next().addClass("sem-bordas");
}
});
But without success.
Thats all the function
$(function(){
$('input[name="postcode"]').blur(function(){
var cep = $.trim($('input[name="postcode"]').val().replace('-', ''));
//$.getScript ("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+cep, function(){
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados){
if(!("erro" in dados)){
$('input[name="address_1"]').val(dados.logradouro);
$('input[name="address_1"]').parent().parent().fadeIn('slow');
$('input[name="address_2"]').val(dados.bairro);
$('input[name="address_2"]').parent().parent().fadeIn('slow');
$('input[name="city"]').val(unescape(dados.localidade));
$('input[name="city"]').parent().parent().fadeIn('slow');
$('select[name="zone_id"]').parent().parent().fadeIn('slow');
$('select[name="country_id"]').find('option[value="30"]').attr('selected', true);
$.post('index.php?route=account/register/estado_autocompletar&estado=' + unescape(dados.uf), function(zone_id){
$.ajax({
url: 'index.php?route=account/register/country&country_id=30',
dataType: 'json',
beforeSend: function() {
$('select[name=\'country_id\']').after(' <i class="fa fa-circle-o-notch fa-spin"></i>');
},
complete: function() {
$('.fa-spin').remove();
},
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
var html = '<option value=""><?php echo $text_select; ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['zone_id'] + '"';
if (json['zone'][i]['zone_id'] == zone_id) {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'zone_id\']').html(html);
}
});
});
}
});
});
});

$(document).on('input','#input-address-1', function() {
if ($(this).val() == '') {
$(this).next().addClass("sem-bordas");
} else {
$(this).next().removeClass("sem-bordas");
}
});

Let me explain, thats all my function to verify if the address exist or not
$(function(){
$('input[name="postcode"]').blur(function(){
var cep = $.trim($('input[name="postcode"]').val().replace('-', ''));
//$.getScript ("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+cep, function(){
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados){
if(!("erro" in dados)){
$('input[name="address_1"]').val(dados.logradouro);
$('input[name="address_1"]').parent().parent().fadeIn('slow');
$('input[name="address_2"]').val(dados.bairro);
$('input[name="address_2"]').parent().parent().fadeIn('slow');
$('input[name="city"]').val(unescape(dados.localidade));
$('input[name="city"]').parent().parent().fadeIn('slow');
$('select[name="zone_id"]').parent().parent().fadeIn('slow');
$('select[name="country_id"]').find('option[value="30"]').attr('selected', true);
$.post('index.php?route=account/register/estado_autocompletar&estado=' + unescape(dados.uf), function(zone_id){
$.ajax({
url: 'index.php?route=account/register/country&country_id=30',
dataType: 'json',
beforeSend: function() {
$('select[name=\'country_id\']').after(' <i class="fa fa-circle-o-notch fa-spin"></i>');
},
complete: function() {
$('.fa-spin').remove();
},
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
var html = '<option value=""><?php echo $text_select; ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['zone_id'] + '"';
if (json['zone'][i]['zone_id'] == zone_id) {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'zone_id\']').html(html);
}
});
});
}
});
});
});
Soon after putting the postcode and an address was not found, I would like to add a class to the fields that were not filled. The goal is to highlight fields that have not been filled

I found the solution
After
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
Put this code
if($.trim($('#input-address-1').val()) == ''){
$('#input-address-1').addClass('form-control');
}else {
$('#input-address-1').removeClass('form-control');
$('#input-address-1').addClass('sem-bordas');
}
Thanks everyone for helping. I think thats the solution

Related

i want to make the price table appear after check id ( success ) I try but always error

I've tried merging or changing using if else , but always getting a result error
html code
<div class="container">
<h1 class="ps-3">Beli</h1>
<!-- form -->
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">ID Character</label>
<input name="nomor" placeholder="1234567" type="text" class="form-control" id="id_character" aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">ID Zone</label>
<input name="id_zone" placeholder="1234" type="text" class="form-control" id="id_zone">
</div>
<button id="button_beli" class="button_beli btn btn-primary" type="button">
<span id="button_beli_loading" class="d-none spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Beli Sekarang
</button>
</div>
if you use this javascript then just check the id
$(document).ready(function() {
$(".button_beli").click( function() {
$("#button_beli_loading").removeClass('d-none');
var id_character = $("#nomor").val();
var id_zone = $("#id_zone").val();
if (id_character.length == "") {
$("#button_beli_loading").addClass('d-none');
Swal.fire({
type: 'warning',
title: 'Oops...',
text: 'Character ID Wajib Diisi !'
});
}else{
//ajax
$.ajax({
url: "api.php",
type: "POST",
dataType: 'JSON',
data: {
"id": id_character,
"server": id_zone
},
success:function(response){
$("#button_beli_loading").addClass('d-none');
//
var response_status = response.status;
var nama = response.nama;
var id = response.id;
var zone = response.zone;
var output = nama + "\n" + id;
//
if (response.status == "ok"){
Swal.fire({
type: 'success',
text: output
});
$("#id_character").val('');
$("#id_zone").val('');
}else if(response.status == "error_1"){
Swal.fire({a
type: 'error',
text: 'ID tidak ditemukan, coba lagi!'
});
}else{
Swal.fire({
type: 'error',
text: 'Error, coba lagi!'
});
}
console.log(response);
},
error:function(response){
$("#button_beli_loading").addClass('d-none');
Swal.fire({
type: 'error',
text: 'server error!'
});
}
})
}
});
i want to combine with javascript which shows the price table after filling the number with check id
how to do so that after checking the response id is successful, the price list appears?
$(document).ready(function() {
$('#tabl').hide();
// $('#nomor').attr('disabled','disabled');
$('.exs').hide();
// $("#tipe").change(function() {
// $('#nomor').val('');
// var tipe = $("#tipe").val();
// if($(this).val() != 0){
// // $('#nomor').removeAttr('disabled');
// }
// // $.ajax({
// // url: '<?php echo $config['web']['url']; ?>ajax/type-top-up.php',
// // data: 'tipe=' + tipe,
// // type: 'POST',
// // dataType: 'html',
// // success: function(msg) {
// // $("#operator").html(msg);
// // }
// // });
// });
// $("#operator").change(function() {
// var tipe = $("#tipe").val();
// var operator = $("#operator").val();
// $.ajax({
// url: '<?php echo $config['web']['url']; ?>ajax/service-top-up.php',
// data : 'tipe=' +tipe + '&operator=' + operator,
// type: 'POST',
// dataType: 'html',
// success: function(msg) {
// $("#layanan").html(msg);
// }
// });
// });
$('.exs').click(function() {
$('.exs').hide();
$('#panel_list').removeClass('isi_p');
$('#ajx').hide();
$('#rep').show();
});
$('#nomor').on('keyup change input', function(e) {
var char = $(this).val().length;
if (char == 0) {
$('#tabl').hide();
normal();
} else {
$('#panel_list').addClass('isi_p');
$('#ajx').show();
$('#tls').hide();
$('#tabl').show();
}
if ($('#tipe').val() != '') {
$('.type_l').html("");
var nmr = $(this).val().split("");
if (nmr[0] == '+') {
nomor($(this).val(), 6);
} else if (nmr[0] == '1') {
nomor($(this).val(), 5);
} else if (nmr[0] == '2') {
nomor($(this).val(), 5);
}else if (nmr[0] == '3') {
nomor($(this).val(), 5);
}else if (nmr[0] == '4') {
nomor($(this).val(), 5);
}else if (nmr[0] == '5') {
nomor($(this).val(), 5);
}else if (nmr[0] == '6') {
nomor($(this).val(), 5);
}else if (nmr[0] == '7') {
nomor($(this).val(), 5);
}else if (nmr[0] == '8') {
nomor($(this).val(), 5);
}else if (nmr[0] == '9') {
nomor($(this).val(), 5);
}else if (nmr[0] == '0') {
nomor($(this).val(), 5);
}else {
}
} else {
if (empty(char)) {
$('.type_l').html("")
} else {
$('.type_l').html("<p style='color:red;'>pilih tipe Layanan</>")
}
}
});
$('#nomor').click(function() {
$('.exs').show();
$('#panel_list').addClass('isi_p');
$('#ajx').show();
$('#rep').hide();
});
normal();
function normal() {
$('.exs').hide();
$('#panel_list').removeClass('isi_p');
$('#ajx').hide();
$('#tls').show();
}
function nomor(nomor, lengths) {
var tipe = $('#tipe').val();
var swit = 'reqnmr';
var nomor = nomor;
$.ajax({
type: "POST",
url: "<?php echo $config['web']['url']; ?>ajax/request-Operator.php",
data: {
nomor: nomor,
tipe: tipe,
swit: swit
},
success: function(response) {
var res = $.parseJSON(response);
var data = '';
var no = 1;
for (var i = 0; i < res.length; i++) {
// var la = ((res[i]['layanan'].split(" ").length == 2)?res[i]['layanan'].split(" ")[1]:res[i]['layanan']);
var la = res[i]['layanan'];
data += '<div class="col-12 list_pls" style="cursor:pointer "'
data += 'data-layanan="' + la +
'"data-harga="' + res[i]['harga'] +
'"data-operator="' + res[i]['operator'] +
'"data-id="' + res[i]['id'] +
'"data-service_id="' + res[i]['service_id'] +
'"data-tipe="' + res[i]['tipe'] +
'"data-deskripsi="' + res[i]['deskripsi'] + '">'
data += '<div class="card mb-3 clasesItem" style="border:1px solid #ccc;" >'
data += '<div class="card-body " >'
data += '<h6 class="card-title m-0" >' + la + ' <span style="float: right; color: #fb4802;" >' + format(res[i]['harga']) + '</span></h6>'
data += '<p class="card-text" >' + res[i]['deskripsi'] + '</p>'
data += ' </div>'
data += '</div>'
data += '</div>'
}
$('#ajx').html(data);
$('.list_pls').click(function() {
$('#rep').show();
$('#layanan').val($(this).data('service_id'));
normal();
layanan($(this).data('service_id'));
$('#operator').val($(this).data('operator'));
//requstOp($(this).data('tipe'),$(this).data('operator'));
rep = '<div class="col-12 " style="cursor:pointer">'
rep += '<div class="card mb-3" style="border:1px solid #ccc; color: #fff; background-color: #039dfc;">'
rep += '<div class="card-body">'
rep += '<h6 class="card-title m-0" id="harga">' + $(this).data('layanan') + '<span style="float: right; color: #fb4802;">' + format(parseInt($(this).data('harga'))) + '</span></h6>'
rep += '<p class="card-text">' + $(this).data('deskripsi') + '</p>'
rep += ' </div>'
rep += '</div>'
rep += '</div>'
$('#rep').html(rep);
})
}
});
}
function layanan(layanan_) {
var tipe = $("#tipe").val();
var layanan = layanan_;
$.ajax({
url: '<?php echo $config['web']['url']; ?>ajax/rate-order-coins-top-up.php',
data: 'layanan=' + layanan,
type: 'POST',
dataType: 'html',
success: function(msg) {
$("#koin").html(msg);
//console.log(msg);
}
});
$.ajax({
url: '<?php echo $config['web']['url']; ?>ajax/price-top-up.php',
data: 'layanan=' + layanan,
type: 'POST',
dataType: 'html',
success: function(msg) {
$("#harga").val(msg);
}
});
}
function requstOp(tipe, kode) {
$.ajax({
url: '<?php echo $config['web']['url']; ?>ajax/request-Operator.php',
data: {
tipe: tipe,
kode: kode,
swit: 'reqOpr'
},
type: 'POST',
dataType: 'html',
success: function(msg) {
$('#operator').val(msg);
}
});
}
});
i tried to combine like this
$(document).ready(function() {
$('#tabl').hide();
// $('#nomor').attr('disabled','disabled');
$('.exs').hide();
// $("#tipe").change(function() {
// $('#nomor').val('');
// var tipe = $("#tipe").val();
// if($(this).val() != 0){
// // $('#nomor').removeAttr('disabled');
// }
// // $.ajax({
// // url: '<?php echo $config['web']['url']; ?>ajax/type-top-up.php',
// // data: 'tipe=' + tipe,
// // type: 'POST',
// // dataType: 'html',
// // success: function(msg) {
// // $("#operator").html(msg);
// // }
// // });
// });
// $("#operator").change(function() {
// var tipe = $("#tipe").val();
// var operator = $("#operator").val();
// $.ajax({
// url: '<?php echo $config['web']['url']; ?>ajax/service-top-up.php',
// data : 'tipe=' +tipe + '&operator=' + operator,
// type: 'POST',
// dataType: 'html',
// success: function(msg) {
// $("#layanan").html(msg);
// }
// });
// });
$('.exs').click(function() {
$('.exs').hide();
$('#panel_list').removeClass('isi_p');
$('#ajx').hide();
$('#rep').show();
});
$(".button_beli").click( function() {
var char = $("#nomor").val();
//ajax
$.ajax({
url: "api.php",
type: "POST",
dataType: 'JSON',
data: {
"id": id_character,
"server": id_zone
},
success:function(response){
$("#button_beli_loading").addClass('d-none');
//
var response_status = response.status;
var nama = response.nama;
var id = response.id;
var zone = response.zone;
var output = nama + "\n" + id;
//
if (response.status == "ok"){
Swal.fire({
type: 'success',
text: output
});
$("#id_character").val('');
$("#id_zone").val('');
}else if(response.status == "error_1"){
Swal.fire({a
type: 'error',
text: 'ID tidak ditemukan, coba lagi!'
});
}else{
Swal.fire({
type: 'error',
text: 'Error, coba lagi!'
});
}
console.log(response);
},
error:function(response){
$("#button_beli_loading").addClass('d-none');
Swal.fire({
type: 'error',
text: 'server error!'
});
if (char < 5) {
$('#ajx').hide();
$('#tls').show();
$('#tabl').hide();
normal();
Swal.fire({
type: 'warning',
title: 'Oops...',
text: 'Character ID Wajib Diisi !'
});
} else {
$('#panel_list').addClass('isi_p');
$('#ajx').show();
$('#tls').hide();
$('#tabl').show();
}
if ($('#tipe').val() != '') {
$('.type_l').html("");
var nmr = $("#nomor").val();
if (nmr[0] == '+') {
nomor($(this).val(), 6);
} else if (nmr[0] == '1') {
nomor($(this).val(), 5);
} else if (nmr[0] == '2') {
nomor($(this).val(), 5);
}else if (nmr[0] == '3') {
nomor($(this).val(), 5);
}else if (nmr[0] == '4') {
nomor($(this).val(), 5);
}else if (nmr[0] == '5') {
nomor($(this).val(), 5);
}else if (nmr[0] == '6') {
nomor($(this).val(), 5);
}else if (nmr[0] == '7') {
nomor($(this).val(), 5);
}else if (nmr[0] == '8') {
nomor($(this).val(), 5);
}else if (nmr[0] == '9') {
nomor($(this).val(), 5);
}else if (nmr[0] == '0') {
nomor($(this).val(), 5);
}else {
}
} else {
if (empty(char)) {
$('.type_l').html("")
} else {
$('.type_l').html("<p style='color:red;'>pilih tipe Layanan</>")
}
}
});
$(".button_beli").click( function() {
$('.exs').show();
$('#panel_list').addClass('isi_p');
$('#ajx').show();
$('#rep').hide();
});
normal();
function normal() {
$('.exs').hide();
$('#panel_list').removeClass('isi_p');
$('#ajx').hide();
$('#tls').show();
}
function nomor(nomor, lengths) {
var tipe = $('#tipe').val();
var swit = 'reqnmr';
var nomor = $('#nomor').val();;
$.ajax({
type: "POST",
url: "<?php echo $config['web']['url']; ?>ajax/request-Operator.php",
data: {
nomor: nomor,
tipe: tipe,
swit: swit
},
success: function(response) {
var res = $.parseJSON(response);
var data = '';
var no = 1;
for (var i = 0; i < res.length; i++) {
// var la = ((res[i]['layanan'].split(" ").length == 2)?res[i]['layanan'].split(" ")[1]:res[i]['layanan']);
var la = res[i]['layanan'];
data += '<div class="col-12 list_pls" style="cursor:pointer "'
data += 'data-layanan="' + la +
'"data-harga="' + res[i]['harga'] +
'"data-operator="' + res[i]['operator'] +
'"data-id="' + res[i]['id'] +
'"data-service_id="' + res[i]['service_id'] +
'"data-tipe="' + res[i]['tipe'] +
'"data-deskripsi="' + res[i]['deskripsi'] + '">'
data += '<div class="card mb-3 clasesItem" style="border:1px solid #ccc;" >'
data += '<div class="card-body " >'
data += '<h6 class="card-title m-0" >' + la + ' <span style="float: right; color: #fb4802;" >' + format(res[i]['harga']) + '</span></h6>'
data += '<p class="card-text" >' + res[i]['deskripsi'] + '</p>'
data += ' </div>'
data += '</div>'
data += '</div>'
}
$('#ajx').html(data);
$('.list_pls').click(function() {
$('#rep').show();
$('#layanan').val($(this).data('service_id'));
normal();
layanan($(this).data('service_id'));
$('#operator').val($(this).data('operator'));
//requstOp($(this).data('tipe'),$(this).data('operator'));
rep = '<div class="col-12 " style="cursor:pointer">'
rep += '<div class="card mb-3" style="border:1px solid #ccc; color: #fff; background-color: #039dfc;">'
rep += '<div class="card-body">'
rep += '<h6 class="card-title m-0" id="harga">' + $(this).data('layanan') + '<span style="float: right; color: #fb4802;">' + format(parseInt($(this).data('harga'))) + '</span></h6>'
rep += '<p class="card-text">' + $(this).data('deskripsi') + '</p>'
rep += ' </div>'
rep += '</div>'
rep += '</div>'
$('#rep').html(rep);
})
}
});
}
function layanan(layanan_) {
var tipe = $("#tipe").val();
var layanan = layanan_;
$.ajax({
url: '<?php echo $config['web']['url']; ?>ajax/rate-order-coins-top-up.php',
data: 'layanan=' + layanan,
type: 'POST',
dataType: 'html',
success: function(msg) {
$("#koin").html(msg);
//console.log(msg);
}
});
$.ajax({
url: '<?php echo $config['web']['url']; ?>ajax/price-top-up.php',
data: 'layanan=' + layanan,
type: 'POST',
dataType: 'html',
success: function(msg) {
$("#harga").val(msg);
}
});
}
function requstOp(tipe, kode) {
$.ajax({
url: '<?php echo $config['web']['url']; ?>ajax/request-Operator.php',
data: {
tipe: tipe,
kode: kode,
swit: 'reqOpr'
},
type: 'POST',
dataType: 'html',
success: function(msg) {
$('#operator').val(msg);
}
});
}
});
I've tried to combine but always error is there any solution?
enter image description here

dynamic select option and dynamic data from php

I tried develop add several selectbox dynamically and get data from selectbox my codes:
this codes add new selectbox and work
var y = 1;
var z = 1;
$('#add_kind').on('click', function () {
var html = '';
html += '<div class="prInput-row">';
html += '<select name="kind_id" class="halfselect kinds">';
html += '<option value="0">Kinds</option>';
html += '<?php foreach($kinds as $kind): ?>';
html += '<option value="<?php echo $kind->id;?>"><?php echo $kind->name;?></option>';
html += '<?php endforeach; ?>';
html += '</select>';
html += '<select name="kind_desc_id" class="halfselect kind_descriptions">';
html += '<option value="0">Kind Descriptions/option>';
html += '</select>';
html += '<input type="text" name="stock_piece" class="halfselect" placeholder="Stock Piece"/>';
html += '</div>';
$('#kind_area').append(html);
$('.kinds').each(function () {
$(this).attr('class', 'halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class', 'halfselect kind_descriptions_'+z);
z++;
});
});
$('.kinds').each(function () {
$(this).attr('class','halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class','halfselect kind_descriptions_'+z);
z++;
});
this codes get data from db and not work,
var i = 1;
$(".kinds_"+i).on('change', function() {
var kindID = $(this).val();
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
i++;
});
how can change those codes and how can get dynamically datas
this picture my example
#anon, I solved thank you so much but 2 times write codes but how can write one time ?
$("#add_kind").click(function(){
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
});
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
you can get all element that have class started with "kinds_" with selector $("[class^=kinds_]") then do a loop to get your class index. So maybe something like this will work:
$.each($("[class^='kinds_']"), function() {
var selector = "."+$(this).attr("class");
$(document).on('change', selector, function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
})

Text message won't clear even after sending the text in chat

I'm working on a chat box and it's working fine but when we enter the text message and sent it after the message is sent it won't clear automatically. It will remain there even after posting the text, we need to clear it manually.
I have tried to change some code but couldn't solve the issue.
Code which I'm using in this.
<div class="row">
<div class="pull-left">
<h3><?php echo sprintf($this->lang->line("conv_with"), $user["username"]); ?></h3>
</div>
</div>
<div class="row">
<div class="main_container clearfix">
<div class="ibox-content-no-bg">
<div class="chat-discussion">
<?php
$last_conv = $last_conv->result_array();
$last_conv = array_reverse($last_conv);
foreach($last_conv as $message):
$activity_thumb = $message["thumb_url"];
if($message["thumb_url"] == "" || $message["photostatus"] == 0) {
$activity_thumb = base_url() . "images/avatar.png";
}
?>
<?php
if($message["user_id"] == $this->session->userdata("user_id"))
$align_message = "left";
else
$align_message = "right";
?>
<div class="chat-message clearfix <?php echo $align_message; ?>" data-id="<?php echo $message["id"]; ?>">
<?php
if($message["gender"] == 0) {
$gender_user_color = "male_color";
} else {
$gender_user_color = "female_color";
}
?>
<a class="nailthumb-msg-container" href="<?php echo base_url("user/profile/".$message["user_id"]) ?>"><img width="62" alt="" src="<?php echo $activity_thumb; ?>" class="message-avatar"></a>
<div class="message">
<a class="message-author <?php echo $gender_user_color; ?>" href="<?php echo base_url("user/profile/".$message["user_id"]) ?>"><?php echo $message["username"] ?></a>
<span class="message-date text-muted pm-date" title="<?php echo $message["date"]; ?>Z"></span>
<span class="message-content">
<?php echo $message["content"]; ?>
</span>
<span class="message-date-mob text-muted pm-date" title="<?php echo $message["date"]; ?>Z"></span>
</div>
</div>
<?php
endforeach;
?>
</div>
<div class="chat-message-form">
<div class="form-group">
<p class="lead emoji-picker-container">
<textarea id="pm-write" class="form-control message-input pm-write-answer-textarea" placeholder="<?php echo $this->lang->line("enter_message_here_placeholder"); ?>" name="message" data-emojiable="true"></textarea>
</p>
</div>
<div class="btn-reply-placeholder">
<a class="btn btn-primary btn-send-reply" href="#" data-user-id="<?php echo $user["uid"]; ?>" data-conv-id="<?php echo $current_conv->id; ?>"><?php echo $this->lang->line("send_reply_btn"); ?></a>
</div>
</div>
</div>
</div>
</div>
AJAX
$(document).ready(function() {
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
$(".message").emoticonize();
$(".chat-discussion").scrollTop(100000);
window.setInterval(function(){
var last_message_id = $(".chat-message:last").attr("data-id");
// Live refresh
$.ajax({
url: base_url + "pm/refresh_conv",
type: 'POST',
data: {conv_id : conv_id, last_message_id: last_message_id},
success: function(data) {
$.each(data.last_messages, function(i, item) {
var message = item;
var avatar = "";
if(message.thumb_url == null || message.photostatus == 0) {
avatar = base_url + "images/avatar.png";
} else {
avatar = base_url + message.thumb_url;
}
if(message.gender == 0) {
var gender_user_color = "male_color";
} else {
var gender_user_color = "female_color";
}
if(message.user_id == user_id) {
var msg_dir = "left";
} else {
var msg_dir = "right";
}
var block_msg = '<div class="chat-message ' + msg_dir + '" data-id="' + message.mid + '">';
block_msg += '<a class="nailthumb-msg-container" href="' + base_url + 'user/profile/' + message.user_id + '"><img width="62" alt="" src="' + avatar + '" class="message-avatar" /></a>';
block_msg += '<div class="message">';
block_msg += '<a class="message-author ' + gender_user_color + '" href="' + base_url + 'user/profile/' + message.user_id + '">' + message.username + '</a>';
block_msg += '<span class="message-date text-muted pm-date" title="' + message.date + 'Z"></span>';
block_msg += '<span class="message-content">';
block_msg += message.content;
block_msg += '</span>';
block_msg += '</div>';
block_msg += '</div>';
$(".chat-message").last().after(block_msg);
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
$(".message").emoticonize();
$(".chat-discussion").scrollTop(100000);
});
}
});
}, 2000);
$(".btn-send-reply").click(function(e) {
e.preventDefault();
$(':input[name="pmwrite"]').val(null);
var conv_id = $(this).attr("data-conv-id");
var user_id = $(this).attr("data-user-id");
var content = $(".emoji-wysiwyg-editor").html();
$(this).html('<i class="fa fa-circle-o-notch fa-spin"></i>');
$(this).addClass("disabled");
var that = $(this);
$.ajax({
url: base_url + "pm/send_reply",
type: 'POST',
data: {conv_id : conv_id, content: content, user_id : user_id},
success: function(data) {
var res = data.result;
if(res == 999) {
alert(not_logged_in_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 998) {
alert(write_something_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 500) {
alert(cant_demo_mode_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 997) {
alert(conv_not_exist_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 996) {
alert(user_blocked_you_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else {
var avatar = "";
if(data.user.thumb_url == null || data.user.photostatus == 0) {
avatar = base_url + "images/avatar.png";
} else {
avatar = base_url + data.user.thumb_url;
}
$(".pm-write-answer-textarea").val("");
if(data.user["gender"] == 0) {
var gender_user_color = "male_color";
} else {
var gender_user_color = "female_color";
}
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
that.html(send_reply_str);
that.removeClass("disabled");
$(".chat-discussion").scrollTop(100000);
}
}
});
});
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
replaceString = replaceString.replace(find[i], replace[i]);
}
return replaceString;
};
});
I expect the textarea to be cleared after someone send t the message but actual is the text will remain in textarea even after the message is sent.
I assume that this $(".emoji-wysiwyg-editor") is your element for your content. since this is the one you called in
var content = $(".emoji-wysiwyg-editor").html();
Try clearing this element after success by using this code since you're using a jquery here.
$(".emoji-wysiwyg-editor").html('');
Just add this line at the start of your AJAX success() function
$('#pm-write').empty();
Using pure Javascript
document.getElementById('pm-write').innerHTML = "";
It would look like this
$.ajax({
url: base_url + "pm/send_reply",
type: 'POST',
data: {conv_id : conv_id, content: content, user_id : user_id},
success: function(data) {
var res = data.result;
$('#pm-write').empty(); //Clean the textarea
//Other code
}
});
Using javascript, you can easily achieve this by setting an event listener on the text-area like this
document.addEventListener("DOMContentLoaded", function() {
var submitBtn = document.getElementsByClassName("btn-send-reply")[0];
submitBtn.addEventListener("click", function(){
document.getElementsByName("message")[0].value = "";
});
});
or in jQuery
$(document).ready(function(){
$('.btn-send-reply').click(function(){
$( "input[name*='message']" ).val("");
})
})

Change Ajax Post parameters & returned HTML based on alternating dependant dropdowns

I have 3 dropdowns containing values that are populated on page load
<select class='form-control' id='make' placeholder='Make:'>
<select class='form-control' id='model' placeholder='Model:'>
<select class='form-control' id='version' placeholder='Version:'>
I have a function that updates the values in the 'other' dropdowns that aren't clicked, based on the value of the dropdown that is clicked - but I have this function repeated 3 times, for each dropdown
$('#model').change(function(){
let selectedModel = $(this).val();
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: {model: selectedModel},
success:function(data)
{ $('#make').html('');
$('#version').html('');
let makeJSON = JSON.parse(data)[0];
let versionJSON = JSON.parse(data)[2];
for (let i = 0; i < makeJSON.length; i++) {
if (makeJSON[i].mMake!= '' && makeJSON[i].mMake!= null) {
$('#make').html($('#make').html() + '<option value="' + makeJSON[i].mMake + '">' + makeJSON[i].mMake + '</option>');
}
}
for (let i = 0; i < versionJSON.length; i++) {
if (versionJSON[i].mVersion != '' && versionJSON[i].mVersion != null) {
$('#version').html($('#version').html() + '<option value="' + versionJSON[i].mVersion + '">' + versionJSON[i].mVersion + '</option>');
}
}
}
});
});
And the PHP looks something like this:
$model = $_REQUEST['model'];
$sqlupdateModel = "SELECT DISTINCT mMake, mVersion FROM Cars WHERE mModel = '$model';
$stmtModel = sqlsrv_query( $conn, $sqlupdateModel);
if( $stmtModel === false)
{
die( print_r( sqlsrv_errors(), true));
}
$updateModel = [];
while( $row = sqlsrv_fetch_array( $stmtModel, SQLSRV_FETCH_ASSOC)){
$updateModel[] = $row;
}
echo json_encode(array($updateMake, $updateModel, $updateVersion));
...and this all works fine,
Basically, I'm looking for a simpler solution for reusing the function (both JS & PHP) instead of rewriting it 3 times!
In terms of what I have attempted,
$('#make, #model, #version').change(function(){
let columnValue = $(this).val();
.......
data: {model: columnValue},
success:function(data)
{$(this).html(''); //this doesn't work obviously!
After this I'm snookered
This one should work for JS side, you will have to check mapping function for response
$('#make, #model, #version').change(function(ev){
let selected = $(this).val();
let id = ev.target.id;
let data = {};
data[id] = selected;
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: data,
success:function(data)
{
let options = ['make', 'model', 'version']
const response = {
make: JSON.parse(data[0].map(make => make.mMake)),
model: JSON.parse(data[1].map(make => make.mModel)),
version: JSON.parse(data[2].map(make => make.mVersion))
}
options.filter(option => option !== id).forEach(option => setDropdown(option, response[option]));
}
});
});
function setDropdown(id, data) {
const id = `#${id}`
$(id).html('');
for (let i = 0; i < data.length; i++) {
if (data[i] != '' && data[i] != null) {
$(id).html($(id).html() + '<option value="' + data[i] + '">' + data[i] + '</option>');
}
}
}

str_replace inside js from Ajax call data

i want to replacement character from data loop ajax (data[i]) to some values,
i have this js
<script type="text/javascript">
$(document).ready(function() {
$('select[name="parameter"]').on('change', function() {
var idpar = $(this).val();
var subdir = $('input[name="subdirid"]').val();
var year = $('input[name="added_year"]').val();
var i = 0;
if (idpar != '') {
$.ajax({
url: "{{URL::to('myform/myformColaborate')}}/" + idpar + "/" + subdir + "/" + year,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (key, city2) {
$('select[name="type2"]').empty();
$('select[name="type2"]').append(
'<option disabled selected>Select Request Colaborate</option>'
);
for (var i = 0; i < data.length; i++) {
$('select[name="type2"]').append(
'<option value="'+ data[i] +'">Request Colaborate with '+ data[i] +'</option>'
);
}
});
}
});
}
});
});
</script>
and the controller
public function myformColaborate($idpar, $subdir, $year) {
$cities = DB::table("pra_kpis")
->where('subdir_colaborate','like','%'.$subdir.'%')
->where('added_year',$year)
->where('kpi_parameters_id',$idpar)
->distinct()
->pluck("subdirs_id");
return response()->json($cities, 200);
}
for example , i have script replacement outside js like this, how to define it inside js
<?php
$roles = DB::table('pra_kpis')->where('id','=',$l->id)->pluck('subdir_colaborate');
$dir2 = DB::table('subdirs')->select('name')->pluck('name');
$iddir = DB::table('subdirs')->select('id')->pluck('id');
?>
#foreach($roles as $drop)
{{$drop = str_replace($iddir, $dir2, $drop)}}
#endforeach
Try this:
Do it from front-end only,
Use data[i].replace('search string', 'replace string');

Categories

Resources