javascript foreach select loop with selected value - javascript

I've written the following code that generates a select list. However, the part where it's supposed to check if this.id equals the same as the existing_code and put the selected value in doesnt seem to work.
any ideas what is wrong?
function showHide(layer, existing_code) {
jQuery.ajax({ url: 'getdata.php', dataType: 'json', cache: 'false', success: function(data) {
var codes = codes;
var selectcode = '';
selectcode += '<select name="codes">';
jQuery.each(codes, function() {
selectcode += '<option value="' + this.id + '"';
if (this.id == existing_code) {
selectcode += ' selected';
}
selectcode += '>' + this.code + '</option>';
});
selectcode += '</select>';
jQuery('.'+layer).html(selectcode);
}});
}

This is probably what you want:
function showHide(layer, existing_code) {
jQuery.ajax({ url: 'getdata.php', dataType: 'json', cache: 'false', success: function(data) {
var codes = data;
var selectcode = '';
selectcode += '<select name="codes">';
jQuery.each(codes, function(i, code) {
selectcode += '<option value="' + code.id + '"';
if (code.id === existing_code) {
selectcode += ' selected';
}
selectcode += '>' + code.code + '</option>';
});
selectcode += '</select>';
jQuery('.'+layer).html(selectcode);
}});
}

Related

Codigniter Javascript nested Jquery error

My requirnment is if data1[count1].result_type > 0 then the td will be a drop down list from a datatable. Nut is i try this, the output is like this, all the required options are comming to a single selectbox insted of the relevent row. And the result comes to the very last row.
The desired result would be two dropdowns at the last two rows. The wanted result options all together in the one dropdown. How can I solve this?
$('#bill_no_search').click(function() {
{
$("#data_table_one tbody").html("");
var barcode = $('#barcode_no').val();
$.ajax({
url: "<?php echo base_url('index.php/Lab_and_lab_office/get_barcode_to_bill_no'); ?>",
data: {
barcode: barcode
},
method: "POST",
dataType: "JSON",
success: function(data) {
var bill_no = data.bill_no;
console.log(bill_no)
$.ajax({
url: "<?php echo base_url('index.php/Lab_and_lab_office/resulting'); ?>",
data: {
bill_no: bill_no
},
method: "POST",
dataType: "JSON",
success: function(data) {
for (var count = 0; count < data.length; count++) {
var element_id = data[count].element_id;
var ct = 'screen' + count + '';
var bt = 'td' + count + ''
var result = 'result' + count + ''
$('#data_table_one tbody').append(
'<tr>' +
'<td >' + (count + 1) + '</td>' +
'<td >' + data[count].billing_element_result_id + '</td>' +
'<td >' + data[count].bill_no + '</td>' +
'<td >' + data[count].processor_id + '</td>' +
'<td >' + data[count].test_processor_display_name + '</td>' +
'<td >' + data[count].test_code + '</td>' +
'<td >' + data[count].test_details + '</td>' +
'<td contenteditable=true id="result' + count + '">' + data[count].result + '</td>' +
'<td id="td' + count + '" contenteditable=true><select id="screen' + count + '" style="display:none"></select></td>' +
'<td contenteditable=true id="resultcell">' + data[count].result + '</td>' +
'</tr>'
);
console.log(ct)
$.ajax({
url: "<?php echo base_url('index.php/Lab_and_lab_office/get_result_type'); ?>",
data: {
element_id: element_id
},
method: "POST",
dataType: "JSON",
success: function(data1) {
for (var count1 = 0; count1 < data1.length; count1++) {
if (data1[count1].result_type > 0) {
document.getElementById(ct).style.display = "block";
$('#' + ct + '').append(
'<option>' + data1[count1].result_options + '</option>'
);
document.getElementById(bt).contentEditable = "false";
document.getElementById(result).contentEditable = "false";
}
console.log(ct)
}
}
})
}
}
})
}
})
}
})

how to change one button based on value

I want to change my ajax button based on if else condition. Like if status is 1 then it will show just active button otherwise it just show the inactive button. I have two buttons. I cant find the logic where I actually put my if else condition. My code is:
function showAllArticle(status = "") {
//alert(status);
$.ajax({
//cache: false,
//headers: { "cache-control": "no-cache" },
type: 'ajax',
method: 'post',
data: {
status: status
},
url: '<?php echo base_url() ?>Article/showAllUser',
async: true,
dataType: 'json',
//cache: false,
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
//(data[i].status);
html += '<tr>' +
'<td>' + data[i].id + '</td>' +
'<td>' + data[i].username + '</td>' +
'<td>' + data[i].email + '</td>' +
'<td>' +
// '{% if data[i].status == 1 %}'
'Active' +
//#if(data[i].status == 1)
//'{% else %}'
'Inactive' +
//'{% endif %}'
/* '</td>' +
'<td>'+
'+#if(data[i].status == 1)+'
'tseting'+
'+#elseif(data[i].status == 0)+'
'debug'+
'+#endif+'
'</td>'+*/
'</tr>';
}
$('#showdata').html(html);
},
error: function() {
alert('Could not get Data from Database');
}
});
}
You must apply the if condition based on JS, not on the template language you are using as JS is executed on the user end.
You must do something similar do this:
html += '<tr>';
html += '<td>' + data[i].id + '</td>';
html += '<td>' + data[i].username + '</td>';
html += '<td>' + data[i].email + '</td>';
html += '<td>';
if (data[i].status == 1) {
html += 'Active';
} else if(data[i].status == 12) {
//...
} else {
html += 'Inactive' +
}
/* '</td>' +
'<td>'+
'+#if(data[i].status == 1)+'
'tseting'+
'+#elseif(data[i].status == 0)+'
'debug'+
'+#endif+'
'</td>'+*/
html += '</tr>';

Make a combo box from ajax response

So, I have a button. When I click on it, It'd retrieve ids by ajax method. While the ids are being generated, I'm using another ajax to get some data using the id's as parameter. it's basically an ajax inside an ajax response.
JS:
$("#btn_add").click(function() {
var val_txt = $('#i_minta').find('option:selected').val().replace(/\s{2,}/g, ' ').trim();
var val = val_txt.split("|");
var val_no = val[0];
var val_tgl = val[1];
var val_kc = val[2];
$.ajax({
type: "POST",
url: "<?php echo site_url('con_atk/get_minta'); ?>",
cache: false,
dataType: "json",
data: {
x: val_no /*this is the parameter to get the ID List*/
},
success: function(response) {
var no = 1;
var col_no, col_brg, col_pnh, col_mnt, col_hrg, col_tot, tableData;
$.each(response, function(index, data) {
var txt_harga = [];
var select_txt = "<select id=combo_harga class='form-control'></select>";
$.ajax({
type: "POST",
url: "<?php echo site_url('con_atk/get_harga'); ?>",
cache: false,
dataType: "json",
data: {
y: data.KodeBarang /* this is the ID to get another data */
},
success: function(outputs) {
$.each(outputs, function(i, value) {
//$('#combo_harga').append($('<option></option>').val(index).html(value.harga));
//txt_harga.push('<option value="'+ value.stok +'">'+ value.harga +'</option>');
txt_harga[i] = "<option value='" + value.stok + "'>" + value.harga + "</option>";
});
$('#combo_harga').append(txt_harga.join(''));
}
});
var rowCount = $("#t_output tbody tr").length;
var in_kode = "<input type='hidden' id='i_kb' name='detail[" + rowCount + "][in_kb]' value='" + data.KodeBarang + "' />";
var in_pmnh = "<input type='text' id='i_pnh' name='detail[" + rowCount + "][in_pnh]' onCopy='return false' onDrag='return false' onDrop='return false' onPaste='return false' autocomplete='off' onkeypress='return isNumber(event)' />";
col_no = "<tr><td style='text-align:right; vertical-align:middle'>" + no++ + "</td>";
col_brg = "<td style='text-align:left; vertical-align:middle'>" + data.KodeBarang + " " + in_kode + "<br />" + data.NamaBarang + "</td>";
col_pnh = "<td class='mid'>" + in_pmnh + "</td>";
col_mnt = "<td class='mid'><input type='text' id='o_pmnt' value='" + data.jumlah_minta + "' style='font-weight:bold; width:70%; text-align:right; background-color:#DE5862 !important' readonly /></td>";
col_hrg = "<td style='text-align:right; vertical-align:middle'>" + select_txt + "</td>";
col_tot = "<td style='text-align:right; vertical-align:middle'>xxx</td></tr>";
tableData += col_no + col_brg + col_pnh + col_mnt + col_hrg + col_tot;
$('#t_output tbody tr').remove();
$('#t_output tbody').append(tableData);
});
}
});
});
The end result is a table with each row has a combobox with the value of each id. Like this:
no id somecolumn somecolumn harga somecolumn
1 A xxx xxx value_of_A_1 xxx
2 B xxx xxx value_of_B_1,value_of_B_2 xxx
3 C xxx xxx value_of_C_1,value_of_C_2,value_of_C_3 xxx
the combobox should be inside the harga column.
Thank you for your help :)
Hope It will success you.(it's my old code. don't worry about code format)
var as = $(this).val();
var val = as;
as = as.replace(/\s/g, '');
if (this.checked) {
var a = "_" + as;
var viewName = { viewName: a }
var billingFieldId = '#A' + as + '_BillingCycleId';
var vatFieldid = '#A' + as + '_VatcalculationProcessId';
var serviceType = '#A' + as + '_ServiceType';
$.ajax({
url: '#Url.Action("GetPartialView", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(viewName),
type: 'POST',
dataType: 'html'
}).success(function (result) {
$('#' + as).html(result);
if (billningCycle != null && vatCalculation != null) {
$.ajax({
url: '#Url.Action("GetCommonValue", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(viewName),
type: 'POST',
dataType: 'json',
success: function (data) {
$.each(data.BillingCycles, function (index, value) {
$(billingFieldId).append($('<option />', {
value: value.Id,
text: value.Name
}));
});
$.each(data.Vats, function (index, value) {
$(vatFieldid).append($('<option />', {
value: value.Id,
text: value.Name
}));
});

check session value (ajax)

Im making a site but i want to check the value of a session so i can show a button depending on what the users role is.
the problem im having is that i cant get the value of the session into SessionValue
i will also add that the file is a .js
what i have so far:
function getGroups() {
var SessionValue = <?php print($_SESSION['user_role']); ?>;
$.ajax({
url: 'services/functions.php',
data: {
action: 'getGroups'
},
type: 'post',
success: function (output) {
var result = JSON.parse(output);
result = result.results;
$(result).each(function (index, element) {
var out = "<div class='row'>";
out += "<div class='col-md-3'>";
out += "<img class='img-responsive image_" + index + "' src=" + element.group_image + ">";
out += "</div>";
out += "<div class='col-md-9'>";
out += "<h3>" + element.group_title + "</h3>";
if(SessionValue == "admin"){
out += "<button class='btn btn-primary pull-right' type='button' id='submitPost'>Delete</button>";
}
out += "<h4 class='hidden_" + index + "'>" + moment(element.group_playdate, 'HH:mm:ss').format('HH:mm') + "</h4>";
out += "<p class='hidden_" + index + "'>" + element.group_description + "</p>";
out += "</div>";
out += "</div>";
out += "<hr/>";
$(".groupContainer").append(out);
$(".hidden_" + index).hide();
$(".image_" + index).hover(
function () {
$('.hidden_' + index).fadeIn(200);
},
function () {
$('.hidden_' + index).fadeOut(100);
}
);
});
},
error: function (output) {
console.error("Something went wrong while loading the groups from the database.");
}
});
}
the session is started and the user_role is also defined #login.

Why are functions executed in this order?

Code:
function fillChooseCompInAddDeviceDiv(){
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "2"},
dataType: "json",
success: function(data) {
$("table#choseComponentAddDeviceDiv").find("td").remove();
for(var i = 0; i<data.length; i++) {
$("table#choseComponentAddDeviceDiv").append("<tr>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].price + "</td>" + "<td>" + data[i].amount + "</td>" + "<td>" + data[i].description + "</td>" + "<td>" + data[i].categoryName + "</td>" + "<td>" + "<a href='" + data[i].link + "'>" + data[i].link + "</a>" + "</td>" + "<td>" + "<img src = '" + data[i].imagePath + "' />" + "</td>" + "<td>" + "<input type='checkbox' class='checkBoxCol' value='" + data[i].name + "'>" + "</td>" + "</tr>");
}
alert("ALERT 1");
},
error: function(status) {
//Do something
}
});
}
//any edit clicked in eny table
function anyEditOnCLick(buttonId, buttonVal){
window.editIsClicked = true;
$("input.nameInput").attr("readonly", true);
if (buttonId === "device"){
$("#addDeviceDiv").css("visibility", "visible");
window.location.hash = "#addDeviceDiv";
fillChooseCompInAddDeviceDiv();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "11", toEdit: buttonVal},
dataType: "json",
success: function(data) {
// puni text area
$("#addDeviceFieldName").val(data.name);
$("#addDeviceFieldDescription").val(data.description);
// cekira odgovarajuce komponente, jedan samo data se ocekuje, ne data[]
//fillChooseCompInAddDeviceDiv();
for (var i = 0; i<data.components.length; i++){
$("table#choseComponentAddDeviceDiv td input").filter(function(){return this.value == data.components[i].name}).attr("checked", true);
}
alert("ALERT 2");
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addDeviceDiv input#addDeviceFieldName").attr("readonly", true);
} else if (buttonId === "component"){
$("#addComponentDiv").css("visibility", "visible");
window.location.hash = "#addComponentDiv";
fillCategorySelection();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "21", toEdit: buttonVal},
dataType: "json",
success: function(data) {
$("#addComponentFieldName").val(data.name);
$("#addComponentFieldPrice").val(data.price);
$("#addComponentFieldAmount").val(data.amount);
$("#addComponentFieldDescription").val(data.description);
$("#addComponentFieldLink").val(data.link);
$("#form#uploadForm #imageFile").attr("value", data.imagePath);
//fillCategorySelection();
$("#addComponentDiv select.categorySelect option").filter(function(){return this.value == data.categoryName}).attr("selected", "selected");
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addComponentDiv input#addComponentFieldName").attr("readonly", true);
} else if (buttonId === "category"){
$("#addCategoryDiv").css("visibility", "visible");
window.location.hash = "#addCategoryDiv";
fillChoseSubCategoriesinAddCategoriesDiv();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "31", toEdit: buttonVal},
dataType: "json",
success: function(data) {
$("#addCategoryFieldName").val(data.name);
$("#addCategoryFieldDescription").val(data.description);
//fillChoseSubCategoriesinAddCategoriesDiv();
for (var i = 0; i<data.subCategories.length; i++){
$("table#choseSubCategoriesinAddCategoriesDiv td input").filter(function(){return this.value == data.subCategories[i].name}).attr("checked", true);
}
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addCategoryDiv input#addCategoryFieldName").attr("readonly", true);
}
}
Function anyEditOnCLick(arg1, arg2) is event function and is placed in onClick tag of a button.
When I click on this button browser always first shows ALERT 2 message and after that go execute fillChooseCompInAddDeviceDiv() and shows ALERT 1. Can someone explain what is really happend here and how can I "persuade" javascript first execute fillChooseCompInAddDeviceDiv()? Before this, i thought function call provides executing whole function body before resuming execution of outer code.

Categories