Right now I'm doing some clean up code for my auction game, but my function is fired immediately after endAuction() is called rather than when the button is clicked. I can't seem to figure out why, and I'm not terribly familiar with JavaScript or jQuery, can anyone point out my issue?
endAuction:function()
{
var i = 0;
var btnID = "as" + (i).toString(),
liID = "asli" + (i).toString();
var cleanBtn = $('li#' + liID + ' button#' + btnID);
cleanBtn.text("Sold!");
var btn = $('#' + btnID);
btn.off().click(this.cleanUpAuction());
},
cleanUpAuction:function()
{
console.log("Removing button");
userStats.money += currentBid;
currentBid = 0;
var i = 0;
var liID = "asli" + (i).toString();
var carElement = $('li#' + liID);
carElement.remove();
},
You are calling the function, not assigning a reference to it.
Change
.click(this.cleanUpAuction())
to
.click(this.cleanUpAuction)
or
.click($.proxy(this.cleanUpAuction, this))
Related
I have created 3 dynamic buttons with class attribute and would like them listed when one is clicked. Only one is shown rather than all three.
<script>
var hyperlink;
$(function() {
var y = 2;
for(var i = 0; i <= 2; i++ ) {
drawRow( i, y );
}
});
function drawRow( x, y ) {
if(x == 0)
row = $("<tr />")
else {
var btnName = "btn" + x;
console.log("ln62 btnName: " + btnName);
hyperlink = document.createElement("button");
hyperlink.setAttribute('id', btnName);
hyperlink.setAttribute('class', 'btnCL'); // class set for button
hyperlink.innerHTML = x;
$("#DataTable").append(row);
row.append($("<td></td>").append(hyperlink));
var btnName2 = "#btn" + x;
}
}
$(document).on("click", '.btnCL', function() {
console.log("inside doc.on ln73");
//console.log("hyperlink: " + hyperlink.getAttribute("id"));
$(hyperlink).each(function( i ) {
console.log("ln76 " + i + ": " + hyperlink.getAttribute("id"));
});
});
</script>
Result:
ln62 btnName: btn1
ln62 btnName: btn2
ln62 btnName: btn3
inside doc.on ln73
ln76 0: btn3 // only one(1) listed?? s/b 3
ANY HELP WOULD BE APPRECIATED.
This is because hyperlink is a variable and not an array.This line hyperlink = document.createElement("button"); will always update hyperlink variable with last created button.
Instead of using each you can use the event object and get the target
var hyperlink;
$(function() {
var y = 2;
for (var i = 0; i <= 2; i++) {
drawRow(i, y);
}
});
function drawRow(x, y) {
if (x == 0)
row = $("<tr />")
else {
var btnName = "btn" + x;
console.log("ln62 btnName: " + btnName);
hyperlink = document.createElement("button");
hyperlink.setAttribute('id', btnName);
hyperlink.setAttribute('class', 'btnCL'); // class set for button
hyperlink.innerHTML = x;
$("#DataTable").append(row);
row.append($("<td></td>").append(hyperlink));
var btnName2 = "#btn" + x;
}
}
$(document).on("click", '.btnCL', function(e) {
console.log("inside doc.on ln73");
console.log(e.target.getAttribute("id"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="DataTable"></table>
The main problem is every iteration of the loop you reassign a new value to the variable hyperlink
All you really need to do is loop over the class collection and you don't need the global variable at all
$(document).on("click", '.btnCL', function() {
// current button is `this`
console.log('Current id:', this.id);
// loop over the class instead to see them all
$('.btnCL').each(function( i, el ) {
console.log("ln76 " + i + ": " + el.id); // or this.id
});
});
my button.onclick doesn't work on the first click, but it works on the second.
I used an alert to check and even the alert doesnt work on the first click, but works on the second click.
here's the link to the app in case you need it -
http://silentarrowz.imad.hasura-app.io/news
could you tell me what's wrong??
here's the code
window.onclick = function () {
var displayNews = document.getElementById('currentNews');
var newsButton = document.getElementById('getnews');
newsButton.onclick = function () {
alert('the button is clicked');
var newsxr = new XMLHttpRequest();
newsxr.onreadystatechange = function () {
if (newsxr.readyState === XMLHttpRequest.DONE && newsxr.status === 200) {
var currentNews = JSON.parse(newsxr.responseText);
var currentArticles = currentNews['articles'];
var numberArticles = currentNews['articles'].length;
var newsDisplay = '';
var author;
var title;
var description;
var urlToImage;
for (var i = 0; i < numberArticles; i++) {
author = currentArticles[i]['author'];
title = currentArticles[i]['title'];
description = currentArticles[i]['description'];
urlToImage = currentArticles[i]['urlToImage'];
newsDisplay = newsDisplay + "<p>" + "<span class='title'>" + title + "</span>" + "<br>" + description + "<br>" + "<img src='" + urlToImage +
"'</img>" + "</p>";
}
alert('displaying the news now');
console.log('current news is : ', currentNews);
displayNews.innerHTML = newsDisplay;
}
}; //on state change
newsxr.open('GET', 'https://newsapi.org/v1/articles?source=national-geographic&sortBy=top&apiKey=1af110441a8e4f72925f78344e58c2a4', true);
newsxr.send(null);
}; //button onclick function ends
}; // window onclick function ends
The truth about your code is the following..
You are assigning an onclick event to the window. when you click the window it then gets the buttons id which then assigns an onclick event to your button.
Your button only works when you click anywhere in the window (your browser User interface). You can try it and see
SOLUTION
remove the on window.onclick event stuff.
this should be the only code you should be seeing in your editor to make things work.
var displayNews = document.getElementById('currentNews');
var newsButton = document.getElementById('getnews');
newsButton.onclick = function(){
alert('the button is clicked');
var newsxr = new XMLHttpRequest();
newsxr.onreadystatechange = function(){
if(newsxr.readyState ===XMLHttpRequest.DONE && newsxr.status ===200){
var currentNews = JSON.parse(newsxr.responseText);
var currentArticles = currentNews['articles'];
var numberArticles = currentNews['articles'].length;
var newsDisplay ='';
var author;
var title;
var description;
var urlToImage;
for(var i=0;i<numberArticles;i++){
author = currentArticles[i]['author'];
title = currentArticles[i]['title'];
description = currentArticles[i]['description'];
urlToImage = currentArticles[i]['urlToImage'];
newsDisplay = newsDisplay + "<p>"+"<span class='title'>"+ title+"</span>"+ "<br>"+description+"<br>"+"<img src='"+urlToImage+"'</img>"+"</p>";
}
alert('displaying the news now');
console.log('current news is : ',currentNews);
displayNews.innerHTML = newsDisplay;
}
};//on state change
newsxr.open('GET','https://newsapi.org/v1/articles?source=national-geographic&sortBy=top&apiKey=1af110441a8e4f72925f78344e58c2a4',true);
newsxr.send(null);
};
//button onclick function ends
I hope this was explanatory
Because the first click is window.onclick = function() part which tells the window to define another click event only, and then the real click event will work when you click the second time.
Deleting the window click event already suffices.
P.S. I don't see why having window click event is meaningful in your code.
my first ever question pretty sure I'm being a bit daft here, but am a beginner and would appreciate your help.
Im working on a webpage where there is a html table listing several columns of data.
When the page loads it runs a jquery script which counts the different types of "incidents" and plots them in another table which then another jquery script populates a graph.
I have a third script (javascript) which after a button is clicked, runs an if loop, which looks at the data in the first column and if it does not match the criteria then the row is deleted.
So far so good, the issue is that I want the script which populates the table for the graph to run again, but Im not sure how to call it from my if loop.
Ive put the two scripts below, basically I want to call the 1st script in the second script.
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')");
$("#result").html(NumFireAlarms.length + " Fire Alarm");
var firealarms = NumFireAlarms.length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = firealarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')");
$("#result").html(NumLockout.length + " Lockout Out of Office Hours");
var lockouts = NumLockout.length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = lockouts
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')");
$("#result").html(NumLockout.length + " Lockout Day Time");
var lockoutsDayTime = NumLockoutDayTime.length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = lockoutsDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')");
$("#result").html(NumSensitiveIncident.length + " Sensitive Incident");
var SensitiveIncident = NumSensitiveIncident.length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = SensitiveIncident
});
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var start_date = document.getElementById("start_date").value;
var end_date = document.getElementById("end_date").value;
var staff_type = document.getElementById("Job_Title").value;
var i;
var count = 0;
var table_length = document.getElementById("incidents").rows;
var TL = table_length.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
var date_column = document.getElementById("incidents").rows[i].cells.item(1).innerHTML;
var staff_colunm = document.getElementById("incidents").rows[i].cells.item(8).innerHTML;
if (category_column === incident_category)
{
alert("yay")
count++
}
else if (category_column !== incident_category)
{
alert("boo")
document.getElementById("incidents").deleteRow(i);
//CALL FIRST SCRIPT HERE??
}
}
}
I removed a few bits of code that did not seem to do anything, but I'm sure you can put them back. I think you might want something like this:
function updateTable(){
var elResult = document.getElementById("result");
var elNumIncidentType = document.getElementById("no_of_incident_type");
var firealarms: document.querySelectorAll("#incidents tr:contains('Fire Alarm')").length;
var lockouts: document.querySelectorAll("#incidents tr:contains('Lockout Out of Office Hours')").length;
var lockoutsDayTime: document.querySelectorAll("#incidents tr:contains('Lockout Day Time')").length;
var sensitiveIncident: document.querySelectorAll("#incidents tr:contains('Sensitive Incident')").length;
elResult.innerHTML = "";
elResult.innerHTML += "<div>" + firealarms + " Fire Alarm</div>";
elResult.innerHTML += "<div>" + lockouts + " Lockout Out of Office Hours</div>";
elResult.innerHTML += "<div>" + lockoutsDayTime + " Lockout Day Time</div>";
elResult.innerHTML += "<div>" + sensitiveIncident + " Sensitive Incident</div>";
elNumIncidentType.rows[1].cells[1].innerHTML = firealarms;
elNumIncidentType.rows[2].cells[1].innerHTML = lockouts;
elNumIncidentType.rows[3].cells[1].innerHTML = lockoutsDayTime;
elNumIncidentType.rows[4].cells[1].innerHTML = sensitiveIncident;
}
function filterForGraph() {
var elIncidents = document.getElementById("incidents");
var incident_category = document.getElementById("Incident_Category").value;
var table_length = document.getElementById("incidents").rows.length;
for (var i = table_length - 1; i >= 1; i--) {
var currentIncident = elIncidents.rows[i].cells;
var category_column = currentIncident.item(0).innerHTML;
if (category_column != incident_category) { elIncidents.deleteRow(i); }
}
updateTable();
}
$(function(){ updateTable(); });
Hi JonSG tried your code and it didnt work not sure why, but it gave me some ideas to work with and I think Ive cracked it
function Populate_Incident_No_Table() {
//previously function called updateTable
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')").length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = NumFireAlarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')").length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = NumLockout
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')").length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = NumLockoutDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')").length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = NumSensitiveIncident
});
}
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var i;
var TL = document.getElementById("incidents").rows.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
if (category_column !== incident_category)
{
document.getElementById("incidents").deleteRow(i);
}
}
Populate_Incident_No_Table();
drawGraph();
}
I think the issue was how I was trying to call the functions. So what I've done to achieve what I wanted (please excuse any bad terminology / phrasing).
First I tried to name the function $(function updateTable(){ this did not work when I then tried to call the function like this updateTable();
Second thing I tried was putting the updateTable() function "inside" a function and call that function. This has worked for me I dont know why.
Thanks for your help without it I would not have thought to try what I did
Here when i click on a particular player its score is displayed.But when again a player is clicked the previous score doesn't get cleared.So pls can anyone provide the solution.
$(document).ready(function () {
for (var i = 0; i < temp.length; i++)
$("#sidebar").append("<div id=" + i + " class='player'>" + temp[i].name + "</div>")
$(".player").click(function () {
var pla = $(this).attr('id');
$("#score").append(temp[pla].score);
//$(".content").append(a[pla].Events);
var selected = $(this).hasClass("highlight");
var a = $("span").append($(this).text());
$(".player").removeClass("highlight");
if (!selected) {
$(this).addClass("highlight");
$(this.Text()).remove();
}
});
});
You might need to add a call to .html() for the sidebar to clear its content, add it at the top of your document ready function.
So something like:
$("#sidebar").html();
I have a form field that is being duplicated / removed dynamically
See the fiddle here : http://jsfiddle.net/obmerk99/y2d4c/6/
In this feature, I also need to increment the NAME of the field ( and ID etc.. ) like so :
o99_brsa_settings[brsa_dash_wdgt_content][0]
o99_brsa_settings[brsa_dash_wdgt_content][1]
o99_brsa_settings[brsa_dash_wdgt_content][2] ...
It is working, but the problem is that when I add / remove fields , when it gets to the last ( actually first one ) , it will give me "undefined" and will not add anymore fields .
To see the problem you will need to "play" a bit with add/remove .
I believe the main problem is how to keep all of those on the same array level if we have [0] and [0][2]
I am far from a JS guru, and this code was somehow assembled from various sources. But I am kind of stuck right now, So any help will be appreciated .
Try this way:
$(function () {
$(".addScnt").on("click", function () {
var i = checkNumberOfElements();
var scntDiv = $("div[id^='widget_dup']:last");
var prevDiv = scntDiv.clone();
var newname = $(prevDiv).find("textarea").attr("name").substring(0, $(prevDiv).find("textarea").attr('name').indexOf(']'));
prevDiv.find('textarea').attr('name', newname + "][" + i + "]");
prevDiv.find('textarea').attr('id', newname + "][" + i + "]");
prevDiv.find('label').attr('for', newname + "][" + i + "]");
prevDiv.attr('id', $(prevDiv).attr('id') + "_" + i);
$(scntDiv).after(prevDiv);
});
$(document).on("click", ".remScnt", function (event) {
var i = checkNumberOfElements();
if (i <= 1) {
return false;
} else {
var target = $(event.currentTarget);
target.parent("div").remove();
}
});
});
function checkNumberOfElements() {
// Number of textareas
var i = $("textarea[name^='o99_brsa_settings[brsa_dash_wdgt_content]']").length;
// Number of divs
// var i = $("div[id^='widget_dup']").length;
if (typeof i === undefined) {
return 0;
} else {
return i;
}
}
Demo: http://jsfiddle.net/y2d4c/7/