jQuery append only the options which are not null - javascript

I am trying to append options which are not null only, but i am getting both of the options appended, why?
jQuery:
success: function (data) {
var obj = JSON.parse(data);
$.each(obj, function (booking_price, value) {
if (value.AIRBNB_CONF.length > 0 ) {
$('.searchable').append("<option value=\"" + value.AIRBNB_CONF + "\">" + value.AIRBNB_CONF + "</option>");
}
if (value.DBASE_ID.length > 0 ) {
$('.searchable').append("<option value=\"" + value.DBASE_ID + "\">" + value.DBASE_ID + "</option>");
}
});
},
I am trying to append either value.AIRBNB_CONF or value.DBASE_ID but instead both of them getting appended. it should be like if DBASE_ID 1234 contains AIRBNB_CONF append the AIRBNB_CONF otherwise the DBASE_ID...

You need to use else if in the second case, otherwise it always go through second if
success: function(data) {
var obj = JSON.parse(data);
$.each(obj, function(booking_price, value) {
if (value.AIRBNB_CONF.length > 0) {
$('.searchable').append("<option value=\"" + value.AIRBNB_CONF + "\">" + value.AIRBNB_CONF + "</option>");
}
else if (value.DBASE_ID.length > 0) {
$('.searchable').append("<option value=\"" + value.DBASE_ID + "\">" + value.DBASE_ID + "</option>");
}
});
}
For better understanding of if...else read the documentation of if...else here

Related

How can I use each loop variable (item) outside of loop

I want to make a switch for declaring variables inside each loop, like this
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' '
+ item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
But since item variable hasn't defined yet I will get an ReferenceError.
Moving switch inside loop will make It really slow.
Is this even possible to declare loop variables outside of scope?
function selectorAddEdit(label, tag, result, labelconf) {
var idtag = tag+"s";
var none = "<option value='None'>None</option>";
var labelHead = (labelconf=="head") ? "<div class='selectTitles'><label>"+label+"</label></div>" : "";
switch (label) {
case "Users":
var content = item.username + ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
html += "</select></div>";
$("." + idtag).html(html);
}
Declare the content as a global variable
var content="";
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='"+item.id+"'>"+content+"</option>";
});
This is assuming that item is distinct/unique and therefore you want the switch statement to be re-evaluated at each iteration of loop. What you can do is to use a method/function that returns the value, after evaluating a given condition:
var getOptionContent = function(item) {
switch (label) {
case "Users":
return item.username + ' ' + item.firstname + ' ' + item.lastname + '(' + item.organization + ')';
default:
return '';
}
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function(i, item) {
html += "<option value ='" + item.id + "'>" + getOptionContent(item) + "</option>";
});

Pass option value from one function to another function

I have a function like this:
$('input[type=radio][name=editList]').change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")",
function (data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" +item.ID+item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
I want to get that item.ID to use into another function as:
$(function getCuadrilla() {
var items = "";
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "?ProveedorID=" + ID, function (data) {
$.each(data, function (index, item) {...
});
$("#lstcuadrilla").html(items);
});
});
I try to use $('input[type=radio][name=editList]').val() as
$(function getCuadrilla() {
var items = "";
$('input[type=radio][name=editList]').val();
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "?ProveedorID=" + ID, function (data) {
$.each(data, function (index, item) {...
});
$("#lstcuadrilla").html(items);
});
});
but instead item.ID I receive string "Proveedor", can any one explain me how can I access to item.ID? Regards
Complete JS:
<script type="text/javascript">
$(function getResponsable() {
$('input[type=radio][name=editList]')
.change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores ", "Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.ID + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("
GetUnidades ", "
Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.Codigo + "-" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario ", "Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + " " + item.Apellido + "</option>";
});
$("#lstProveedor").html(items);
});
}
});
$(function getCuadrilla() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
});
As James comment, I try it and JS hit first line but it donĀ“t pass over there
Update:
New js structure:
<script type="text/javascript">
$(function getResponsable() {
$('input[type=radio][name=editList]')
.change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.ID +
item.NombreComercial +
"</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("GetUnidades", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.Codigo +
"-" +
item.Nombre +
"</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.Nombre +
" " +
item.Apellido +
"</option>";
});
$("#lstProveedor").html(items);
});
}
});
$("#lstProveedor").change(function() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
}
);
});
});
</script>
You can try this. Keep in mind that the ID you are passing to the handler function is either a provider id or a sucursal id or a usuario id, depending on which radio button populated the drop down the first time around. Also this handler will remain on the dropdown even when it has been populated by Cuadrillas.
Change
$(function getCuadrilla() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
to
$("#lstProveedor").change(function (e) {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
}
);
});

Why doesn't the code enter each block?

I need to select all the check boxes, that are checked and then get the value of id attribute.
I am doing the following way :
$("input:checkbox[class=selectioncheckbox]").each(function() {
console.log("Inside each block");
if($(this).is(":checked")) {
console.log("Inside if block");
pnames[c] = $(this).attr('id');
console.log(pnames[c] + " " + c);
c++;
}
});
But there is a problem. The code never enters the each block. What could be the reason for this?
EDIT:
Here is the code that adds checkboxes with class selectioncheckbox:
$('#teamcheckbox_a').change(function() {
if($(this).is(':checked')) {
$('#teamcheckbox_b').prop('checked',false);
$('#playerselect').empty();
team_a = $('#teamnames_a option:selected').text();
$.ajax( {
url : 'http://localhost:8081/Football/GetPlayerNames',
data : {
teamname : $('#teamnames_a option:selected').text()
},
dataType : 'json',
type : 'GET'
})
.done(function(message) {
$('#playerselect').html("<label>Select Players</label>");
$.each(message,function(index,row) {
$('#playerselect').append(
"<tr>" +
"<td class='text-center'>" + row.jnumber + "</td>" +
"<td>" + row.name + "</td>" +
"<td class='text-center'>" + row.position + "</td>" +
"<td> <input type='checkbox' class='selectioncheckbox form-control input-lg' id='" + row.jnumber + ":" + row.name + "' /> </td>" +
"</tr>");
});
$('.selectioncheckbox').change(function() {
if($(this).is(':checked')) {
count++;
} else {
count--;
}
$('#pcount').html("Count : " + count);
});
})
.fail(function(message) {
console.log(message);
})
}
});
$('#teamcheckbox_b').change(function() {
if($(this).is(':checked') ) {
$('#teamcheckbox_a').prop('checked',false);
$('#playerselect').empty();
team_a = $('#teamnames_b option:selected').text();
$.ajax( {
url : 'http://localhost:8081/Football/GetPlayerNames',
data : {
teamname : $('#teamnames_b option:selected').text()
},
dataType : 'json',
type : 'GET'
})
.done(function(message) {
$('#playerselect').html("<label>Select Players</label>");
$.each(message,function(index,row) {
$('#playerselect').append(
"<tr>" +
"<td class='text-center'>" + row.jnumber + "</td>" +
"<td>" + row.name + "</td>" +
"<td class='text-center'>" + row.position + "</td>" +
"<td> <input type='checkbox' class='selectioncheckbox form-control input-lg' id='" + row.jnumber + ":" + row.name + "' /> </td>" +
"</tr>");
});
$('.selectioncheckbox').change(function() {
if($(this).is(':checked')) {
count++;
} else {
count--;
}
$('#pcount').html("Count : " + count);
});
})
.fail(function(message) {
console.log(message);
})
}
});
Either the code isn't being called at all, or $("input:checkbox[class=selectioncheckbox]") has a length of 0 (which is most likely caused by running the code before the elements have been added to the DOM, in which case you can resolve it with a ready handler).
Use as selector: $(".selectioncheckbox:checked") because i guess selectioncheckbox is only applied to checkboxes and no need to check for checked state inside each loop.
And your issue was none element was matched because using attribute selector [class=selectioncheckbox] if more than one class set on same element, this doesn't match.
The script is calling before the elements added to the DOM. So the script is unable to identify the class name and the length will be 0. Call the script in the ready handler as follows.
$(document).ready(function(){
var c= 0;
var pnames = [];
$("input:checkbox[class=selectioncheckbox]").each(function() {
console.log("Inside each block");
if($(this).is(":checked")) {
console.log("Inside if block");
pnames[c] = $(this).attr('id');
console.log(pnames[c] + " " + c);
c++;
}
});
});

Is there a better way to check if the category has been iterated upon?

Currently, I display a category once I check to see if the category id exists, if id is null , document.write. Is there a way to write each category just once without using id?
Here is the JSON:
var foods = {
"category":{
"Meats":[
{
"product":"NY Strip",
"price":20.00,
"cost":14.00,
"total sold": 3
},
{
"product":"Ribeye",
"price":20.00,
"cost":14.00,
"total sold": 6
}
],
"Vegetables":[
{
"product":"Kale",
"price":4.00,
"cost":2.00,
"total sold": 10
},
{
"product":"Sunchokes",
"price":3.20,
"cost":1.00,
"total sold": 5
}
]
}
}
Here is the code:
for(var key in foods.category) {
foods.category[key].forEach(function(item, index) {
// check if the id exists, if not write the category with id
if(document.getElementById(key) === null){
document.write("<h4" + " id='" + key + "'" + ">" + key + "</h4>")
}
document.write("<li>" + item.product + "</li>");
});
}
Here's the result:
Meats
NY Strip
Ribeye
Vegetables
Kale
Sunchokes
assuming category values are unique, the following should produce the same result.
for(var key in foods.category) {
document.write("<h4" + " id='" + key + "'" + ">" + key + "</h4>")
foods.category[key].forEach(function(item, index) {
document.write("<li>" + item.product + "</li>");
});
}
Not sure if you were just trying to eliminate the ID querying via the document object or not, but this just queries via a string being built.
var output = "";
for (var key in foods.category) {
if (output.indexOf("<h4 id='" + key + "'") < 0) {
output += "<h4" + " id='" + key + "'" + ">" + key + "</h4>";
}
foods.category[key].forEach(function (item, index) {
// check if the id exists, if not write the category with id
output += "<li>" + item.product + "</li>";
});
}
document.querySelector('#output').innerHTML = output;
http://jsfiddle.net/phh7nsnv/1/

If / Else jQuery to skip undefined value

I have this chained select box (demo) using JSON file to populate options based on this script.
Here's the script:
$(window).bind('load', function() {
$.getJSON('suggest.json', function(data){
var $select = $('#mySelectID');
$.each(data, function (index, o) {
var $option = $("<option/>").attr("value", o.Box1ID + ":" + o.Box3).text(o.Box1 + "|" + o.Box2 + "|" + o.Box3);
$select.append($option);
});
$("#mySelectID").dynamicDropdown({"delimiter":"|"});
});
});
I have trouble using if statement to skip undefined value. The JSON file is like this:
[{"Box1":"A","Box1ID":"B","Box3":"C"},{"Box1":"E","Box1ID":"F","Box2":"G","Box3":"H"}]
If Box2 doesn't exist, I want the var $option to be:
var $option = $("<option/>").attr("value", o.Box1ID + ":" + o.Box3).text(o.Box1 + "|" + o.Box3);
Would typeof undefined work here? But I'm not sure what variable should be defined.
if (typeof var?? === 'undefined') {
var $option = $("<option/>").attr("value", o.Box1ID + ":" + o.Box3).text(o.Box1 + "|" + o.Box3); }
else {
$("<option/>").attr("value", o.Box1ID + ":" + o.Box3).text(o.Box1 + "|" + o.Box2 + "|" + o.Box3);
}
Any help would be appreciated. Thank you.
You can also just do this:
if (! data.Box2) {
...
}
Undefined, null, and empty string all test as false in JavaScript.
you can do something like:
... .text(o.Box1 + "|" + (o.Box2?oBox2+"|":"") + (o.Box3||"") );
Use
$(window).bind('load', function() {
$.getJSON('suggest.json', function(data){
var $select = $('#mySelectID');
$.each(data, function (index, o) {
var $option = $("<option/>").attr("value", o.Box1ID + ":" + o.Box3);
if (typeof data.Box2 === 'undefined')
{
$option.text(o.Box1 + "|" + o.Box3);
}
else {
$option.text(o.Box1 + "|" + o.Box2 + "|" + o.Box3);
}
$select.append($option);
});
$("#mySelectID").dynamicDropdown({"delimiter":"|"});
});
});
If you check the typeof of a object method/attribute that does not exists, it will return 'undefined'.

Categories

Resources