I am creating an IPad application using JavaScript and Html. Html for the page design and JavaScript for the functionality. I have a displayBox created using Html and I want to populate this with an array of countries using javascript.
It is currently adding just the first item in the array to the displayBox but the following error is appearing when i debug the application using firefox
EDIT:
I got it working, i had to take off the end of it
BEFORE:
$('#countrySelection').append('<option value="' + this.id + '">' + this.name + '</option>').selectmenu('refresh');
AFTER
$('#countrySelection').append('<option value="' + this.id + '">' + this.name + '</option>');
the .selectmenu('refresh') was causing the error
I have made some updates like adding $(document).ready() handler etc.
var arrayOfCountries = [{"name":"USA","id":1,"active":"Y"},{"name":"CANADA","id":2,"active":"Y"},{"name":"AALAND ISLANDS","id":270,"active":"Y"},{"name":"AFGHANISTAN","id":236,"active":"Y"},{"name":"ALBANIA","id":109,"active":"Y"},{"name":"ALGERIA","id":17,"active":"Y"},{"name":"AMERICAN SAMOA","id":307,"active":"Y"},{"name":"AMMAN","id":111,"active":"Y"},{"name":"ANDORRA","id":112,"active":"Y"},{"name":"ANGOLA","id":54,"active":"Y"},{"name":"ANGUILLA","id":22,"active":"Y"},{"name":"ANTARTICA","id":308,"active":"Y"},{"name":"ANTIGUA","id":113,"active":"Y"}];
$(document).ready(function(){
if ( $('#countrySelection').find('option').length == 0 ){
$.loadingMessage = "Retrieving Countries";
$.showPageLoadingMsg();
$.each(arrayOfCountries, function() {
$('#countrySelection').append('<option value="' + this.id + '">' + this.name + '</option>');//.selectmenu('refresh');
});
$.mobile.hidePageLoadingMsg();
}
});
Related
I'm download data from JSON file and display button with value:
function iterateOverPrzepisy(best) {
$('#listaPrzepisow').html('');
$.getJSON('przepisy.json', function(data) {
for (var x in przepisyDost) {
$('#listaPrzepisow').append(" <div data-role=\"collapsible\"><h2>" + przepisyDost[x].nazwa + "</h2>" +
"<ul data-role=\"listview\" data-theme=\"d\" data-divider-theme=\"d\">" +
"<li>" +
"<h3>Składniki: " + przepisyDost[x].skladniki + "</h3>" +
"<p class='ui-li-desc' style='white-space: pre-wrap; text-align: justify;'>" + przepisyDost[x].tresc + "</p>" +
"<button id='ulubioneBtn' value='" + przepisyDost[x].id + "'>Ulubione</button></li>" +
"</ul>" +
"</div>");
j++;
}
})
}
When I click to button #ulubioneBtn I would like to get value from this button. So I add done to getJSON
}).done(function(data){
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $("button#ulubioneBtn").val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
});
But it's not working. When I click on button Ulubione I always get in console log value = 0
The problem seems to be that you add multiple buttons with the same id. An id of a html element should be unique.
przepisyDost does not appear to be defined at
for (var x in przepisyDost) {
? Try
for (var x in data.przepisyDost) {
Duplicate id's are appended to document at
"<button id='ulubioneBtn' value='" + przepisyDost[x].id
+ "'>Ulubione</button></li>" +
within for loop. Try substituting class for id when appending html string to document
"<button class='ulubioneBtn' value='" + data.przepisyDost[x].id
+ "'>Ulubione</button></li>" +
You could use event delegation to attach click event to .ulubioneBtn elements, outside of .done()
$("#listaPrzepisow").on("click", ".ulubioneBtn", function() {
// do stuff
})
I have created a dummy JSON and executed the same JS with a single change.
In onclick handler instead of getting button I am using $(event.target).
And it is working fine.
Please find the fiddle https://jsfiddle.net/85sctcn9/
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $(event.target).val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
Seems like first object doesn't have any id value.
Please check JSON response returned from server.
Hope this helps you in solving.
A feature was developed in an application by clicking a hyperlink in a table, open a div below with a table, filtering contents, depending on the link.
The link was created dynamically in one jQuery function and had the following attributes:
$("#pending div#list").bind("data_loaded", function (event, records) {
var tableBody = $("tbody", $(this));
for (var index = 0; index < records.length; index++) {
var rowHtml = '<tr id="' + rowid + '"><input type="hidden" name="' + rowid + '" id="' + rowid + '" value="1"/>' +
'<td><a class="populate" id="' + rowid + '" onclick="javascript:clickHandler(' + rowid + ');">' + docid + '</a></td>' +
'</tr>';
tableBody.append($(rowHtml));
}
});
In Mozilla Firefox, it works perfectly fine. However in Chrome I cannot call the clickHandler function.
From the information I find on Google, say Inline JavaScript will not be executed.
You can check here: https://developer.chrome.com/extensions/contentSecurityPolicy
But now comes my difficulty.
I changed my hyperlink to:
'<td><a class="populate" id="' + rowid + '" onclick="clickHandler(' + rowid + ');">' + docid + '</a></td>' +
And I created this jQuery:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById([parameter]).addEventListener('click', function () { clickHandler([parameter]); },false);
});
Can anyone explain how I can pass the parameter rowid for jQuery?
Thanks.
Regards.
Your snippets imply you're using raw DOM manipulation in Javascript rather than JQuery (which is good! it's definitely faster) but since you mention JQuery, that's what I'll be suggesting.
Instead of your addEventListener call above, try
$('div#list').on('click', 'a.populate', function() {
clickHandler($(this).attr('id'));
});
And then remove the 'onclick' attribute in the declarations of the anchor tags too.
This will add an event listener to all anchor tages with a class of 'populate' which will call clickHandler passing a string parameter consisting of that anchor tag's 'id'.
I am calling a javascript which is returning variable
options = '<option value="' + dateVal + '">' + dateText + '</option>' + '<option value="' + dateVal + '">' + dateText + '</option>';
Also my select element has an id="select-value"
and in javascript i am writting
document.getElementById("select-value").value=options; but it is not taking any values nor throwing any error
I have also tried
document.getElementById("select-value").innerHTML=options; but still no luck.
PFB my html code for select
<select name="select-name" id="select-value" ></select>
<script type="text/javascript">
formatSelectedDate();
</script>
I'd suggest to use appendChild instead of innerHTML.
var s = document.getElementById("select-id");
var op1 = document.createElement("option");
op1.setAttribute("value",dateval);
s.appendChild(op1);
...
EDIT: it looks better inside a loop ;)
I'm trying to dynamically add buttons, and add a jQuery listening even to them.
However, I'm having troubles with JavaScript's scoping (at least I think that's it is).
This is pretty much my code:
for (var item in group) {
$('div').append("<input type='button' value='" + item + "' id = 'id" + item + "'>");
$('#id' + item).click(function() {
alert("Hello from " + item);
});
}
Now the problem is that no matter which button I click, the alert inside the event callback always uses the last item.
Now I understand why this is happening (well, roughly :P), but how I can fix it?
one way of achieving this correctly is like so
for (var item in group) {
$('div').append("<input type='button' value='" + item + "' id = 'id" + item + "'>");
(function(item){
$('#id' + item).click(function() {
alert("Hello from " + item);
});
})(item);
}
here is a jsfiddle to demonstrate http://jsfiddle.net/reefbarman/bbP64/
You can use jQuery's $.each method to iterate over the group array in the same way, but this will solve the issue for you:
$.each(group,function(i,v){
$('div').append("<input type='button' value='" + v + "' id = 'id" + v + "'>");
console.log($('#id' + v))
$('#id' + v).click(function() {
alert("Hello from " + v);
});
});
http://jsfiddle.net/ebiewener/byV9X/
I would look in to using the jQuery Delegate function.
http://api.jquery.com/delegate/
That will attach an event handler to a container. All the element events in the container will trickle up to the container and if handled will trigger the event handler.
It works for me: http://jsfiddle.net/bgt89/ but i did change your handler to use closures.
var group = ['asdf', 'rere', 'eeeee']
$(document).ready(function() {
for (var item in group) {
$('div').append("<input type='button' value='" + item + "' id = 'id" + item + "'>");
$('#id' + item).click((function(item) {
return function() {
alert("Hello from " + item);
}
})(item));
}
});
Most of answers above are correct, but unnecessarily verbose. "this" is your friend.
for (item in group) {
$('div').append("<input type='button' value='" + item + "' id = 'id" + item + "'>");
$('#id' + item).click(function() {
alert("Hello from " + this.id.slice(2) );
});
}
The easy ways: pass some event data:
for (var item in group) {
$('div').append("<input type='button' value='" + item + "' id = 'id" + item + "'>");
$('#id' + item).click({item: item}, function(event) {
alert("Hello from " + event.item);
});
}
Or use event.target or this:
for (var item in group) {
$('div').append("<input type='button' value='" + item + "' id = 'id" + item + "'>");
$('#id' + item).click(function(event) {
alert("Hello from " + event.target.id); //or this.id
});
}
I think everything is OK in your code except for using the item variable in the alert() statement.
Since the alert runs long after the for loop has finished, the alert will see the last value for item, not the one you want. If you just want to access the currently clicked on items ID, then you can just get that from the this reference rather than passing it in. Try changing your code to this:
for (var item in group) {
$('div').append("<input type='button' value='" + item + "' id = 'id" + item + "'>");
$('#id' + item).click(function() {
alert("Hello from " + this.id.slice(2));
});
}
Works here in this jsFiddle: http://jsfiddle.net/jfriend00/uyK3m/
Harmen,
Why not you jquery's live function.
It allows you to bind a function to an event on a set of objects with the jquery selector just like $('#button').click() does but also allows new elements that are appended in the future to also work with the click event. This would fit your dynamically requirement.
See the example below. I use the live function to bind click event to all elements that are a class 'testButton'. Then to get the value use the attr('value') on the $(this) because this is the element clicked.
var group = ["Test 1", "Test 2", "Test 3"];
for (var item in group) {
$('div').append("<input class='testButton' type='button' value='" +item+ "'>");
}
$('.testButton').live('click', function(e) {
alert('Hello Im From ' + $(this).attr('value'));
});
Jquery Live Function : http://api.jquery.com/live/
Working Example : http://jsfiddle.net/bbP64/12/
Hope that helps.
How is it possible to get the id of the dynamically generated textboxes using jquery?. I need to fire the TextChanged event for the corresponging textbox. There is no method reference for the textboxes in the code behind.How can i refer to any method in the codebehind on firing the event. Somebody please help. I dont know jquery much. The entire script im using is as as follows:
<script type="text/javascript">
$(init);
function init()
{
$('#test').droppable(// Div Control
{
drop: handleDropEvent
});
$('a').each(function(idx, item) {
$(item).draggable({ cursor: 'move', helper: 'clone' })
});
}
$(function() {
$("#draggable").draggable(); //Nothing to do with this div
});
function handleDropEvent(event, ui)
{
var draggable = ui.draggable;
document.getElementById('test').innerHTML += addColumn(draggable.attr('text')) + '<br>';
}
function addColumn(column)
{
var iHtml;
// This code will generate a checkbox and a textbox. I need to fire the event of thus generated textboxes.
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input type="text" runat="server" id="aln' + column + '"> </div>';
return iHtml;
}
</script>
There's two ways: keep the generated element, or generate an ID when you generate your new element.
a) keep the generated element
This requires that you don't use innerHTML, but create the element (with document.createElement, or with jQuery's $), and then you can use the element directly (no need to call it by ID any more). For instance, with jQuery:
var container = $('#container');
var myDiv = $('<div id="myDiv"/>');
var myCheck = $('<input type="checkbox"/>');
myDiv.append(myCheck);
container.append(myDiv);
b) generate the ID
container.innerHTML = '<div id="myDiv"><input type="checkbox" id="myCheck"/></div>';
// and after this you can get them by ID:
var myCheck = $('#myCheck');
I would just add a class to the textbox in your iHtml then use .live() event
replace your iHtml with this
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input class="myclass" type="text" runat="server" id="aln' + column + '"> </div>';
then add the live event
$('.myclass').live('change', function() {
alert(' Live handler called.');
});
here is a WORKING DEMO