Pressing a button in the list of JQM - javascript

I have a list of JQM, and a button for each instance on a list.
When click on the button I call to function ...
function xxx()
{
alert ('click on me!! :]');
}
Clicking on the button Not triggering the function, why?
Look at the following jsFiddle: http://jsfiddle.net/Hodaya/nR369/3/

To bind the xxx function to the click event of the newLI DOM element you should either use the newLI.onclick=xxx; or better yet use jQuery to do the binding with $(newLI).click(xxx);

Finally the problem is resolved:
Pressing the button did not work because:
to each button on the list was the same id ,In the moment I added a unique name for each of the buttons, it worked.
Here the code:
for (var i = 0; i < Local.length; i++) {
newLI.innerHTML = '<a href="to.html" data-transition="slide" dir="rtl" onclick="YYY();" >' +
'<p>...'</p>' +
'<a id="btnClearOneBookmark' + i + '" data-role="button" data-icon="delete" data-theme="b"></a>' +
' </a>';
$("#btnClearOneBookmark" + i).click(function () { xxx(); });
}

Try this:
$("#mybutton").on('click',function() {
var ul = document.getElementById("bookMarkMenu");
for (var i = 0; i < 5; i++) {
var newLI = document.createElement("LI");
console.log(i)
newLI.innerHTML = '<p>...</p>' +'<a id="btnClearOneBookmark" data-theme="b" data-role = "button"></a>';
newLI.setAttribute('data-theme', 'c');
newLI.setAttribute('onclick', 'DisplayBookMark()');
ul.appendChild(newLI);
$('ul').listview('refresh');
}
});
$("#btnClearOneBookmark").live('click',function() {
alert("click on me!! :]");
});

Related

How to set a css property to an html element that i get as a string

I generate an html table using javascript and jquery.
One of the row cells has an anchor element, that I append to table as a string var deleteLink = "Delete"
I need to set an event listener to the generated element, but don't know how to select it
I can't pass deleteLink as a string like this
$(deleteLink).on("click", function () {
//call fucntion
});
I'm trying to set a unique id to the generated links, but I also need to know how to select them first. Please help
This's how I generate the html table.
Please note that each delete link should only trigger the row it belongs to.
function appendToDigitalMapTable(docId) {
tbl = document.getElementById('digitalMapTable');
var selectedDigitalMap = $("#DigitalMapTypeId option:selected").text();
var deleteButton = "<a href='#'>Delete</a>";
addRow(tbl, selectedDigitalMap, deleteButton, docId);
}
function deleteUploadedDoc(docIdAssociatedToRow) {
console.log("deleteUploadedDoc function is called. docId = " + docIdAssociatedToRow);
//ajax call to backend function
}
function addCell(tr, val) {
var td = document.createElement('td');
td.innerHTML = val;
tr.appendChild(td)
}
function addRow(tbl, val_1, val_2, docId) { 2
var tr = document.createElement('tr');
var docIdAssociatedToRow = $(tr).data("documentID", docId)
//selected digitalMapType text
addCell(tr, val_1);
//delete row
addCell(tr, val_2);
//val_3 is "<a href='#'>Delete</a>"
//attach eventListener to this element
$(val_3).on("click", function () {
deleteUploadedDoc(docIdAssociatedToRow);
});
tbl.appendChild(tr)
}
Option 1: return the row from addRow then find the delete button in that row to add the event handler:
function addRow(...) {
...
return tr;
}
var tr = addRow(...);
var delbutton = $(tr).find("a")
// not clear if you question is for css or event handler, asks both
delbutton.css("color", "red").click(function() { handleRowDeleteEvent(); });
this assumes you only have one button/anchor, mitigated using a class
var delbutton = $(tr).find("a.del-button")
(as an aside, it should be a <button type='button' not <a> as it's an action, not a link, so I've used <button> below)
Option 2: use event delegation
$("#digitalMapTable").on("click", "a", handleRowDeleteEvent);
again, assumes you have a single button for delete, not for edit etc, but this can easily be mitigated by adding a class to your buttons when you create them, eg:
var deleteLink = "<button type='button' class='delete-button'>delete</button>";
$("#digitalMapTable").on("click", "button.delete-button", handleRowDeleteEvent);
Option 3: use onclick=
var deleteLink = "<button type='button' onclick='handleRowDeleteEvent'>delete</button>";
not recommended for numerous reasons that I'll leave you to research
How to ensure your button only works on the row it needs to - use this:
function handleRowDeleteEvent() {
var btn = $(this);
var row = btn.closest("tr");
var docId = row.data("documentID");
deleteUploadedDoc(docId);
}
or, all in one line:
function handleRowDeleteEvent() {
deleteUploadedDoc($(this).closest("tr").data("documentID"));
}
You can give your anchor element an unique id and later use Jquery's # selector to select that particular element.
var counter = 1;
var deleteLink
for (var a = 0; a < 2; a++) {
deleteLink = "<a href='#' id='myLink" + counter + "'>Delete </a>";
document.body.innerHTML += deleteLink;
counter++;
}
$('#myLink1').on("click", function() {
console.log("clicked")
});
$('#myLink2').on("click", function() {
console.log("other clicked")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to clear table inside a dialog when dialog is closed

When the button is clicked, 2 sets data is added. I use material design.
Button needs 2 clicks to run function for first time. Due to this, the data is added to table 2 times.
Code
HTML
<button onclick="purchaseList(orderid)" id="dialog">Button</button>
JS
function popup(listid) {
var starCountRef = firebase.database().ref('Orders/' +
listid).child('foodItems');
starCountRef.on('child_added', snapshot => {
var snaps = snapshot.val();
var itemPrice = snaps.price;
var itemName = snaps.productName;
var itemQuantity = snaps.quantity;
console.log(itemName);
$("#producttable").append(
'<tr><td class="mdl-data-table__cell--non-numeric">' + itemName +
'</td><td>' + itemQuantity + '</td><td>' + itemPrice + '</td></tr>'
);
});
var dialog = document.querySelector('dialog');
var showDialogButton = document.querySelector('#dialog');
if (!dialog.showModal) {
dialogPolyfill.registerDialog(dialog);
}
showDialogButton.addEventListener('click', function() {
dialog.showModal();
});
dialog.querySelector('.close').addEventListener('click', function() {
var element = document.getElementById("producttable")
while (element.lastChild) {
element.removeChild(element.lastChild);
}
dialog.close();
});
}
This should work:
var element = document.getElementById("producttable")
while (element.lastChild) {
element.removeChild(element.lastChild);
}
Add this as necessary.
I suggest you change your firebase function from using .on to .once to avoid multiple additions of data to your table and as your data isn't expected to change frequently or require active listening you better use .once for performance benefits.
firebase.database().ref('Orders/' +
listid + '/foodItems').once('value').then(function(snapshot) {
// the rest of your code goes here
});
this remocve element with class name ".mdl-data-table__cell--non-numeric"
when user click .close
dialog.querySelector('.close').addEventListener('click', function () {
dialog.close();
$(".mdl-data-table__cell--non-numeric").remove();
});
UPDATE:
to open dialog on 2nd click use pseudo element to activate like this
<div class=pseudo><button onclick="purchaseList(orderid)"id="dialog" disabled>Button</button></div>
var i=0;
$('.pseudo').click(function(){
i++;
if(i==2){
$("#dialog").prop('disabled',false);
}
});

Binding event before Creating DOM in jQuery

var thumbDom = '';
for (var i = 0; i < 10; i++) {
thumbDom = thumbDom + '<div id = "div-" ' + i + '>DIV-'+ i +'</div>';
bindEvent(i);
}
$('#parent').append(thumbDom);
function bindEvent(i){
$('#div-' + i).click(function(event) {
alert(i);
});
}
I know the code can't work , beacuse event is bind before dom append.
but is there anyway to bind the click event to many dynamically doms before appending to dom tree?
I don't wnat to use $(document).on('click, ... , I want to bind event to the child node.
Any suggest will be help , thank you~
Fiddle Here
You could try this approach:
define a <div></div>
set its id and innerHtml
bind it with an onclick event (that alerts its id)
append it to the "#parent" item
$(function() {
for (var i = 0; i < 10; i++) {
$("<div></div>")
.attr("id", "div-" + i)
.html("DIV-" + i)
.click(function() {
alert($(this).attr("id"));
})
.appendTo("#parent");
}
});

Click event on every item on populated list with jQuery

Here is how I populate my list:
function bingNetworksList(myList) {
var list = '';
for (i = 0; i < myList.length; i++) {
list += '<li>' + myList[i] + '</li>';
}
$('#myList').empty();
$('#myList').append(list);
}
Here is my html file:
<ul id="myList"></ul>
I want to add a click event for every item of list (without having separate ids):
$(function() {
$('#myList').click(function() {
var listItem = this.find('a').text();
console.log(listItem); // never logged
});
});
However, when I click at a list item, click event doesn't fire.
What am I doing wrong?
I can only assume there's a js error in your console.
I've created a working sample for you. We can use event delegation and then retrieve the DOM node that was clicked. You need to ensure you call the bingNetworksList [assume typo in here and meant binD ;)] function when the DOM ready event has fired.
function bingNetworksList(myList) {
var list = '';
for (i = 0; i < myList.length; i++) {
list += '<li>' + myList[i] + '</li>';
}
$('#myList').empty();
$('#myList').append(list);
}
$(function() {
var list = ["foo", "bar"]
bingNetworksList(list);
$('#myList').click(function(evt) {
var listItem = $(evt.target).text();
console.log(listItem); // never logged
});
});
You need to wrap this inside $ as like this:
$(function() {
$('#myList').click(function() {
var listItem = $(this).find('a').text();
console.log(listItem); // will always be logged
});
});

Multiple functions in a for loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 9 years ago.
I have a php page with spoilers in wich I use javascript to view or hide the spoilers. This is done by changing classes on the span of each spoiler div (.hidden, .visible). The classes are s1, a1, s2, a2, s3, a3 etc.
I want to select each spoiler and give them an onclick function to view or hide the answer of the clicked spoiler. This can be done which variables in a for loop. I am getting no errors in Chrome debugger, but the classes won't change.
It works fine without the for loop.
This is a part of my php:
<div class="spoiler">
Is this a second question
View answer
<span id="a1" class="hidden">Yes it is</span>
<hr />
</div>
<div class="spoiler">
Is this a second question
View answer
<span id="a2" class="hidden">Yes it is</span>
<hr />
</div>
This is my javascript using jquery:
window.onload = function () {
for (var i = 1; i < 2; i++) {
var s = [];
s[i] = document.getElementById("s" + i);
s[i].addEventListener("click", function () {
var a = [];
a[i] = document.getElementById("a" + i);
if ($("a" + i).hasClass("hidden")) {
$("a" + i).removeClass("hidden");
$("a" + i).addClass("visible");
$("a" + i).html("Hide answer");
} else if ($("a" + i).hasClass("visible")) {
$("a" + i).removeClass("visible");
$("a" + i).addClass("hidden");
$("a" + i).html("View answer");
}
}, true);
};
}
Thanks for the help!
In your case just use $(this).next('span') instead of $("a" + i). Because this in your handler represents the current element clicked on and you want to select the anchor next to it, so you don't have to create the selector. Also the actual reason being, you are using the i as a shared variable inside your handler which would have run to the last value of the iteration by the time your handler gets invoked. Plus you have duplicate ids in your html which will select only the first item matching the selector.
Try:
window.onload = function () {
for (var i = 1; i <= 2; i++) {
var s = document.getElementById("s" + i);
s.addEventListener("click", function () {
var $this = $(this).next('span'), // or do $('#' + this.id.replace("a",""));
msg = "View answer";
$this.toggleClass("hidden visible")
if ($this.hasClass("hidden")) {
msg = "Hide answer";
}
$this.html(msg);
}, true);
};
}
Demo
Binding the event with jquery:
$(function(){
$('.spoiler [id^="s"]').click(function () {
var $this = $(this).next('span'),
msg = "View answer";
$this.toggleClass("hidden visible")
if ($this.hasClass("hidden")) {
msg = "Hide answer";
}
$this.html(msg);
});
});

Categories

Resources