If / Else jQuery to skip undefined value - javascript

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'.

Related

jQuery append only the options which are not null

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

Javascript type mismatch error

I have the following code and i am unsure why i am getting the error `Type mismatch'
If i simply have the following, it works;
Working code
newTag = tags.AddNew( 'MyTag0', 'Number0' );
newTag.Update();
Code that returns an error
var p = {
"MyTag0" : "Number0",
"MyTag1" : "Number1"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
newTag = tags.AddNew("'" + key + "'" + " , " + "'" + p[key] + "'");
newTag.Update();
}
}
They are already strings, you do ont have to build up a string to try to look like a string.
newTag = tags.AddNew("'" + key + "'" + " , " + "'" + p[key] + "'");
What the above code results in is
newTag = tags.AddNew( "'MyTag0'", "'Number0'" );
It just needs to be
newTag = tags.AddNew(key, p[key]);
Use Something like this :
if (p.hasOwnProperty(key)) {
var k = "'" + key + "'";
var pk = "'" + p[key] + "'";
newTag = tags.AddNew(k, pk);
newTag.Update();
}
Another Idea ( not able to debug but you can try..)

Jquery adding and removing items from listbox

I've created this fiddle, it allows the user to click on either art or video, dynamically populating the the second listbox with the list associated with those selections. There are two buttons, one to add the selection to the box, the other which removes the selection.
What I would like to do is prevent the user from adding some that has already been added. The value of the options will all be Guids. Bonus points if you can modify the fiddle to use Guid instead of ints.
I've tried this:
$.each($("#SelectBox2 option:selected"), function (i, ob) {
if (i == $(this).val()) {
} else {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
I would like to enable the user to remove the selected items from the list.
Thanks,
UPDATE Just letting you guys know what the solution is that I came up with, I got the bonus points because i added GUID to it in a really smart way :) fiddle, I also tidied up the html to make it look nice and neat.
MAJOR UPDATE A massive thanks to everyone who has contributed to this question, I have taken on board everyones comments and fiddles and have generated this >> fiddle <<
I think you would want to do something like this: Check if value is in select list with JQuery.
Modifying your code to something like this should work:
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var exists = false;
$('#SelectedItems option').each(function(){
if (this.value == optionVal) {
exists = true;
}
});
if(!exists) {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
Removing selected items would look like this:
$('#remove').click(function () {
$("#SelectedItems option:selected").remove();
});
If you want to dynamically add and delete rows seamlessly try this way
http://jsfiddle.net/WX4Nw/
Adding a pointer to the selecteditems list as a data attrib to the root item key will help you control so that you can easily manage add/remove.
Snippet from fiddle:-
$('#SelectBox').change(function () {
var str = "",
inHTML = "",
key = $('#SelectBox').val(),
items;
items = $(this).val() == 'art' ? artItems : vidItems;
$.each(items, function (i, ob) {
if($('#SelectedItems option[value="' + i + '"][data-key="' + key + '"]').length == 0)
inHTML += '<option value="' + i + '" data-key="' + key + '">' + ob + '</option>';
});
$("#SelectBox2").empty().append(inHTML);
});
$('#add').click(function () {
var itemsToAdd = [];
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var key = $(this).data('key');
if ($('#SelectedItems option[value="' + optionVal + '"][data-key="' + key + '"]').length == 0) {
itemsToAdd.push($(this).removeAttr('selected'));
}
});
$("#SelectedItems").append(itemsToAdd);
});
Try:
$(function () {
var artItems = ["Art 1", "Art 2", "Art 3", "Art 4", "Art 5", "Art 6"];
var vidItems = ["Video 1", "Video 2", "Video 3", "Video 4", "Video 5", "Video 6"];
$('#SelectBox').change(function () {
var str = "",
inHTML = "",
items;
items = $(this).val() == 'art' ? artItems : vidItems;
$.each(items, function (i, ob) {
inHTML += '<option value="' + i + '">' + ob + '</option>';
});
$("#SelectBox2").empty().append(inHTML);
});
$('#SelectBox2').change(function () {
$("#selectedValues").text($(this).val() + ';' + $("#SelectBox").val());
$('#hidden1').val($(this).val());
});
$('#add').click(function () {
inHTML = "";
$("#SelectBox2 option:selected").each(function () {
if ($("#SelectedItems option[value=" + $(this).val() + "]").length == 0) {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
$("#SelectedItems").append(inHTML);
});
$('#remove').click(function () {
$('#SelectedItems option:selected').remove();
});
});
Fiddle here
Ok to fix your add function just add the following if condition::
if($("#SelectedItems option:contains("+$(this).text()+")").length<=0)
inHTML += '<option value="' + $(this).text() + '">' + $(this).text() + '</option>';
to remove items::
$('#remove').click(function () {
$("#SelectedItems option:selected").each(function () {
$(this).remove();
});
});
here is the example after i updated it jsfiddle
Have a look at this solution:- Using the data attribute to keep track of the items parent list selector and avoiding a loop with the help of this selector and data attribute.
http://jsfiddle.net/pramodsankar007/rMpBv/
$('#add').click(function () {
var itemsToAdd = [];
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var key = $(this).data('key');
if($('#SelectedItems option[value="' + optionVal + '"][data-key="' + key +'"]').length == 0)
{
itemsToAdd.push($(this).removeAttr('selected').clone(true));
}
});
$("#SelectedItems").append(itemsToAdd);
});
});
SEE THE LINK
write if condition as
if($("#SelectedItems option:contains("+$(this).val()+")").length<=0)
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
Then add
$('#remove').click(function(){
$('#SelectedItems :selected').each(function(i, selected) {
$(this).remove();
});
});
Get existing list of options, check if those you're adding already exist, if not, add them:
http://jsfiddle.net/bZXs4/
$('#add').click(function () {
var inHTML = "";
var $opts = $('#SelectedItems').find('option');
$("#SelectBox2 option:selected").each(function () {
var allowItemToBeAdded = true;
var selectedVal = $(this).val();
$opts.each(function(index, element){
if($(this).val() === selectedVal){
allowItemToBeAdded = false;
}
});
if(allowItemToBeAdded){
inHTML += '<option value="' + selectedVal + '">' + $(this).text() + '</option>';
}
});
if(inHTML !== ''){
$("#SelectedItems").append(inHTML);
}
});
try this if you want to prevent the user from adding an option that already exists
$("#SelectBox2 option:selected").each(function () {
if( $("#SelectedItems option[value='"+$(this).val()+"']").length <=0)
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
})
http://jsfiddle.net/j2ctG/8/
Updated the fiddle for remove also.
Really Clean and Simple (works great and only a few lines):
$("#icon_move_right").click(function(){
$("#available_groups option:selected").each(function(){
available_group = $(this).val();
$("#assigned_groups").append("<option value='" + available_group + "'>" + available_group + "</option>");
});
$("#available_groups option:selected").remove()
});
$("#icon_move_left").click(function(){
$("#assigned_groups option:selected").each(function(){
assigned_group = $(this).val();
$("#available_groups").append("<option value='" + assigned_group + "'>" + assigned_group + "</option>");
});
$("#assigned_groups option:selected").remove()
});
$("#icon_move_right_all").click(function(){
$("#available_groups option").each(function(){
available_group = $(this).val();
$("#assigned_groups").append("<option value='" + available_group + "'>" + available_group + "</option>");
});
$("#available_groups option").remove()
});
$("#icon_move_left_all").click(function(){
$("#assigned_groups option").each(function(){
assigned_group = $(this).val();
$("#available_groups").append("<option value='" + assigned_group + "'>" + assigned_group + "</option>");
});
$("#assigned_groups option").remove()
});

Shorten a method. Syntax better practices

I've been learning via jQuery how to shorten things up. I was wondering if this script can be expressed in a less verbose way? I don't like how everything sits on one huge line.
items.push('<li id="' + key + '">' + ' (key: ' + key + ')(value: ' + val.value + ')(type: ' + val.type + ') (range: ' + val.range + ') (clone: ' + val.clone + ') (archive: ' + val.archive + ') (access: ' + val.access + ')</li>')
Assuming that the object will always have the correct key/values:
str = '';
for (var item in val) {
str += '(' + item + ': ' + val[item] + ')';
}
$("<li>").attr('id', key).text(' (key: ' + key + ')' + str);
http://jsfiddle.net/36Nyu/
If items is another element, you can do something like this.
var str;
for(var i in val)
str += '('+ i +': '+ val[i] +')';
$('<li>', {
id: key,
text: str
}).appendTo(items);
You could use jquery tmpl, or similar:
var template = '(key: ' + key + ')(value: {{value}})(type: {{type}}) (range: {{range}}) (clone: {{clone}}) (archive: {{archive}}) (access: {{access}})';
$('<li />').attr('id', key).html($.tmpl(template, val));
Or, use a string.Format equivalent:
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
/* Allow escaping of curly brackets with {{ or }} */
if (m === '{{') { return '{'; } else if (m === '}}') { return '}'; }
return typeof args[n] != 'undefined' ? args[n] : '{' + n + '}';
});
};
var text = '(key: {0})(value: {1})(type: {2}) (range: {3}) (clone: {4}) (archive: {5}) (access: {6})'.format(key, val.type, val.range, val.clone, val.archive, val.access);
Assuming you're appending all of the key/value pairs in the val object, doing something like this would be pretty maintainable:
var liPrefix = '<li id="' + key + '">(key: ' + key + ')',
liSuffix = '</li>',
liData = '';
$.each(val, function(k, v) {
liData += ' (' + k + ': ' + v + ')';
});
items.push(liPrefix + liData + liSuffix);
See demo

Jquery inArray not returning correct value

In Firebug when I rollover the SelectList variable it certainly looks like an array.
if (GroupList != "") {
$('select[name^=DDLColumns1] option').each(function(){
if ($(this).val() != "-1") {
var ItemsArray = $(this).val().split('|');
var DataTypes = ItemsArray[1];
var TestItem = "[" + ItemsArray[0] + "]";
PROBLEM IS HERE---> if (jQuery.inArray(TestItem, SelectList) != -1) {
if(DataTypes == 104)
NewSelectList += " SUM(CAST(" + ItemsArray[0] + " AS INT)) as " + ItemsArray[0] + ",";
else
NewSelectList += " max(" + ItemsArray[0] + ") as " + ItemsArray[0] + ",";
}
}
});
if(NewSelectList.length > 0) {
NewSelectList = NewSelectList.substring(0, NewSelectList.length - 1);
SelectList = NewSelectList;
}
}//end of if GroupList is not empty
What about cleaning up that mess first? Your errors should get clear if you do it.
if (GroupList != "") {
$('select[name^=DDLColumns1] option').each(function() {
if ($(this).val() != "-1") {
var ItemsArray = $(this).val().split('|');
var DataTypes = ItemsArray[1];
var TestItem = "[" + ItemsArray[0] + "]";
if (jQuery.inArray(TestItem, SelectList) != -1) {
if(DataTypes == 104)
NewSelectList += " SUM(CAST(" + ItemsArray[0] + " AS INT)) as " + ItemsArray[0] + ",";
else // <--- why all of a sudden no {}?
NewSelectList += " max(" + ItemsArray[0] + ") as " + ItemsArray[0] + ",";
}
//} //<--- why is commented out? it breaks everything
} //<-- this closes the callback
}); //<-- broken close of the if
if(NewSelectList.length > 0) {
NewSelectList = NewSelectList.substring(0, NewSelectList.length - 1);
SelectList = NewSelectList;
}
} // <---- what is this for? yeah it's broken
PS: Normally variables start with a lowercase letter and classes start with an uppercase one
if($.isArray( SelectList ) == false)
SelectList = SelectList.split(',');

Categories

Resources