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/
Related
to summarize my problem ... I have made a calendar with contains the from - to date range. Now the selected dates are displayed in a div with a delete button for each. But as the id of the button is the same for all the dates ....it deletes the entire date range. I have attached the screenshot as well.
I also tried taking a loop and giving each date a div so that the Del function will work properly. but I wasn't successful. I will mention code for the same
$(document).ready(function () {
var i = 0;
$.each(between, function (key, value) {
var rest = $('#target').append($('<div id="r' + i +value+ '" class="ansbox">
</div>'));
console.log(between);
var template = '<div id="ChildTarget_' + i + '"><span>key + ":" + "' + value + '"
</span><button id="tr' + i + '" class="target">X</button></div><br></div>';
i++;
$('#target').on('click', function () {
console.log("hola");
$('#target').remove();
You should add click event for the button itself.
var template = `
<div id="ChildTarget_' + i + '">
<span>key + ":" + "' + value + '"</span>
<button id="tr' + i + '" class="deleteButton">X</button>
</div>`;
$(".deleteButton').on('click', function() {
// do deletion here
});
First of all ,
The 'X' button should have different id
$.each(between, function (key, value){
$('#results').append(key+":"+value+'<br>');
$('#results').html(between.join('<button id="result"+key+"" > X </button><br>')
here you can see i am adding key to the Button Id making it unique. Use that id to remove the value, that you dont want. Hope this helps
Hi i m having one page with one textbox named search and one search button. When i'm searching anything for the first time it's showing me the right data but when i'm searching some other things for the next time then the elements which was listed before are also appended below of that new list. Suppose i'm searching state name by k it will give me right list of karnataka, kerala. But if i start to search again by g, it will show me in output as goa,gujrat,karnataka kerala. i tried using refresh option but it still not working. This is my js code
$.each(response.state, function (i, state) {
$('#statelist').append(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});
$("#statelist").listview("refresh");
and this is html
You are using .append() function. It appends whatever you append to the end of the list.
Check this link:
http://api.jquery.com/append/
Try using innerHTML property of the DOM model.
You could add
If(!('#statelist').html() == ""){
$(this).remove();
//execute rest of code that appends state list
}
Then do an else statement and execute your append code without removing()
UPDATE: a better option is to do this-
$.each(response.state, function (i, state) {
$('#statelist').html(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});
HTML:
<input value='Rename' type='button' onclick='RenameGlobalPhase({$row['id']});'
<span id='renameGlobalPhase{$row['id']}'>" . $row['phase'] . "</span>
Here is my JS code:
function RenameGlobalPhase(id)// {{{
{
var phase = $('#renameGlobalPhase' + id).html();
$('#renameGlobalPhase' + id).replaceWith("<input id='#renameGlobalPhase" + id + "' type='text' onblur='SaveNewPhaseName(" + id + ");' value='" + phase + "' />");
$('#renameGlobalPhase' + id).focus();
} // }}}
function SaveNewPhaseName(id)// {{{
{
var newPhase = $('#renameGlobalPhase' + id).val();
alert(newPhase);
$('#renameGlobalPhase' + id).replaceWith('<span>' + newPhase + '</span>');
} // }}}
So when user clicks the input button above, I turn a span next to it into an input field so user can rename the value. And in onblur (newly created from jQuery for that new input field), I want to save the new value and return back to span.
The alert shows an undefined value. Can anyone see what is wrong?
Remove the # from the id
Change
.replaceWith("<input id='#renameGlobalPhase" + id + "'
to
.replaceWith("<input id='renameGlobalPhase" + id + "'
fiddle
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">'.
I've got a problem with another dojo enabled form that I am working on. A user can enter details onto the page by entering the data using a dialog box, which in turn updates the database and then displays the user data entered on to the form.
Each element added consist of 2 x Validation Text boxes 1 x FilteringSelect. When it's added to the page they are added as simply text boxes.
I've tried just adding as standard strings but that means the dojo.parse() does not run on the code. I've also tried programmatically adding the elements but that just displays the element object as a string to the page. So far I have:
var xhrArgs = {
url: url,
handleAs: "text",
preventCache: true,
load: function(data){
var idResult = parseInt(data);
if(idResult > 0){
var divStr = '<div id="employ_' + idResult + '" style="float:left;width:100%;">' +
'<table width="300">' +
'<tr>' +
'<td height="29"><Strong>' +
'<input type="text" dojoType="dijit.form.ValidationTextBox ' +
'change="markEmploymentForUpdate(); ' +
'id="cmpy_'+ idResult +'" '+
'required="true" ' +
'promptMessage="Please enter a valid company name" ' +
'invalidMessage="please enter a valid company name" ' +
'trim="true"' +
'value="'+ companyname +'"/>' +
'</td>' +
'<td height="29"><input dojoType="dijit.form.FilteringSelect" store="rolestore" searchAttr="name" name="role" onchange="markEmploymentForUpdate();" id="roleInput_'+ idResult +'" value="'+ jobrole +'" ></td>' +
'<td height="29">' +
'<input type="text" dojoType="dijit.form.ValidationTextBox" onchange="markEmploymentForUpdate();"' +
'id="jtitle_'+ idResult + '"' +
'required="true"' +
'promptMessage="Please enter your job title"' +
'invalidMessage="Please enter your job title"' +
'value="'+ jobtitle + '"/>' +
'</td>' +
'<td height="29"><img src="/images/site/msg/small/msg-remove-small.png" border="0" onmouseover="this.style.cursor=\'pointer\';" onclick="removeEmployer(\'employ_'+ idResult +'\', '+ idResult +')" /></td>' +
'</tr>' +
'</table>' +
'</div>';
dijit.byId('companydetails').hide();
dijit.byId('employername').setValue('');
dijit.byId('jobtitle').setValue('');
dijit.byId('jobrole').setValue('');
dojo.byId('data-table').innerHTML += divStr;
dojo.byId('companydetails').hide();
}else{
dojo.byId('add-error').innerHTML = '<div class="error">Unable to process your request. Please try again.</div>';
}
}
};
var deferred = dojo.xhrGet(xhrArgs);
This is displaying text boxes as the dojo.parse isn't running on this. If I replace the ValidationTextBox with:
var textbox = new dijit.form.ValidationTextBox({
id:"cmpy_" + idResult,
required:true,
trim:true,
"change":"markEmploymentForUpdate();",
promptMessage:"Please enter a valid company name",
value:companyname
});
I just get the object printed to the page.
Any ideas how I can added this to my page and maintain the dojo component rather than it defaulting to a text box?
Many thanks.
dojo.parser.parse(dojo.byId('data-table')); after you set it's innerHTML