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>');
}
});
})
Related
I am facing an issue that has baffled and actually exhausted me for hours.
I have tried so many different things, have done and still doing various debugging techniques but I am very tired and would seek for some help of any kind.
I will post the very basics for start, in case someone has any helpful idea/suggestion to unstack me, and I might be adding further information or more code as we go if needed.
I am working on a Joomla site and on a custom component view I place an inline jQuery script at some point of my html output.
The problem is that while everything works well on my localhost, when I upload it online the javascript breaks in whatever point I try to create variables that contain html. Then the browser will auto-close the script tag with </script> and the rest of the js code will be output as html.
So for example, the following script:
<script>
(function($)
{
$(document).ready(function()
{
var loader = '<div id="loader"><div>';
});
})(jQuery);
</script>
will end up to something like below:
<script>
(function($)
{
$(document).ready(function()
{
var loader = '<div id="loader">';
</div></script>
});
})(jQuery);
</script>
*Another clue that I just got is that the issue seems to be when I upload this on Litespeed server.
I tested this on 2 different servers with Litespeed and then on 1 Apache.
The one on the Apache server works fine (like on my localhost).
This is my complete inline script, just in case anyone is in place to catch anything that I am missing.
(function($)
{
$(document).ready(function()
{
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var obj = <?php echo json_encode($availableTags); ?>;
var searchForm = $('#adminForm');
var predefinedTags = $('.tags-cloud.popular-tags .li-item');
var searchTermId = '';
var oldSearchTermId = '';
var categories = <?php echo json_encode( $search_categories ); ?>;
var categoriesAction = '<?php echo (int)$sel_categories_option; ?>';
var list_limit = '<?php echo (int)$list_limit; ?>';
var list_limitstart = 0;
var list_order_by = '<?php echo $list_order_by; ?>';
var list_order_dir = '<?php echo $list_order_dir; ?>';
var menuItem = '<?php echo (int)$menuItem; ?>';
var show_image = '<?php echo (int)$show_image; ?>';
var show_date = '<?php echo (int)$show_date; ?>';
var which_date = '<?php echo $which_date; ?>';
var show_category = '<?php echo (int)$show_category; ?>';
var searchResults;
var loadMore = false;
var loader = "";
// Form submit
$(searchForm).on('submit', function(e) {
searchTermId = $('#sm-search-term-id').val();
e.preventDefault();
ajaxSearchArticles();
});
$('.search-order-selects').on('change', function(e) {
searchTermId = $('#sm-search-term-id').val();
list_order_by = $('#search-order').val();
list_order_dir = $('#search-order-dir').val();
list_limitstart = 0;
ajaxSearchArticles();
});
$(predefinedTags).on('click', function(e) {
searchTermId = $(this).attr('data-tagid');
$( "#sm-search" ).val( $(this).text() );
$( "#sm-search-term-id" ).val( searchTermId );
$( "#sm-search-description" ).html( '(' + $(this).attr('total_articles') + ' Total Articles)');
ajaxSearchArticles();
return false;
});
$('#search-results').on('click','#load-more-div', function() {
searchTermId = $('#sm-search-term-id').val();
list_limitstart = parseInt(list_limitstart) + parseInt(list_limit);
loadMore = true;
ajaxSearchArticles();
});
function appendResults() {
var html = '';
oldSearchTermId = searchTermId;
var l = parseInt(list_limit);
$(searchResults).each(function(i, e) {
var itemi = list_limitstart + i;
if (i < l) {
html += '<div id="artid-'+e.id+'" class="sm-search-result g-block s-item-'+itemi+'">';
html += '<div class="sm-search-result-content">';
if (show_image == '1') {
html += '<a href="'+ e.url +'" title="'+e.title+'" target="_blank">';
html += '<div class="smrc-image-holder"><img src="' + e.images + '" alt="'+e.title+'" /></div></a>';
}
html += '<div class="smrc-text-block"><h3>'+e.title+'</h3><p>'+e.introtext+'</p>';
if (show_date || show_category) {
html += '<div class="item-meta">';
if (show_date) {
var date = e.modified;
if (which_date === 'created') {
var date = e.created;
}
html += '<span class="item-date"><i class="fa fa-calendar-o" aria-hidden="true"></i> '+ date +'</span>';
}
if (show_category) {
html += '<span class="item-cat">in '+e.category +'</span>';
}
html += '</div>';
}
html += '</div></div></div>';
}
if (i === l) {
html += '<div id="load-more-div" class="sm-search-result load-more g-block">';
html += '<div class="sm-search-result-content" style="display: flex;align-items: flex-end;justify-content: center;height: 100%;">';
html += '<div class="load-more-results flex-item"><span>Load More...</span></div>';
html += '</div></div>';
}
});
html += '<div class="clear clearfix"></div>';
if (loadMore) {
$('#search-results').append(html);
} else {
$('#search-results').html(html);
}
loadMore = false;
}
// Autocomplete
$( function() {
var results = true;
$( "#sm-search" ).autocomplete({
minLength: 3,
source: obj,
focus: function( event, ui ) {
if (results) {
$( "#sm-search" ).val( ui.item.label );
}
event.preventDefault();
return false;
},
select: function( event, ui ) {
if (results) {
$( "#sm-search" ).val( ui.item.label );
$( "#sm-search-term-id" ).val( ui.item.value );
$( "#sm-search-description" ).html( '(' + ui.item.total_articles + ' Total Articles)');
}
event.preventDefault();
$(searchForm).submit();
return false;
},
response: function(event, ui) {
if (ui.content.length === 0) {
results = false;
var res = { label: "no results", value: 0 };
ui.content.push(res);
} else {
results = true;
}
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
if (results) {
return $( "<li>" )
.append( "<div><strong>" + capitalizeFirstLetter(item.label) + "</strong> <small>(" + item.total_articles + " articles)</small></div>" )
.appendTo( ul );
} else {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
}
};
});
// Ajax call
function ajaxSearchArticles() {
if (!searchTermId) {
$('#empty-message').text('No Tags Defined!');
setTimeout(function() {
$('#empty-message').text('');
}, 3000);
return false;
}
$('body').append(loader);
if (searchTermId !== oldSearchTermId) {
list_limitstart = 0;
}
var xhrRequest = {
'option' : 'com_rabattdatabase',
'task' : 'RabattAjax.ajaxReceiver',
'action' : 'customSearch',
'tagid' : searchTermId,
'orderby' : list_order_by,
'orderdir': list_order_dir,
'limit' : list_limit,
'limitstart' : list_limitstart,
'cats' : categories,
'itemid' : menuItem,
'catswhat': categoriesAction,
'<?php echo JSession::getFormToken();?>' : 1,
};
$.ajax({
context : this,
type : 'POST',
data : xhrRequest,
success : function(response) {
var response = $.parseJSON(response);
searchResults = response.data;
if (response.success == true) {
appendResults();
} else {
$('#search-results').html("<h4>We couldn't process your request!</h4>");
}
}
}); // End Ajax
}
})
})(jQuery);
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
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');
In the success part of my ajax each result gets put into columns.
What I am trying to achive is every 4 columns it will create a new row.
Question: On success part of ajax how to make it so every after every 4 columns will create a new row?
<script type="text/javascript">
$("#select_category").on('keyup', function(e) {
$.ajax({
type: "POST",
url: "<?php echo base_url('questions/displaycategories');?>",
data: {
category: $("#select_category").val()
},
dataType: "json",
success: function(json){
list = '';
list += '<div class="row">';
$.each(json['categories'], function(key, value ) {
list += '<div class="col-sm-3">';
list += value['name'];
list += '</div>';
});
list += '</div>';
$('.category-box').html(list);
}
});
});
</script>
You could just count how many you've added and insert a new row each time it reaches 4:
$("#select_category").on('keyup', function(e) {
$.ajax({
type: "POST",
url: "<?php echo base_url('questions/displaycategories');?>",
data: {
category: $("#select_category").val()
},
dataType: "json",
success: function(json) {
var list = '<div class="row">';
var index = 0;
$.each(json['categories'], function(key, value) {
list += '<div class="col-sm-3">';
list += value['name'];
list += '</div>';
index++;
if(index === 4) {
list += '</div><div class="row">';
index = 0;
}
});
list += '</div>';
$('.category-box').html(list);
}
});
});
Try this:
success: function(json){
list = '';
var cnt = 0;
list += '<div class="row">';
$.each(json['categories'], function(key, value ) {
list += '<div class="col-sm-3">';
list += value['name'];
list += '</div>';
cnt++;
if(!cnt%4){
list += '</div><div class="row">';
cnt = 0;
}
});
list += '</div>';
$('.category-box').html(list);
}
I have a web service with link: http://41.128.183.109:9090/api/data/getalllocations
I recived this data in dropdown using jquery .this data contains 2 objects LocationName and LocID. I want to display an alert with LocID in dropdown change function in jQuery. Here is my code:
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
var SubDropdown = $("#main");
for (var i = 0; i < data.length; i++) {
SubDropdown.append('<option value?' + i + '?="">' + data[i].LocationName + '</option>');
}
}
});
});
$("#countries").change(function () {
alert();
});
Here is my HTML code :
<select tabindex="-1" class="select2_group form-control" style="display: normal; width: 290px;" name="countries" id="countries">
<optgroup label="Select Your City" id="main"></optgroup>
</select>
please try following
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
var SubDropdown = $("#main");
for (var i = 0; i < data.length; i++) {
SubDropdown.append('<option value="' + data[i].LocID + '">' + data[i].LocationName + '</option>');
}
}
});
$("#countries").change(function () {
alert($("#countries").val());
});
});