I'm very new to JQuery, and I'm having some trouble
function Clients(guid)
{
var that = this;
this.guid = guid;
this.container = $("#Clients_" + that.guid);
this.LoadClients = function () {
var ids = that.container.find("#clients-tbl").getDataIDs();
for (var i = 0; i < ids.length; i++) {
var row = that.container.find("#clients-tbl").getRowData(ids[i]);
var imgView = "<img src='../../Content/Images/vcard.png' style='cursor:pointer;' alt='Open case' onclick=OnClickImage(" + ids[i] + "); />";
that.container.find("#clients-tbl").setRowData(ids[i], { CasesButtons: imgView });
}
}
this.CreateClientsGrid = function () {
var clientsGrid = that.container.find("#widget-clients-tbl").jqGrid({
.....
ondblClickRow:function(rowid)
{
---
}
loadComplete: function () {
that.LoadClients();
}
}
this.OnClickImage=function(idClient){
....
}
this.Init = function () {
that.CreateClientsGrid();
};
this.Init();
}
The problem is with onclick, because OnClickImage is not global function.
How can I use OnClickImage function?
You can bind to the click event in different ways. For example you can follow the way from the answer. By the way, it works much more quickly as getRowData and setRowData. Moreover you should save the result of that.container.find("#clients-tbl") operation in a variable outside of the loop and use use the variable inside the loop. JavaScript is dynamic language and every operation even ids.length will be done every time.
One more way would to use onCellSelect event without click event binding. See the answer which describe the approach and gives the corresponding demo.
Related
I'm working on a page in which one element ('.item--itemprice') updates its text through another function that I'd prefer not to touch. What I'd like to do is get another element ('.header--itemprice') to update so that its text matches the first element.
Unfortunately, it seems that handler below is acting faster than the updating function. As a result, the header either stays with the previous text or changes to a blank string. Is there a way to delay the final line below until after the first element is finished updating?
$('select').on('change', function() {
const headPrice = document.querySelector('.header--itemprice');
const lowerPrice = document.querySelector('span.item--itemprice');
const $lowerText = $(lowerPrice).text();
$(headPrice).text($lowerText);
});
Here's the preexisting function:
$(document).ready( function () {
$('#txtQuantity, .ProductGroupItemQuantity').blur(updatePrice);
});
function updatePrice() {
var itemPriceEl = $('.item--itemprice');
var itemCountEl = $('#txtQuantity');
var groupUpdateEl = $('#lnkProductGroupUpdatePrice');
var groupPriceEl = $('.pdetail--price-total');
var totalPriceEl = $('.ProductDetailsPricing');
var itemPrice = moneyToNumber(itemPriceEl.text());
var itemCount = moneyToNumber(itemCountEl.val());
var itemTotalPrice = itemCount * itemPrice;
var groupTotalPrice = 0;
// Trigger Group Update
groupUpdateEl.click();
groupTotalPrice = moneyToNumber(groupPriceEl.text());
// Calculate Total Price
totalPriceEl.text('Total: $' + Number(groupTotalPrice + itemTotalPrice) / 100);
}
/*$('select').on('change', function() {
const headPrice = document.querySelector('.header--itemprice');
const lowerPrice = document.querySelector('span.item--itemprice');
const $lowerText = $(lowerPrice).text();
$(headPrice).text($lowerText);
});*/
function moneyToNumber(moneyEl) {
try {
return Number(moneyEl.replace(/[^0-9\.]+/g,"").replace(/\D/g,''));
} catch (err) {
return 0;
}
}
If you don't want to touch the other function at all and assuming it is also being called on the change event of select. A really hacky way could be, something like this -
$('select').on('change', function() {
setTimeout (function()
{
const headPrice = document.querySelector('.header--itemprice');
const lowerPrice = document.querySelector('span.item--itemprice');
const $lowerText = $(lowerPrice).text();
$(headPrice).text($lowerText);
}, 0);
});
In that case, the better way is changing the function, you can even trigger a event when the function is executed and watch this event to trigger the other function to change the element ('.header--itemprice')
In this homework assignment, I'm having issues with this part of the problem.
window.onload=setup;
function setup()
{
var questions = document.querySelectorAll('ol li');
for (var i= 0; i < questions.length ; i++)
{
questions[i].id = i + "phrases";
questions[i].onmousedown = showEnglish;
//questions[i].onmouseup = showFrench;
questions[i].style.cursor = "pointer";
}
}
function showEnglish()
{
var phraseNumber = parseInt(question[i].id)
document.getElementById(phraseNumber).innerHTML = english[phraseNumber];
english[phraseNumber].style.font = "italic";
english[phraseNumber].style.Color = "rgb(191,22,31)";
}
a) Using the id property of the list item experiencing the mousedown event, extract the index number with the the parseInt() function and store that value in the phraseNumber variable.
I get an error, saying questions is not defined in the showenglish().
Am I supposed to be referencing another object?
You need to pass the question as a parameter:
for(i=0;i<question.length;i++){
let a=i;//important for scoping
question[a].onmousedown=function(){
showEnglish(question[a]);
}
}
function showEnglish(question){
document.getElementById(question.id).style.font="italic";
...
}
(Note: this answer contains ES6. Do not use it in real productional environment. The let a=i; defines that a is kept for being used inside of the listener, while i will always be question.length, because the event is probably clicked after the loop occured...)
Alternatively, the event listener binds this as the clicked element:
question[i].addEventListener("click",showEnglish,false);
function showEnglish(){
document.getElementById(this.id).style.font="italic";
...
}
The mousedown event is raised when the user presses the mouse button. Look at the documentation for the mousedown event.
Your event handler function will be passed an Event object, which has a target property, which is a reference to the element that the mouse clicked on.
You can access this inside your event handler function with event.target.
window.onload = setup;
function setup() {
var questions = document.querySelectorAll('ol li');
for (var i = 0; i < questions.length; i++) {
questions[i].id = i + "phrases";
questions[i].onmousedown = showEnglish;
//questions[i].onmouseup = showFrench;
questions[i].style.cursor = "pointer";
}
}
function showEnglish(event) {
var phraseNumber = parseInt(event.target.id);
// etc
};
I cannot seems to select the correct keywords in google to find this answer so...
I am creating a series of functions within a class to handle select box changes. Here is a very simple example of how the javascript is laid out
function example(n) {
this.name = n;
}
example.prototype.setChange(i) {
var c = document.getElementById('test' + i );
for ( var x = 0; x < 10; x++
c.options[0] = new Option(x, x);
c.change = this.doChange;
}
example.prototype.doChange() {
alert(this.name);
}
Everything works find until I try to access 'this'. When doChange is called, this is the actual select html object instead of the class. Because this is an event, I cannot use .call(this) to enforce the proper bindings.
You loose your this by doing this.doChange. Use something like
function example(n) {
this.name = n;
var self = this;
this.doChange = function () {
alert(self.name);
}
}
Just about everyone has ran into this specific issue:
function addLinks () {
for (var i=0, link; i<5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function () {
alert(i);
};
document.body.appendChild(link);
}
}
window.onload = addLinks;
The value of i after the loop is cached. A closure can be used to create a "live" reference:
function addLinks () {
for (var i=0, link; i<5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function (num) {
return function () {
alert(num);
};
}(i);
document.body.appendChild(link);
}
}
window.onload = addLinks;
We can also use self executing anon fns to create closures as well, etc..
My situation
The issue I'm facing is the same, but the context is a little different. Here's a failing example:
Hit 'add more lis' a few times and click 'hit me', which will alert -1. The value of maxIndex is cached. Relevant code:
var attached = false;
function actions() {
var elements = $('body').find('li');
var maxIndex = elements.length -1;
var cycle = {
next: function() {
alert( maxIndex );
}
};
if ( !attached ) {
$('#next').click(function(e) {
cycle.next();
});
attached = true;
}
};
actions();
$('#add').click(function(e) {
e.preventDefault();
$('<li/>').text('god').appendTo('body');
actions();
});
I've tried applying closures to no avail. ( see http://jsfiddle.net/Bfcus/23/ and down to /1/ ).
I don't want to use with statements or let statements/expressions to solve this. I know another way this is solvable is by changing maxIndex to be a property of a named object. Here's a working example doing it that way.
What I'm wondering is - is there a way of having it work while keeping the elements variable definition inside of the action function, and having the maxIndex variable defined in the same scope? Basically, can http://fiddle.jshell.net/r7Ekj/2/show/ be adjusted to work almost in the same manner as it is, without relying on with/let/object property?
Weird, sometimes creating a thorough question actually helps you solve it and I swear I didn't have it solved beforehand...
I just created the maxIndex variable outside of the actions scope and actually assign it inside.. this makes it work because it isn't defined in the same function scope and so the binding behaves differently.
http://fiddle.jshell.net/r7Ekj/9/
( How embarassing? )
I just started using javascript and I'm missing something important in my knowledge. I was hoping you could help me fill in the gap.
So the script I'm trying to run is suppose to count the characters in a text field, and update a paragraph to tell the user how many characters they have typed. I have an object called charCounter. sourceId is the id of the text area to count characters in. statusId is the id of the paragraph to update everytime a key is pressed.
function charCounter(sourceId, statusId) {
this.sourceId = sourceId;
this.statusId = statusId;
this.count = 0;
}
There is one method called updateAll. It updates the count of characters and updates the paragraph.
charCounter.prototype.updateAll = function() {
//get the character count;
//change the paragraph;
}
I have a start function that is called when the window loads.
function start() {
//This is the problem
document.getElementbyId('mytextfield').onkeydown = myCounter.updateAll;
document.getElementbyId('mytextfield').onkeyup = myCounter.updateAll;
}
myCounter = new charCounter("mytextfield","charcount");
window.onload = start;
The above code is the problem. Why in the world can't I call the myCounter.updateAll method when the event is fired? This is really confusing to me. I understand that if you call a method likeThis() you'll get a value from the function. If you call it likeThis you are getting a pointer to a function. I'm pointing my event to a function. I've also tried calling the function straight up and it works just fine, but it will not work when the event is fired.
What am I missing?
Thanks for all the answers. Here's three different implementations.
Implementation 1
function CharCounter(sourceId, statusId) {
this.sourceId = sourceId;
this.statusId = statusId;
this.count = 0;
};
CharCounter.prototype.updateAll = function() {
this.count = document.getElementById(this.sourceId).value.length;
document.getElementById(this.statusId).innerHTML = "There are "+this.count+" charactors";
};
function start() {
myCharCounter.updateAll();
document.getElementById('mytextfield').onkeyup = function() { myCharCounter.updateAll(); };
document.getElementById('mytextfield').onkeydown = function() { myCharCounter.updateAll(); };
};
myCharCounter = new CharCounter('mytextfield','charcount');
window.onload = start;
Implementation 2
function CharCounter(sourceId, statusId) {
this.sourceId = sourceId;
this.statusId = statusId;
this.count = 0;
};
CharCounter.prototype.updateAll = function() {
this.count = document.getElementById(this.sourceId).value.length;
document.getElementById(this.statusId).innerHTML = "There are "+ this.count+" charactors";
};
CharCounter.prototype.start = function() {
var instance = this;
instance.updateAll();
document.getElementById(this.sourceId).onkeyup = function() {
instance.updateAll();
};
document.getElementById(this.sourceId).onkeydown = function() {
instance.updateAll();
};
};
window.onload = function() {
var myCounter = new CharCounter("mytextfield","charcount");
myCounter.start();
};
Implementation 3
function CharCounter(sourceId, statusId) {
this.sourceId = sourceId;
this.statusId = statusId;
this.count = 0;
};
CharCounter.prototype.updateAll = function() {
this.count = document.getElementById(this.sourceId).value.length;
document.getElementById(this.statusId).innerHTML = "There are "+this.count+" charactors";
};
function bind(funcToCall, desiredThisValue) {
return function() { funcToCall.apply(desiredThisValue); };
};
function start() {
myCharCounter.updateAll();
document.getElementById('mytextfield').onkeyup = bind(myCharCounter.updateAll, myCharCounter);
document.getElementById('mytextfield').onkeydown = bind(myCharCounter.updateAll, myCharCounter);
};
myCharCounter = new CharCounter('mytextfield','charcount');
window.onload = start;
I think you are having problems accessing your instance members on the updateAll function, since you are using it as an event handler, the context (the this keyword) is the DOM element that triggered the event, not your CharCounter object instance.
You could do something like this:
function CharCounter(sourceId, statusId) {
this.sourceId = sourceId;
this.statusId = statusId;
this.count = 0;
}
CharCounter.prototype.updateAll = function() {
var text = document.getElementById(this.sourceId).value;
document.getElementById(this.statusId).innerHTML = text.length;
};
CharCounter.prototype.start = function() {
// event binding
var instance = this; // store the current context
document.getElementById(this.sourceId).onkeyup = function () {
instance.updateAll(); // use 'instance' because in event handlers
// the 'this' keyword refers to the DOM element.
};
}
window.onload = function () {
var myCharCounter = new CharCounter('textarea1', 'status');
myCharCounter.start();
};
Check the above example running here.
The expression "myCounter.updateAll" merely returns a reference to the function object bound to "updateAll". There's nothing special about that reference - specifically, nothing "remembers" that the reference came from a property of your "myCounter" object.
You can write a function that takes a function as an argument and returns a new function that's built specifically to run your function with a specific object as the "this" pointer. Lots of libraries have a routine like this; see for example the "functional.js" library and its "bind" function. Here's a real simple version:
function bind(funcToCall, desiredThisValue) {
return function() { funcToCall.apply(desiredThisValue); };
}
Now you can write:
document.getElementById('myTextField').onkeydown = bind(myCounter.updateAll, myCounter);
You can:
function start() {
//This is the problem
document.getElementbyId('mytextfield').onkeydown = function() { myCounter.updateAll(); };
document.getElementbyId('mytextfield').onkeyup = function() { myCounter.updateAll(); };
}
In ASP.Net Ajax you can use
Function.createDelegate(myObject, myFunction);
I want to do something like this but simpler.
The idea is to have the user click on bolded text and have a text field appear where they can change all the values of a role-playing character. Then when the value is changed, have the text field disappear again replaced by the updated bolded text value.
I can do this already using an annoying text box alert. But I would rather have something similar to this below to replace all that.
I have searched for months and CMS is the closest to answering my question in the simplest way with a full html example. Nobody else on the net could.
So my question is, how do I do this?
I have multiple objects(characters) and need this.elementId to make this work.
I've modified this example but it breaks if I try to add to it.
html>
head>
title>Sandbox
/head>
body>
input id="textarea1" size=10 type=text>
script>
function CharCounter(sourceId, statusId)
{this.sourceId=sourceId;
this.statusId=statusId;
this.count=0;
}
CharCounter.prototype.updateAll=function()
{text=document.getElementById(this.sourceId).value
document.getElementById(this.statusId).innerHTML=text
}
CharCounter.prototype.start=function()
{instance=this
document.getElementById(this.sourceId).onkeyup=function ()
{instance.updateAll()}
}
window.onload=function ()
{myCharCounter=new CharCounter('textarea1', 'status')
myCharCounter.start()
}
/script>
/body>
/html>