how to put if condition in jquery's append function - jquery-ui

i have trapped in a jquery function, all i want is to append some divs using jquery's append function, but the problem is that i want to put some if conditions in this function,
here is my working code without condition
$( "#some-div-container" ).append(
"<div>name 1" +
"<a href=\"#\">" +
"<div id=\"add\">Add</div>" +
"</a>" +
"<div>Available</div>" +
"</div>"
);
i am using jquery's ajax function having some json response, so i want just that, let say if(response == 1) then execute the code inside it, i am trying using condition,
$( "#some-div-container" ).append(
"<div>name 1"
if(response == 1) {
+"<a href=\"#\">" +
"<div id=\"add\">Add</div>" +
"</a>"
}
+ "<div>Available</div>" +
"</div>"
);
is it possible?
Any help will be appreciated, an error occured when i put this condition "my some other javascript function is not defined", works perfect without condition

Build your string beforehand, by using a variable:
var elements = "<div>";
if (someCondition) {
elements += "<a href='#'>some link</a>";
}
elements += "</div>";
Or, a more specific example:
var elements = "<div>name 1";
if(response == 1) {
elements +=
"<a href='#'>" +
"<div id='add'>Add</div>" +
"</a>";
}
elements += "<div>Available</div>";
elements += "</div>";
Then append the resulting string:
$("#some-div-container").append(elements);

You could acheive that in the following manner:
$('#some-div-container').append(
'<div>name 1' +
(response == 1 ? '<div id="add">Add</div>' : '') +
'<div>Available</div></div>'
);
Demo
But I think it would be neater to do something like this
var div = $('<div/>', { text: 'name 1' });
if(response == 1) {
div.append($('<a/>', { href: '#' }).append($('<div/>', { id: 'add', text: 'Add' })));
}
$('<div/>', { text: 'Available' }).appendTo(div);
div.appendTo('#some-div-container');
Demo

Try this :
$( "#some-div-container" ).append(
"<div>name 1"
+ (
response == 1 ?
"<a href=\"#\">" +
"<div id=\"add\">Add</div>" +
"</a>"
:
""
)
+ "<div>Available</div>" +
"</div>"
);

Create different strings based on the value of response, and do a single append() call with the conditioned string.

var html;
html += "<div>name 1";
if(response == 1) {
html += "<a href=\"#\">";
// other code.....
}
$( "#some-div-container" ).append( html );

Related

Jquery UI multicolumn autocomplete change event is not triggered

I am using jquery-ui autocomplete with multicolumn using _renderMenu and _renderItem as per jsfiddle
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function(index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function(index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function(ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function(index, column) {
t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>').data('item.autocomplete', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
return result;
}
});
Change event is triggered if I click outside of autocomplete without selecting any result.
But change event is not triggered when clicking on header(column) and then clicking on outside.
Thanks in advance
I managed to fix the problem, jquery changed the key by which autocomplete saves the item data from 'item.autocomplete' to 'ui-autocomplete-item' so the fix is to change your line:
result = $('<li></li>').data('item.autocomplete', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
to
result = $('<li></li>').data('ui-autocomplete-item', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
Here is a working jsfiddle using jquery 1.10

JQM Check Box Not Styling inside Webview ".trigger('create')"

Here is my javascript code snippet:
<script>
function returnStringForID(param) {
var retStr =
param.replace(/[\. ,:-]+/g, '').replace(/'/g, '')
.replace(/&/g, '').replace(/\(|\)/g, '');
return retStr;
}
$(document).ready(function () {
var chanId = 'Demo';
var fs_dyn = $('#fs_dyn');
var data = ['Sony', 'Pix', 'Max', 'Set'];
var seriesColors = ['#4000E3', '#FFC526', '#FF0000', '#C0504D'
, '#1F497D', '#4BACC6', '#8064A2', '#9BBB59', '#F79646', '#948A54'];
for (var i = 0; i < data.length; i++) {
var checkId = "graphItem_" + i;
var color;
color = seriesColors[i];
var chanId = returnStringForID(data[i]);
var tmp = "";
tmp = "<input type='checkbox' checked='true' class='custom' value='" + data[i]
+ "' id='" + chanId + "' name='" + chanId + "'/>"
+ "<label for='" + chanId + "' style='font-size:12pt;font-weight:bold;color:"
+ color + "'>" + data[i] + "</label>";
fs_dyn.append(tmp);
}
fs_dyn.trigger('create');
});
</script>
Here is the HTML:
<td width='30%' style="vertical-align: top;" id="tdDynamic">
<fieldset data-mini='true' id='fs_dyn'></fieldset>
</td>
This code works perfect if done in raw html. However when inside a webview, checkbox doesn't style.
Also I have used .trigger('create') to style a nested collapsible in the same app which is also inside a webview, but that works fine.
PS: I am using JQM 1.3.1 version, just in case this helps.
Use pageinit event which is equivalent to .ready() or any jQuery Mobile events.
Demo
$(document).on('pageinit', function () {
// code
});
Using .ready() in jQuery Mobile isn't recommended, please refer to this post.

Using JSON to display the data

I am a new to JSON, I am trying to make the menu that can click and display the data.
All the objects are return from the Controller of my asp.net mvc project.
This is my code :
<script language="javascript" type="text/javascript">
function ViewProduct() {
var searchVal = $("#txtsearch").val();
$.getJSON(url, function (data) {
var mainMenu = $("#content ul#navmenu-v");
$.each(data, function (index, dataOption) {
var new_li = $("<li class='level1' id='select_list'><a href='javascript:void(0);' id='" + dataOption.ID + "' class ='selectedcategory'>" + dataOption.Name + "</a>");
mainMenu.append(new_li);
$('a#' + dataOption.ID).click(function () {
var urlGetProByDep = '<%: Url.Content("~/") %>' + "Products/GetProductsByDepList";
t = dataOption.ID;
var data = {};
if (searchVal != "") {
data.depID = t;
data.Q = searchVal;
} else {
data.depID = t;
}
$(".brand_id").empty();
$.getJSON("ProductListing/Index", data, function (product) {
$(".brand_id").empty();
$.getJSON("ProductListing/Index", data, function (product) {
$.each(product.ja, function (index, value) {
$(".brand_id").html( value.Name + "</br>" + value.PictureName + "</br>" + value.ID);
});
});
});
});
}
$(document).ready(function () {
ViewProduct();
});
The other block of menu code works very well , just have a problem with this block of my code above :
$.getJSON("ProductListing/Index", data, function (product) {
$(".brand_id").empty();
$.getJSON("ProductListing/Index", data, function (product) {
$.each(product.ja, function (index, value) {
$(".brand_id").html( value.Name + "</br>" + value.PictureName + "</br>" + value.ID);
});
});
});
It is the block that I take the the object of JSON to display the in my view, but when I click on the menu , It shows only the element at the last of JSON object.
This is my JSON :
{"ja":
[
{"Name":"ABC1","PictureName1":"my image name1","ID":1},
{"Name":"ABC2","PictureName2":"my image name2","ID":2}
]}
Each menu is the department of each product. And if I do not loop the product data in the menu block, I cannot take the ID of the department to query to get the product in each department.
Any idea or question are welcome, Thanks you for taking your time.
You seem to have a copy&paste-error in your code, you will do 2 request to exactly the same url after each other - not even using the results of the first request. I guess you only wanted something like
$(".brand_id").empty();
$.getJSON("ProductListing/Index", data, function (product) {
$.each(product.ja, function (index, value) {
$(".brand_id").html( value.Name + "</br>" + value.PictureName + "</br>" + value.ID);
});
});
But your problem is the .html() method. You are looping over your products, and in each turn you set the html of each .brand_id-element to a new value. So the result you see is what you have set to all elements in the last iteration. What you would need to do is set the HTML of each element on its own, each with a different content.
Yet, instead of emptying the list items and readding new contents to them (maybe the number of your products changes each query request), I'd rather remove all items and append new ones:
$(".brand_id").remove();
$.getJSON("ProductListing/Index", data, function (product) {
var $parent = $("#parent"); // the parent node of the product list
$.each(product.ja, function (index, value) {
$parent.append('<li class="brand_id">' + value.Name + '<br />' + value.PictureName + '<br />' + value.ID + '</li>');
});
});
(edit) ...or, if brand_id really is an id:
var $parent = $("#brand_id").empty();
$.getJSON("ProductListing/Index", data, function (product) {
$.each(product.ja, function (index, value) {
$parent.append('<div>' + value.Name + '<br />' + value.PictureName + '<br />' + value.ID + '</div>');
});
});
You are subscribing to the .click event of the anchor inside a $.each call. But since you have captured the dataOption variable you are using to prepare the AJAX request in a closure, it is obvious that by the time you click on the link, this dataOption variable is already pointing to the last element of the array you are looping over. So you could pass the argument to the click callback like this:
<script type="text/javascript">
function ViewProduct() {
// TODO: There's some url variable used here which is nowhere defined => define it
$.getJSON(url, function (data) {
var mainMenu = $("#content ul#navmenu-v");
$.each(data, function (index, dataOption) {
$(mainMenu)​.append(
$('<li/>', {
'class': 'level1',
// TODO: find an unique id or you get broken HTML
'id': 'select_list',
'html': $('<a/>', {
'href': '#',
'id': dataOption.ID,
'class': 'selectedcategory',
'text': dataOption.Name,
'click': function(arg) {
return menuClick(arg);
}({ dataOption: dataOption })
})
})
);​
});
});
}
function menuClick(arg) {
var urlGetProByDep = '<%= Url.Action("GetProductsByDepList", "Products") %>';
var t = arg.dataOption.ID;
var data = { };
var searchVal = $('#txtsearch').val();
if (searchVal != '') {
data.depID = t;
data.Q = searchVal;
} else {
data.depID = t;
}
$('.brand_id').empty();
var url = '<%= Url.Action("Index", "ProductListing") %>';
// TODO: Are those 2 nested AJAX calls really necessary here?
$.getJSON(url, data, function (product) {
$('.brand_id').empty();
$.getJSON(url, data, function (product) {
$.each(product.ja, function (index, value) {
$('.brand_id').html( value.Name + "</br>" + value.PictureName + "</br>" + value.ID);
});
});
});
}
$(document).ready(ViewProduct);
</script>
Also notice that I have moved the searchVal declaration inside the click callback in order to account for changes of its value between the time the page is loaded and the user actually clicking on the link.

How to get Jquery-ui Autocomplete with Codeigniter to display response text

I have got the autocomplete to work but with errors. How would i format the response code correctly?
Response Code:
{
label: "Label 1",
value: "27"
},
{
label: "Label 2",
value: "18"
},
{
label: "Dave",
value: "25"
},
{
label: "Jacqui Potatoes",
value: "17"
}
Javascript:
$("#account_search .ac_input").autocomplete({
minLength: 0,
source: base_url + "accounts/ac_results/account_name",
dataType: "json",
type: "POST",
}).data( "autocomplete" )._renderItem = function( ul, item ) {
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
return $( "<li></li>" );
};
I think the .data() function is the problem although it is working somehow. I would like to access both the label and value
You've got an error in the _renderItem function (you should call .data on the newly created <li></li>):
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.value + "</a>" )
.appendTo( ul );
};
I also replaced item.desc which did not exist on your JSON response with item.value.
As a sidenote, you may not need to override that function at all. You only need to use it if you want to change the way each item looks in the suggestion list.
Also, make sure to remove that extra comma in the options object. Additionally, the options dataType and type are not valid options anyway:
$("#account_search .ac_input").autocomplete({
minLength: 0,
source: base_url + "accounts/ac_results/account_name"
});
Example (local data source): http://jsfiddle.net/nG8Q4/

Selecting a jquery-ui-tab based on its id instead of its index?

Anyone know why the following does not work?
$.each( data.d, function( index, item ) {
// creates the tabs with custom ids
$( "#tabs" ).tabs( "add", "page.aspx?id=" + item.id, item.name )
.find('>ul>li:last')
.attr('id', 'tab_' + item.id);
// creates the buttons
$( "#buttons" ).append( "<input type='button' id='buttona" + item.id + "' value='" + item.name + "'>" );
// link buttons with tabs
$( "#buttona" + item.id ).live('click', function() {
$( "#tabs" ).tabs( "select" , "#tab_" + item.id );
});
});
I am trying to assign id's to the tabs, then select the tabs using their id's.
The above does nothing when a button is clicked and it returns no errors at all.
It works fine when using the index as shown below, but I need to use an id for various reasons:
$.each( data.d, function( index, item ) {
// creates the tabs
$( "#tabs" ).tabs( "add", "page.aspx?id=" + item.id, item.name );
// creates the buttons
$( "#buttons" ).append( "<input type='button' id='button" + index + "' value='" + item.name + "-" + index + "'>" );
// link buttons with tabs
$( "#button" + index ).live('click', function() {
$( "#tabs" ).tabs( "select" , index );
});
});
You can use the index() method to get the index of the tab from the id of its header:
$("#button" + item.id).live("click", function() {
$("#tabs").tabs("select", $("#tab_" + item.id).index());
});
Since index() is called without arguments in the code above, it will return the index of the element relative to its siblings, i.e. the other tab headers.
you can switch the tabs with the id of the tab:
var $tabs = $("#tabs").tabs();
$("button").click(function() {
$tabs.tabs( "select", "#tabs-6" );
});
It seems to me that .index() returns an index from 1 so that if I have 3 tabs and want to select the third one, I should return :
$("#button" + item.id).live("click", function() {
$("#tabs").tabs("select", $("#tab_" + item.id).index()-1);
});

Resources