What I'm trying to do here is make one function that does all the functionality for a custom select element. So I made a function that accepts three parameters which are defined in the function itself (see code below for more detail). I'm trying to accomplish the following: I want the parameters to be the IDs of the various elements (the wrapper div for example), and I want those parameters to be dropped in the function. My Code is below. Thanks so much
function createList(ParentDivID,SelectMenuID,ListMenuID) {
$('#' + ParentDivID + "'");
$('#' + SelectMenuID + "'");
$('#' + ListMenuID + "'");
var options = $("#" + SelectMenuID +'"' ).find("option");
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + "></ul>";
$('#' + ParentDivID + "'").append(ul).end().children('#' + ListMenuID + "'").hide().click(function(){$(ul).slideToggle();});
$("#" + SelectMenuID + '"').hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi);
At a guess, it is probably because your ids don't end in quote characters (which aren't allowed in ids in HTML 4), but you are appending them to the strings you are searching for with jQuery.
You only need to do your selectors like this
$('#' + ParentDivID);
Also you need to stop interchanging 's and "s because it is causing you to miss some closing quotes
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $('#' + SelectMenuID).find('option');
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + '"></ul>';
$('#' + ParentDivID).append(ul).end().children('#' + ListMenuID).hide().click(function(){$(ul).slideToggle();});
$('#' + SelectMenuID).hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi); `
You are messing up all of your string concatenations like:
$('#' + ParentDivID + "'"); should be $('#' + ParentDivID);
It's generally a bit of a mess but I've tried to fix as much as possible.
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $("#" + SelectMenuID).find("option");
var ul = $('<ul>', {id: ListMenuID});
$(options).each(function(){
ul.append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
$('#' + ParentDivID)
.append(ul)
.end()
.children('#' + ListMenuID)
.hide()
.click(function() { ul.slideToggle(); });
$("#" + SelectMenuID).hide();
}
When you call the function, are the three parameters already variables assigned elsewhere in your code? If not, and the are actually the string id attributes, you need to enclose them in quotes.
createList("fancySelectLarge", "selectWalkerType", "walkerTypeLi");
Note: See other valuable responses about the incorrect quoting in $('#' + ParentDivID + "'");
$(ul) is undefined when execution reaches it, because var ul is only declared a few lines later on. You will also need to use document.body.createElement('ul') instead of putting '<ul ...>' in a string.
Also, the lines $('#' + ParentDivID + "'"); don't do anything.
You need to define ul before using it. Also, define it as $('<ul.../>') not just '<ul.../>', so that you can create a jQuery element from that definition.
and you want also try to create the dom element like this
$('<span class="value">') instead of a string value '<span class="value">'.
Related
<a class="click_' + module_row + '_' + element + '_on">Show</a>
<div class="div_' + module_row + '_' + element + '_show">div content</div>
$('.div_' + module_row + '_' + element + '_show').hide();
$('.click_' + module_row + '_' + element + '_on').click(function(){
$('.div_' + module_row + '_' + element + '_show')
.fadeIn('slow')
.show('slow')
});
I trying to show dynamically a div content via JavaScript. But not working.
I'm guessing that you are adding it dynamically via JavaScript, if that is the case you should use:
$(document).on('click','.click_' + module_row + '_' + element + '_on',function () {
// hide here, that is simple
});
Edit 1) DO you have module_row and element defined? I'm thinking that is the problem. Tell us more about those selectors?
Edit 2) Since you told me that module_row and elements are numbers, you should use different syntax. Use php to put module_row and element in attribute. Code HTML:
<a class="div_show" data-module="module_row" data-element="element">div content</div>
Code JS:
$(document).on('click','.click_on',function (e) {
// not to reload the page
e.preventDefault(e);
var module = $(this).attr('data-module');
var element = $(this).attr('data-element');
$('div_' + module + '_' + element + '_show').hide()
});
You might need to tweak it around little more, but thats it
weird little bug I can't figure out, I have the following line:
$("#ingredientlist").append('<li>' + value + ' parts ' + capitalize(index + '') + '</li>').css("color", curColor);
Basically, in a previous statement I get curColor, which is different depending on what value I'm on. I checked the colors and they're different each time. I want each <li> to be styled to a specific color, so I tried setting the .css() to that, but all my entries are the same color. Any ideas?
Thanks
Currently you are appending li to $("#ingredientlist") then setting its color
You need to set color of li not its parent.
Use
$("#ingredientlist").append(
$('<li></li>')
.text(value + ' parts ' + capitalize(index + ''))
.css("color", curColor)
);
The issue is because append() returns the parent element, not the one which was appended. This means that your code is actually setting the color of the #ingredientlist element, not the li. Try this instead:
$('<li />', { text: value + ' parts ' + capitalize(index + '') })
.css('color', curColor)
.appendTo('#ingredientlist');
You're applying the .css call to the #ingredientlist set, not the li you're appending.
Instead:
$("#ingredientlist").append($('<li>' + value + ' parts ' + capitalize(index + '') + '</li>').css("color", curColor));
// Changes -----------------^^-------------------------------------------------------------------------------------^
Breaking that up into parts just to make it clearer:
var $li = $('<li>' + value + ' parts ' + capitalize(index + '') + '</li>');
$li.css("color", curColor);
$("#ingredientlist").append($li);
I have a modal dialog (Bootstrap) that has a list-group with custom list-group-items inside of it (populated by loop using append after adding data from my server).
Inside each list-group-item, I have a Checkbox that will be used to "select" the result. As I populate the items, I hook up the JQuery click event to the respective Checkbox:
// Add to search results
$('#search-results').append(
'<a id="centroid-list-item-' + featureAttrs['ObjectID'] + '" href="\\#"' + 'class="list-group-item" style="outline: 0">' +
'<table style="background: transparent">' +
'<tr>' +
'<td>' +
'<input id="centroid-checkbox-' + featureAttrs['ObjectID'] + '" type="checkbox" value=""> ' +
'</td>' +
'<td>' +
'<h4 class="list-group-item-heading">' +
featureAttrs['UNIQUEID'] +
'</h4>' +
'<p id="centroid-item-text-' + featureAttrs['ObjectID'] + '"' + 'class="list-group-item-text">' +
featureAttrs['NAME'] +
'</p>' +
'</td>' +
'</tr>' +
'</table>' +
'</a>'
);
// When the DOM is ready, add event
$(document).ready(function () {
$('#centroid-checkbox-' + featureAttrs['ObjectID']).click(function (event) {
var objectId = $(this).attr('id').replace(/^\D+/g, '');
console.log(objectId + " was clicked");
if ($(this).is(':checked')) {
// Enable the 'Set Target' button
$('#btn-set-target').removeAttr('disabled');
// Disable all other choices
$('[id^="centroid-checkbox-"]').each(function (event) {
console.log("Picked up values for checkboxes");
if ($(this).attr('id') != ('centroid-checkbox-' + objectId)) {
$(this).attr('disabled', true);
}
});
}
else {
$('#btn-set-target').attr('disabled', 'disabled');
// Enable all text boxes
$('[id^="centroid-checkbox-"]').each(function () {
if (this.attr('id') !== ('centroid-checkbox-' + objectId)) {
this.removeAttr('disabled');
}
});
}
});
});
The problem I am having is that when I call $('[id^="centroid-checkbox-"]') it is returning undefined. However, at the time is gets called, there are about 30 "centroid-checkbox-XXXXX" checkboxes. What am I doing wrong here?
The $ function never returns undefined.
But this in the callback you pass to each is an element, not a jQuery object.
Which means you must use this.id instead of this.attr('id') and $(this).removeAttr('disabled') instead of this.removeAttr('disabled') (and you probably want this.disabled=false or $(this).prop('disabled', false)).
objectId never gets defined because you need to quote enclose the regular expression you're using for replace():
var objectId = $(this).attr('id').replace(/^\D+/g, '');
should be:
var objectId = $(this).attr('id').replace('/^\D+/g', '');
DEMO: http://jsfiddle.net/4fUvn/8/
I have the following code:
$("#stats-list")
.append("<li>Elapsed: " + ajaxElapsed + "</li>\n" +
"<li>Display: " + tableElapsed + "</li>\n" +
"<li>Total: " + (ajaxElapsed + tableElapsed) + "</li>");
This was originally three appends that I concatenated into one. Is there anything I could do with jQuery that would clean up this code even more. What I was wondering was if jQuery has any string formatting with tokens that I could use.
function format(formatString) {
var args = Array.prototype.slice.call(arguments,1);
return formatString.replace(/\{(\d+)\}/g, function(match, num) {
return args[Number(num)];
});
}
format("<li>Elapsed: {0}</li>\n<li>Display: {1}</li>\n<li>Total: {2}</li>",
ajaxElapsed, tableElapsed, ajaxElapsed + tableElapsed);
afaik there is none built-in, but a powerful templating-subsystem, see jQuery Templates
just for completeness, i think this could be done more elegant:
var list = $('#stats-list');
$('<li />').text('Elapsed: ' + ajaxElapsed).appendTo(list);
$('<li />').text('Display: ' + tableElapsed).appendTo(list);
$('<li />').text('Total: ' + (ajaxElapsed + tableElapsed)).appendTo(list);
If you have many items you can do something like this to avoid missing + and writing li so many times. You can add any number of items inside the array and they will be joined with lis appropriately.
var list = '<li>' + [
'Elapsed: ' + ajaxElapsed,
'Display: ' + tableElapsed,
'Total: ' + ajaxElapsed + tableElapsed
].join('</li><li>') + '</li>';
$("#stats-list").append(list);
As a note I wouldn't use \n. li is a block element by default, so you'd be better styling it with css.
I'm having a bit of a problem escaping quotes in the following example:
var newId = "New Id number for this line";
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction("#my' + newId + '");"></td>');
The issue is that when I look at the generated code the id does update to id="myNewId", but in the function call it looks like this:
onkeyup="runFunction(" #row2="" );=""
What exactly am I doing wrong?
Just don't put JavaScript into the HTML string:
$(id).html(
'<td><input type="text" id="my' + newId + '"></td>'
).find("input").keyup( function() {
runFunction("#my" + newId);
});
Thinking about it, in this special case you can exchange the keyup() function body for:
runFunction(this);
because you seem to want to run the function on the object itself.
You need to use HTML character references for HTML attribute values. Try this:
function htmlEncode(str) {
var map = {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"};
return str.replace(/[&<>"']/g, function(match) { return "&" + map[match] + ";"; });
}
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="' + htmlEncode('runFunction("#my' + newId + '");') + '"></td>');
You forgot to escape the attribute's quotes.
var newId = "New Id number for this line";
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction(\'#my' + newId + '\');"></td>');
You should use escaped single quotes \' to surround the #my... part.