Calling multiple functions to generate textboxes on same page - javascript

I am calling two separate functions to generate dynamic textboxes one of the function works fine whereas other doesn't work though the code for generating textboxes is same except the variables names and label names. Could anyone please let me know what I am doing wrong and how can i figure out this ?
this is the function which is not working.
var C = 3;
var matrixArray = ["question", "mrank"];
$("#addMatrix").click(function () {
for(var j = 0; j < matrixArray.length; j++){
createMatrixInput(MatrixArray[j]);
}
C++;
});
function createMatrixInput(l){
var tb_Div = $('#TextBoxes');
var mstr = '<div class="control-group">';
mstr += '<label class="control-label">' + l + " " + C + '</label>';
mstr += '<div class="controls">';
mstr += '<input type="text" id="' + l + '_' + C + '" name="'+ l +'_' + C + '" />';
mstr += '</div>';
mstr += '</div>';
tb_Div.append(mstr);
};
this is my jsfiddle with complete code.
http://jsfiddle.net/qqqyC/2/

There are 2 problems. The button id is addmatrix and the array is matrixArray, not MatrixArray. The method should look like:
$("#addmatrix").click(function () {
for(var j = 0; j < matrixArray.length; j++){
createMatrixInput(matrixArray[j]);
C++;
}
});

I've spotted a error in your JSFiddle see the id of your button "matrix button" it is addmatrix and you are binding the onClick event to addMatrix and javascript event binding via ID is case sensitive, so the event will not be bind.
Maybe this will solve your whole problem, because it was preventing to execute the click event.

Related

print array of object in javascript and print in html tags

i am using storelocater.js for multiple location in google map and show the information according to the location with image. i can show only one image but i want to show multiple images inside the information panel. link this
Here is my code
var panelDiv = document.getElementById('panel');
storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">The nearest outlet:</li>';
var Store = storeLocator.Store;
Store.prototype.generateFieldsHTML_ = function(fields) {
var html = '';
html += '<div class="store-data">';
if(this.props_['title']){
html += '<div class="title"><div class="img-list clearfix">' +
for (var i = 0; i <= this.props_[images].length; i++) {
console.log(this.props_[images[i]]);
// <img src=' + this.props_['images'] + '>
}
+ '</div></div>'
}
html += '</div>';
return html;
}
var data = new storeLocator.StaticDataFeed;
data.setStores([
new storeLocator.Store('store02', new google.maps.LatLng(27.67663,85.31093), null, {images: ["img/thapathalil.jpg","img/thapathalil.jpg","img/thapathalil.jpg"]})
]);
and it shows:
Uncaught SyntaxError: Unexpected token for...
how can i solve this?? how can i fetch location inside of "images"
THANKS in advance
Actually you got Uncaught SyntaxError: Unexpected token for... because you used the for..loop in the string concatenation statement, directly after the + sign.
Change this code :
html += '<div class="title"><div class="img-list clearfix">' +
for (var i = 0; i <= this.props_[images].length; i++) {
console.log(this.props_[images[i]]);
// <img src=' + this.props_['images'] + '>
}
+ '</div></div>'
To the following:
html += '<div class="title"><div class="img-list clearfix">';
for (var i = 0; i <= this.props_['images'].length; i++) {
console.log(this.props_['images'][i]);
html += '<img src=' + this.props_['images'][i] + '>';
}
html += '</div></div>'
Note:
You should separate the concatenation of strings to the html
variable and the for loop logic, using html += instead of just using concatenation with + sign on multiple lines.
Make sure to wrap the properties names between two '' while accessing your objects, like in this.props_[images] where it should be this.props_['images'] and in this.props_[images[i]] where it should be this.props_['images'][i].
And the first 2 lines of your html variable decalaration and the concatenation, var html = ''; html += '<div class="store-data">'; can be shortened to just var html = '<div class="store-data">';.
I think there is a typo. Change this:
console.log(this.props_[images[i]])
to
console.log(this.props_['images'][i])
And you should use
i < this.props_['images'].length
So try this:
for (var i = 0; i < this.props_['images'].length; i++) {
console.log(this.props_['images'][i]);
}

JQUERY DataTables - Keep Table stying on print

I am trying different ways to keep the table styling when I print a data table. I am well aware that data tables currently strips all table styling except the main table class. I have began trying a few different things and modifying the buttons.print.js file in order to achieve this.
var a = c.buttons.exportData(d.exportOptions),
k = function (b, a) {
for (var c = '<tr class="' + (this).className + '">', d = 0, e = b.length; d < e; d++) c += "<" + a + ">" + b[d] + "</" + a + ">";
return c + "</tr>"
},
This returns as undefined for the classes...has anyone had any luck out there...or have any tips or examples of what I am trying to achieve?
Also here is the link for the complete buttons.print.js file that I am working with: LINK
Myself and my colleague figured this out for anyone that would like to retain classes/styling for the tables when they are trying to print...
var a = c.buttons.exportData(d.exportOptions),
counter = [];
k = function (b, a) {
if(a != 'th') {
counter.push(a);
}
for (var c = "<tr class=" + $('tr:nth-child(' + counter.length + ')').attr('class') + ">", d = 0, e = b.length; d < e; d++) c += "<" + a + ">" + b[d] + "</" + a + ">";
return c + "</tr>"
},
One thing to note is that this will only work correctly if one data table is on the screen...still working out a way to support multiple tables correctly...

jquery append() works in chrome debugger and on IE, but not in Chrome

I have a strange situation where my code works in the debugger (Chrome), and also work on IE 9, but doesn't work in chrome, and in Firefox. All I'm trying to do is to append a bunch of list elements to a list.
HTML:
<div id="FriendSelector">
<ul></ul>
</div>
JS:
var friends = []; //this gets loaded with about 600 friend objects (name, icon, id) earlier
function openFriendSelector() {
var $friendSelector = $('#FriendSelector');
$friendSelector.show();
bindFriends();
}
function bindFriends() {
var $list = $('#FriendSelector ul');
for (i = 0; i < friends.length; i++) {
var friend = '<li id="' + friends[i].id + '"><div><img src="' + friends[i].icon + '" class="avatar"/>' + friends[i].name+ '</div></li>';
$list.append(friend);
}
}
When I click the button that opens the FriendSelector DIV (initially hidden), I see a blank DIV, however, if I close the popup and re-open it, the friends are there...
Any help is appreciated.
Found the issue. The array was taking a few seconds to get loaded (via ajax). So, after the page loads, if I wait a couple seconds and then open the div, it works. Which explains why it worked in the debugger.
Try to avoid so many .append() calls at once, so replace your following code:
for (i = 0; i < friends.length; i++) {
var friend = '<li id="' + friends[i].id + '"><div><img src="' + friends[i].icon + '" class="avatar"/>' + friends[i].name+ '</div></li>';
$list.append(friend);
}
for this one:
for (i = 0, friend=''; i < friends.length; i++) {
friend +='<li id="' + friends[i].id + '"><div><img src="' + friends[i].icon + '" class="avatar"/>' + friends[i].name+ '</div></li>';
}
$list.append(friend);
UPDATE:
Try to load friends prior to showing the div, like this:
function openFriendSelector() {
bindFriends();
}
function bindFriends() {
var $list = $('#FriendSelector ul');
for (i = 0, friend = ''; i < friends.length; i++) {
friend = '<li id="' + friends[i].id + '"><div><img src="' + friends[i].icon + '" class="avatar"/>' + friends[i].name+ '</div></li>';
}
$list.append(friend);
$list.parent().show();
}

Strange for-loop behavior in Javascript

I have next problem: arr has only two elements. Next loop tries to execute his body 3 times:
var selectHTML = "";
for (var i = 0; i< arr.length; i++) {
selectHTML += '<option value="' + arr[i].id + '">' + arr[i].name + '</option>';
}
Next loop tries to execute his body only 2 times as I expect:
var selectHTML = "";
for (var i = 0; i< arr.length; i++) {
alert(i);
selectHTML += '<option value="' + arr[i].id + '">' + arr[i].name + '</option>';
}
Why (tested in Firefox 14.0.1)?
Updated: sorry for the semicolon after counter increment, it's a typo. But the code still doesn't work event without it.
Updated: Ok, this code was simplified. Whole code itself:
var selectHTML = "";
timeSheet.steps = [ { name:"Leave as is", id:-1}, { name:"Approved", id:2} ];
for (var counter = 0; counter < timeSheet.steps.length; counter++) {
selectHTML += '<option value="' + timeSheet.steps[counter].id + '">' + timeSheet.steps[counter].name + '</option>';
}
In Firebug I can see that timeSheet.steps.length equals 2. By the way, instead of placing "alert(i)" I've added a comment and body executes 2 times. Magic...
You have an extra semicolon in the loop
for (var i = 0; i< arr.length; i++;) {
Try it without:
for (var i = 0; i< arr.length; i++) {
This works fine for me (Tested in Firefox 14.0.1):
var arr = [{id:1, name: 'test2'}, {id:2, name: 'test2'}];
var selectHTML = "";
for (var i = 0; i< arr.length; i++) {
selectHTML += '<option value="' + arr[i].id + '">' + arr[i].name + '</option>';
}
console.log(selectHTML);
var selectHTML = "";
for (var i = 0; i< arr.length; i++) {
selectHTML += '<option value="' + arr[i].id + '">' + arr[i].name + '</option>';
}
console.log(selectHTML);
Returns
<option value="1">test2</option><option value="2">test2</option>
<option value="1">test2</option><option value="2">test2</option>
Please elaborate what you meant by the body running three times. If your array contains only 2 elements, when i == 2, arr[i] is undefined and hence accessing id and name will throw an error.
If this is what is happening, then at some point in the looping, the length of the array is being modified with/without an element being added.
Issues that fixed by adding an alert are usually timing issues. See this section on Alerts
Alert boxes (and the related confirm and prompt-boxes) have some
strange properties.
They are synchronous in the sense that the script that initiates the
dialog is suspended until the dialog is closed. The script waits for
the alert()-function to return before it continues.
The tricky part is that some browsers allow events to be dispatched
while the dialog is visible and waiting for some user action. This
means that while one script is suspended, waiting for the alert
function to return, another function might be executed as part of a
different event dispatch.
User interface events like mouseup and click will not fire during the
alert, as the alert is modal and captures all user input, but
non-user-initiated events like page load, timeout handlers, and
asynchronous XMLHttpRequest return handlers, might fire.
You have not shown code that modifies the arr variable. Chances are you have a ajax call some where that is modifying the arr. In the first code sample there is no alert, so maybe the entire for loop gets over before the ajax success handler fires. In the second sample, the alert prevents the for loop from executing till you discard the alert. In the time it took for you to discard it, the ajax success handler must have fired.
Please share all relevant code that modifies the arr variable.

Jquery help needed- infinite loop?

i have a problem with this code:
var par = [];
$('a[name]').each(function() {
if (($(this).attr('name')).indexOf("searchword") == -1) {
par.push($(this).attr('name'));
$('.content').empty();
for (var i = 0; i < par.length; i++) {
$(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
}
}
});
It causes ie and firefox to popup the warning window "Stop running this script". But it happens only when there is a very very large amount of data on page. Any ideas how to fix it?
Your code should look like this:
var par = [];
$('a[name]').each(function() {
if (($(this).attr('name')).indexOf("searchword") == -1) {
par.push($(this).attr('name'));
}
});
$('.content').empty();
for (var i = 0; i < par.length; i++) {
$(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
}
There is no reason for the second loop to be inside the first - that will just cause a lot of unneeded work.
You can make this code a bit simpler by removing the par array and the second loop, and just creating the content inside the first loop:
$('.content').empty();
$('a[name]').each(function() {
var name = $(this).attr('name');
if (name.indexOf("searchword") == -1) {
$(".content").append('<a id="par" href="#' + name + '">' + name + '</a><br />');
}
});
Browsers run all javascript (and most page interaction) on a single thread. When you run a long loop like this with no interruptions, the UI is totally frozen. You should try to make your algorithm have to do less, but in case that's not possible you can use this trick where you do a bit of work, then pause and give the browser control of the UI thread for a bit, then do more work.
var $targets = $('a[name]');
var current = 0;
var i = 0;
function doSomeWork() {
if (i == $targets.length) return;
var $t = $targets[i];
if (($t.attr('name')).indexOf("searchword") == -1) {
par.push($t.attr('name'));
$('.content').empty();
for (var i = 0; i < par.length; i++) {
$(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
}
}
i++;
window.setTimeout(arguments.callee, 0);
}
This does one iteration of your loop in a function before yielding. It might be a good idea to do more than just one in a function call, but you can experiment with that. An article on this idea: http://www.julienlecomte.net/blog/2007/10/28/

Categories