How to properly add multiple elements event in jQuery custom plugin - javascript

I am trying to write my first jquery plugin and I'm having some difficulties trying to implement functions, events and triggers.
Here is the scenario in which I'm working.
I've multiple input box with same class eg. "numberTextBox"
Apply plugin directly to these classes eg. "$(".numberTextBox").inputNumericTextBox();".
I can also give settings in it.
Now plugin should allow only numeric value based on setting either given on default.
what I had in my mind is to properly convert and verify any given value. I want to use both onkeypress and onblur event. For that I wrote simple JavaScript program see here http://jsfiddle.net/wHgH5/29/.
I wanted to create jquery plugin so I can use in future easily with more friendly code.
On "return this each function" you can see I wrote keypress and blur function for that specific reason.
Problems which I am facing:
Firstly the blur event is not working so I can't trigger beforeBlurAction, afterBlurAction, onComplete functions and not to mention all the functionality in triggerBlurAction will not work.
Secondly even on keypress event it's assuming all "numberTextBox" input elements are same and doesn't apply separately. To understand it run the code snippet there are two input box with same classes, now type/press from keyboard "2.1.1" it will only allow "2.1" in that input box but on the second one it won't allow decimal. but if you empty first input box and it will allow writing single decimal on the second input box. I want to do it separately.
Check here https://jsfiddle.net/mzhe2rde/
//JQuery Custom Plugin inputNumericTextBox
(function($) {
jQuery.fn.inputNumericTextBox = function(options) {
var defaults = {
negativeAllow: true,
decimalAllow: true,
decimalError: false,
negativeSignError: false,
beforeKeypressAction: function() {},
afterKeypressAction: function() {},
beforeBlurAction: function() {},
afterBlurAction: function() {},
onError: function() {},
onComplete: function() {},
};
var settings = $.extend({}, defaults, options);
return this.each(function(i, element) {
$(document).on('keypress', element, function(e) {
triggerKeypressAction(e, element)
});
$(document).on('blur', element, function(e) {
alert(); //for testing but it's now working
triggerBlurAction(e, element)
});
});
function triggerKeypressAction(evt, element) {
settings.beforeKeypressAction.call(element, settings);
var regex;
var theEvent = evt || window.event;
var key = String.fromCharCode(theEvent.keyCode || theEvent.which);
if (/\./.test(key) && /\./.test($(element).val())) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
settings.decimalError = true;
settings.onError.call(element, settings);
return false;
}
/** Any idea on how to allow only one negative sign at the beginning?
write regex code here **/
if (settings.decimalAllow) {
regex = (settings.negativeAllow) ? /[0-9]|\-|\./ : /[0-9]|\./;
} else {
regex = (settings.negativeAllow) ? /[0-9]|\-/ : /[0-9]/;
}
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
settings.afterKeypressAction.call(element, settings);
}
function triggerBlurAction(evt, element) {
settings.beforeBlurAction.call(element, settings);
var inputValue = $(element).val(),
parsedValue = (settings.decimalAllow) ? parseFloat(inputValue) : parseInt(inputValue, 10);
if (isNaN(parsedValue)) {
$(element).val('');
} else if (settings.negativeAllow) {
$(element).val(parsedValue);
} else {
$(element).val(Math.abs(parsedValue));
}
settings.afterBlurAction.call(element, settings);
settings.onComplete.call(element, settings);
}
};
})(jQuery);
$(".numberTextBox").inputNumericTextBox({
negativeAllow: true,
decimalAllow: true,
beforeKeypressAction: function(e) {
console.log(this);
console.log(e);
console.log('before key');
},
afterKeypressAction: function(e) {
console.log(this);
console.log(e);
console.log('after key');
},
beforeBlurAction: function(e) {
console.log(this);
console.log(e);
console.log('before blur');
},
afterBlurAction: function(e) {
console.log(this);
console.log(e);
console.log('after blur');
},
onError: function(e) {
console.log(this);
console.log(e);
console.log('on error');
if (e.decimalError) {
alert('More than one decimal number is not allowed');
} else if (e.negativeSignError) {
alert('More than one negative sign is not allowed.\n You can only use negative at the start');
}
},
onComplete: function(e) {
console.log(this);
console.log(e);
console.log('on complete');
},
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input id="firstbox" type="text" class="numberTextBox" />
<input id="secondbox" type="text" class="numberTextBox" />
</body>

I thought I should try myself. what I did is put all the content of the plugin to another private function. and call the function in a loop to initialize every element separately. that way I achieved my goal and all events are working properly. and few more to support single negative sign. now it's proper input number textbox.
check it out here https://jsfiddle.net/mzhe2rde/6/
//JQuery Custom Plugin inputNumericTextBox
(function($) {
"use strict";
var inputNumericTextBox = function(element, options) {
var previous_value_set = false;
var previous_value = '';
var defaults = {
negativeAllow: true,
decimalAllow: true,
decimalError: false,
startNegativeSignError: false,
multipleNegativeSignError: false,
beforeKeypressAction: function() {},
afterKeypressAction: function() {},
beforeKeyupAction: function() {},
afterKeyupAction: function() {},
beforeBlurAction: function() {},
afterBlurAction: function() {},
onError: function() {},
onInitializationComplete: function() {},
};
var settings = $.extend({}, defaults, options);
$(element).on('keypress', function(e) {
//console.log("keypress");
triggerKeypressAction(e, element);
});
$(element).on('keyup', function(e) {
//console.log("keyup");
triggerKeyupAction(e, element);
});
$(element).on('blur', function(e) {
//console.log("blur");
triggerBlurAction(e, element);
});
settings.onInitializationComplete.call(element, settings);
function triggerKeypressAction(evt, element) {
settings.beforeKeypressAction.call(element, settings);
var regex;
var theEvent = evt || window.event;
var key = String.fromCharCode(theEvent.keyCode || theEvent.which);
if (/\./.test(key) && /\./.test($(element).val())) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
settings.decimalError = true;
settings.onError.call(element, settings);
settings.afterKeypressAction.call(element, settings);
settings.decimalError = false;
return false;
}
if (/-/.test(key) && /-/.test($(element).val())) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
settings.multipleNegativeSignError = true;
settings.onError.call(element, settings);
settings.afterKeypressAction.call(element, settings);
settings.multipleNegativeSignError = false;
return false;
}
if (/-/.test(key)) {
previous_value_set = true;
previous_value = $(element).val();
}
if (settings.decimalAllow) {
regex = (settings.negativeAllow) ? /[0-9]|-|\./ : /[0-9]|\./;
} else {
regex = (settings.negativeAllow) ? /[0-9]|-/ : /[0-9]/;
}
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
settings.afterKeypressAction.call(element, settings);
}
function triggerKeyupAction(evt, element) {
settings.beforeKeyupAction.call(element, settings);
if (settings.negativeAllow && previous_value_set) {
if (!(/^-.*/.test($(element).val()))) {
$(element).val(previous_value);
settings.startNegativeSignError = true;
settings.onError.call(element, settings);
settings.startNegativeSignError = false;
}
}
previous_value_set = false;
previous_value = '';
settings.afterKeyupAction.call(element, settings);
}
function triggerBlurAction(evt, element) {
settings.beforeBlurAction.call(element, settings);
var inputValue = $(element).val(),
parsedValue = (settings.decimalAllow) ? parseFloat(inputValue) : parseInt(inputValue, 10);
if (isNaN(parsedValue)) {
$(element).val('');
} else if (settings.negativeAllow) {
$(element).val(parsedValue);
} else {
$(element).val(Math.abs(parsedValue));
}
settings.afterBlurAction.call(element, settings);
}
return;
};
if (!jQuery.fn.inputNumericTextBox) {
jQuery.fn.inputNumericTextBox = function(options) {
return this.each(function() {
inputNumericTextBox(this, options);
return this;
});
};
}
})(jQuery);
$(".numberTextBox").inputNumericTextBox({
negativeAllow: true,
decimalAllow: true,
beforeKeypressAction: function(e) {
//console.log(this);
//console.log(e);
//console.log('before keypress');
},
afterKeypressAction: function(e) {
//console.log(this);
//onsole.log(e);
//console.log('after keypress');
},
beforeKeyupAction: function(e) {
//console.log(this);
//onsole.log(e);
//console.log('before keyup');
},
afterKeyupAction: function(e) {
//console.log(this);
//onsole.log(e);
//console.log('after keyup');
},
beforeBlurAction: function(e) {
//console.log(this);
//console.log(e);
//console.log('before blur');
},
afterBlurAction: function(e) {
//console.log(this);
//console.log(e);
//console.log('after blur');
},
onError: function(e) {
//console.log(this);
//console.log(e);
//console.log('on error');
if (e.decimalError) {
alert('More than one decimal number is not allowed');
} else if (e.multipleNegativeSignError) {
alert('More than one negative sign is not allowed.');
} else if (e.startNegativeSignError) {
alert('You can only use one negative sign at the start');
}
},
onInitializationComplete: function(e) {
//console.log(this);
//console.log(e);
//console.log('on complete');
},
});
/* Last initialization settings will take the precedence but events will trigger on all initialization
* You shouldn't initialize more than one on a single element because it will create more object and it will take some memory to store it.
* It's their to support large environment */
/* This is an example of last initialization or initialization more than one */
/*
$(".numberTextBox").inputNumericTextBox();
var n = $(".numberTextBox").inputNumericTextBox({
negativeAllow: false,
decimalAllow: true
});
console.log(n);*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type="text" class="numberTextBox" />
<input type="text" class="numberTextBox" />
</body>

Related

using bootstrap 3.37 header dropdown menu and tranlsating jquery to knockoutJS

I was looking at this article to apply header menu with dropdowns in my mvc5 knockoutjs solution.
https://jdmdigital.co/news/codex/bootstrap-3-secondary-dropdown-menu/
The frontend it looks nice, and it is ok in my solution, however, I cant figure it out how to bind js section to work.
Now when I click on my dropdown parent item, nothing happens, because the js code is not working.
here is my setup of the js (knockoutjs) file.
define(['durandal/system', 'plugins/router', 'durandal/services/logger', 'knockout', 'common', 'plugins/dialog', 'durandal/binder', 'fastclick'],
function (system, router, logger, ko, common, dialog, binder, fs) {
var shell = {
activate: activate,
router: router,
};
// Make Dropdown Submenus possible
$('.dropdown-submenu a.dropdown-submenu-toggle').on("click", function (e) {
$('.dropdown-submenu ul').removeAttr('style');
$(this).next('ul').toggle();
e.stopPropagation();
e.preventDefault();
});
// Clear Submenu Dropdowns on hidden event
$('#bs-navbar-collapse-1').on('hidden.bs.dropdown', function () {
$('.navbar-nav .dropdown-submenu ul.dropdown-menu').removeAttr('style');
});
//...
//...
//OTHER INIT METHODS (not in the scope for this question)
//#region Internal Methods
function activate() {
var result = registerRoutes();
//setRouteGuard();
if (window.cordova) {
window.document.addEventListener("deviceready", function () {
shell.refreshUserData(true);
shell.changeLanguage();
});
} else {
shell.refreshUserData(true);
shell.changeLanguage();
}
shell.isLoading.subscribe(function (newValue) {
//if something gone wrong
if (newValue) {
setTimeout(function () {
//shell.isLoading(false);
}, 10000);
}
});
if (router.activeInstruction().config.moduleId == "viewmodels/parentschedule") {
if (shell.isAnonymousUser() == true) {
shell.isClient(false);
shell.isEmployee(false);
}
else {
shell.isClient(true);
shell.isEmployee(true);
}
//console.log("test");
}
return result;
}
function route(r, moduleId, name, visible, alwaysVisible, role, condition) {
var self = this;
self.route = r;
self.moduleId = moduleId;
self.title = name;
self.visible = visible;
self.nav = true;
self.role = role;
self.condition = condition;
self.mouseover = ko.observable(false);
self.onhover = function () {
self.mouseover(!self.mouseover());
};
self.goToPage = function () {
router.navigate(this.hash);
};
self.alwaysVisible = alwaysVisible;
self.isTouched = ko.observable(false);
self.setTouched = function () {
self.isTouched(true);
return true;
}
self.setUnTouched = function () {
setTimeout(function () {
self.isTouched(false);
}, 200);
return true;
}
self.isActiveMenuItem = ko.computed(function () {
return router.activeInstruction() &&
router.activeInstruction().fragment.indexOf(self.route) > -1
});
return self;
}
//#endregion
});

How can prevent the scroll event execute more times?

I am implementing a new feature to let my page to support endless scroll AJAX show. But when I pull down my page scroll bar, sometimes the same request occurs.
This means that alert(nextPage) method is executed and it shows the same result. I've added the event.stopPropagation() code, but it didn't solve the problem. How can i fix it?
(function(window, undefined) {
var app = {
event: {
add: function(obj, type, handle) {
try {
obj.addEventListener(type, handle, false);
} catch (e) {
try {
obj.attachEvent('on' + type, handle);
} catch (e) {
obj['on' + type] = handle;
}
}
}
},
scroll: function(id, url) {
$.get(url, function(html) {
$("#" + id).append(html)
});
}
}
})(window);
HTML
<script>
$(function() {
app.event.add(window, "scroll", function(event) {
var nextPage = getNextPage();
alert(nextPage);
app.scroll("productTable", '?page=' + nextPage);
if (event && event.stopPropagation) {
event.stopPropagation();
} else {
window.event.cancelBubble = true;
}
});
});
</script>

How do I change a div from popup to slide down?

I'm not very good with javascript and I have this javascript code. When I click on the link the div shows and hides. The problem is the showing effect, it pops up and doesn't look good so I want the div to slide down when it shows.
Here's the code:
<script type="text/javascript">
var s;
ShowHideWidget = {
settings : {
clickHere : document.getElementById('clickHere'),
dropdown_signup : document.getElementById('dropdown_signup')
},
init : function() {
//kick things off
s = this.settings;
this.bindUIActions();
},
bindUIActions : function() {
//Attach handler to the onclick
/*
s.clickHere.onclick = function() {
ShowHideWidget.toggleVisibility(s.showing);
return false;
};
*/
ShowHideWidget.addEvent(s.clickHere, 'click', function() {
ShowHideWidget.toggleVisibility(s.dropdown_signup);
});
},
addEvent : function(element, evnt, funct) {
//addEventListener is not supported in <= IE8
if (element.attachEvent) {
return element.attachEvent('on'+evnt, funct);
} else {
return element.addEventListener(evnt, funct, false);
}
},
toggleVisibility : function(id) {
if(id.style.display == 'block') {
id.style.display = 'none';
} else {
id.style.display = 'block';
};
}
};
(function() {
ShowHideWidget.init();
})();
</script>
You can achieve it by using jquery slideDown and slideUp functions:
Add following code:
toggleVisibility : function(id) {
if( $(id).is(':visible') ){
$(id).slideUp();
} else {
$(id).slideDown();
}
}
DEMO
You'd do well to use something like jQuery's .slideDown function. You'll have to write a lot of code to do this yourself.

What does this BlackBerry Web App Javascript code do?

I know my way around several programming languages but am struggling understanding Javascript and how it's used in mobile apps. I'm developing for BlackBerry and a using the BlackBerry 10 jQuery Mobile Theme. I'm looking at the App.js from the samples and am confused as to what the App object is.
App = {};
App.init = function () {
console.log("App Init");
App.utils.metaHack();
$("#activity").live("pageinit", function(){
App.page.activity.init();
});
$("#bb_activity").live("pageinit", function(){
App.page.bb_activity.init();
});
$("#progressPage").live("pageinit", function(){
App.page.progress.init();
});
$("#sliderPage, #sliderPageDark").live("pageinit", function(){
App.page.slider.init();
});
$("#togglePage, #togglePageDark").live("pageinit", function(){
App.page.toggle.init();
});
$("#actionBarSample").live("pageinit", function() {
App.page.actionBarSample.init();
});
$('#applicationMenu').live("pageinit", function() {
App.page.applicationMenu.init();
});
}
App.utils = {
metaHack: function () {
var meta = document.createElement("meta");
meta.setAttribute('name','viewport');
meta.setAttribute('content','initial-scale='+ (1/window.devicePixelRatio) + ',user-scalable=no');
document.getElementsByTagName('head')[0].appendChild(meta);
}
}
App.page = {
activity: {},
bb_activity: {},
progress: {},
slider: {},
toggle: {},
actionBarSample: {},
applicationMenu: {}
}
App.page.activity.init = function() {
$('#show').on('click', function () {
$.mobile.loading('show');
});
$('#text').on('click', function() {
$.mobile.loading('show', {
text: 'Loading',
textVisible: true,
textonly: true,
theme: 'a'
});
});
$('#swatch-a').on('click', function() {
$.mobile.loading( 'show', {
text: 'Loading',
textVisible: true,
theme: 'a'
});
});
$('#swatch-a-notext').on('click', function() {
$.mobile.loading( 'show', {
theme: 'a'
});
});
$('#swatch-c').on('click', function() {
$.mobile.loading( 'show', {
text: 'Loading',
textVisible: true,
theme: 'c'
});
});
$('#swatch-c-notext').on('click', function() {
$.mobile.loading( 'show', {
theme: 'c'
});
});
$('#hide').on('click', function () {
$.mobile.loading('hide');
});
}
App.page.bb_activity.init = function() {
console.log("bb_activity");
$('#throttle').on('change', function () {
console.log("throttle");
var speed = $('#throttle').val();
$('#speedTest').activityindicator('speed', speed+'s');
});
}
App.page.progress.init = function() {
var p = 0;
var error = pause = false;
function watchProgress() {
if( p > 100 || error || pause) {
return;
}
$('#rogress').progressbar("setValue", p);
p+= 4;
setTimeout(watchProgress, 100);
}
$('#start').on('vclick', function () {
error = false;
watchProgress();
});
$('#error').on('vclick', function () {
$('#rogress').progressbar("setError", error = !error);
});
$('#pause').on('vclick', function () {
$('#rogress').progressbar("pause", pause = !pause);
});
$('#reset').on('vclick', function () {
p = 0;
error = pause = false;
$('#rogress').progressbar("setValue", p);
});
}
App.page.slider.init = function() {
$('#slider-disabled').slider('disable');
$('#slider-disabled-highlight').slider('disable');
}
App.page.toggle.init = function() {
console.log("toggle init");
$('#flip-disabled').slider('disable');
}
App.page.actionBarSample.init = function() {
var $tabo = $("#tover"),
overflowState = $tabo.hasClass("noContent");
$("#left").on("panelbeforeopen", function() {
//Save the state of the overflow button
overflowState = $tabo.hasClass("noContent");
$tabo.addClass("noContent");
})
.on("panelbeforeclose", function() {
//Put the overflow button into the correct state
if(!overflowState) {
$tabo.removeClass("noContent");
}
});
//Handle overflow menu clicks
$(".bb10-panel").bind("vclick", function() {
//Close the panel
$(this).panel("close");
});
$("#left li").bind("vclick", function() {
//Clear the active state from any other buttons that may have been set to active
$(this).siblings().removeClass("ui-btn-active");
//Add the active state to the selected button
$(this).addClass("ui-btn-active");
//Clear the contents of the tab overflow button
//Add class to put the tab overflow icon in the correct position
//Clear the active state from all tab buttons in action bar
$('[data-role="tab"], [data-role="tab-overflow"]').removeClass("active");
});
$(".inBar").bind("vclick", function() {
//Set the active state to the tab in the actionbar
$('#' + this.id.slice(0, 2)).addClass("active");
$tabo.addClass("noContent").empty();
overflowState = true;
});
$(".notInBar").bind("vclick", function() {
//Set the active state to the tab overflow button
$tabo.empty()
.addClass("active")
.html('<img src="img/generic_81_81_placeholder.png" alt=""><p>' + $(this).text() + '</p>')
.removeClass("noContent");
overflowState = false;
});
$("[data-role='tab']").bind("vclick", function() {
//Change page on tab click
if($(this).data("href")) {
$.mobile.changePage( $(this).data("href"), { transition: "slideup"} );
}
});
}
App.page.applicationMenu.init = function() {
if(typeof blackberry != 'undefined'){
blackberry.event.addEventListener('swipedown', function(){
$('#top').panel("open");
});
$('#menuBtn').css('display','none');
}
else{
$('#simulInst').css('display','none');
}
}
App.init();
Is App an object specific to Blackberry? I did some dabbling and made a small app but didn't use App or init anything.
App in this example is defined at the top:
App = {};
So it's just a new plain old JavaScript object (dictionary), which they then define functions and data to it e.g. App.utils = ....
You can try it out on a browser, press F12 and then go to the console (ESC) and type e.g. blah = {} and you will see a new object created with the name blah. Everything is an object in JavaScript apparently.
Read more
http://www.w3schools.com/js/js_objects.asp

Cant add a Jquery plugin inside a loop

Hi I have a JQuery plugin that takes an array of Orders and creates rows for each Order in the array. No issues here. However if one of these Orders meets a condition it should add a textbox in one of the TD cells. When I debug I can see it adding the textBox but when the next row is created which requires a textBox the previous textbox gets removed. i have this inside a close so not sure what to do. So the result is I only get textboxes in the last row.
If I add the textBox as html it works fine but I want it as a plugin as I need to bind several events KeyUp/Down MouseWheel, Click. etc
The textbox plugin control (gep_inputcontrol) just creates the html and binds events, nothing fancy.
Any help appreciated.
var _table = $('#orderTable', this);
for (var i = 0; i < params.orders.length; i++) {
var row = createRow(params.orders[i]);
_table.append(row);
}
function createRow(order){
var unmatchedStake = (order.requestedStake - order.matchedStake);
var partMatched = (unmatchedStake > 0);
var tr = $(String.format('<tr id="order_{0}" class="{1}"/>' ,order.orderId, ((i % 2) == 0) ? 'gep-altrow' : 'gep-row'));
tr.append(String.format('<td class="gep-icon gep-status">{0}</td>', order.orderStatusId));
tr.append(String.format('<td class="gep-selectionname">{0} {1} {2}</td>', GBEUtils.getEventName(order.eventClassifierFullName()), gep._settings.resources.general.polarity[order.polarityId], order.selectionName()));
tr.append(String.format('<td class="gep-odds betSlipRowPrice">{0}</td>', order.averageMatchedPrice));
tr.append(String.format('<td class="gep-unmatched betSlipRowStake">{0}</td>', com.base.formatDecimal(order.requestedStake - order.matchedStake,2)));
tr.append(String.format('<td class="gep-matched">{0}</td>', com.base.formatDecimal(order.matchedStake,2)));
tr.append(String.format('<td class="gep-action"><span class="gep-icon"/></td>', order.orderStatusId));
//var tablerow = $(String.format('#order_{0}',order.orderId), _table);
//(function (_table, tr, i, unmatchedStake, tablerow) {
if(unmatchedStake > 0)//part matched
{
$('.gep-unmatched', tr).gep_inputcontrol({
type:'STAKE',
ccSymbol:clientObject.state.ccSymbol,
value: unmatchedStake,
decimalValue:unmatchedStake,
onMouseWheeled: function(e, ev){
gep.inputControlWheeled(e, ev);
gep.calculateRowProfit(e, false);
return false;
},
onArrowClicked: function(e){
gep.onArrowClick(e);
return false;
}
});
//$('.gep-unmatched', tr).html($('.gep-unmatched', tr).html());
$('.gep-odds', tr).gep_inputcontrol({
type:'PRICE',
value:order.requestedPrice,
decimalValue:order.requestedPrice,
onMouseWheeled: function(e, ev){
gep.inputControlWheeled(e, ev);
gep.calculateRowProfit(e, false);
return false;
},
onArrowClicked: function(e){
gep.onArrowClick(e);
return false;
}
});
$('.gep-action .gep-icon', tr).addClass("gep-icon-delete");
$('.gep-icon-delete', tr).bind("click", function(){
alert("delete");
toggleCurrentBetSlipBet(this);
return false;
});
}
// })(_table, tr, i, unmatchedStake, tablerow);
return tr;
}
The textbox plugin creates a table with input box and two anchor tags.
/********************
GEP.gep_inputcontrol // stake input, price input box
********************/
(function ($) {
var _templatePrice = $('<table class="gep-inputcontrol" cellpadding="0" cellspacing="0"><tr><td rowspan="2"><input type="text" size="5" class="gep-inputcontrol-price" /></td><td><a tabindex="-1" href="javascript:void(0);" class="gep-inputup"></a></td></tr><tr><td> <a tabindex="-1" href="javascript:void(0);" class="gep-inputdown"></a> </td></tr></table>');
var _templateStake = $('<table class="gep-inputcontrol" cellpadding="0" cellspacing="0"><tr><td rowspan="2"><span class="gep-ccsymbol" /> <input type="text" size="5" class="gep-inputcontrol-stake" /> </td> <td> <a tabindex="-1" href="javascript:void(0);" class="gep-inputup"></a></td></tr><tr><td> <a tabindex="-1" href="javascript:void(0);" class="gep-inputdown"></a> </td></tr> </table>');
var _template;
var _settings = null;
var _instance;
var methods = {
init: function (options) {
_settings = options;
//options.type = 'STAKE'or 'PRICE'
_template = (options.type == 'STAKE')? _templateStake: _templatePrice;
$('.gep-ccsymbol',_template).html(options.ccSymbol);
this.html(_template);
$('input', this).attr('value', options.value);
$('input', this).attr('initialvalue', options.decimalValue);
$('input', this).attr('decimalValue', options.decimalValue);
$('input', this).bind("mousewheel", function (ev) {
_settings.onMouseWheeled.call(null, this, ev.originalEvent);
});
$('.gep-inputup', this).bind("click", function (e) {
_settings.onArrowClicked.call(null, this);
});
$('.gep-inputdown', this).bind("click", function (e) {
_settings.onArrowClicked.call(null, this);
});
_instance = this;
return this;
},
show: function (params) {
alert("show" + params);
},
hide: function () {
// GOOD
},
update: function (content) {
// !!!
}
};
$.fn.gep_inputcontrol = function (method) {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.gep_inputcontrol');
}
};
})(jQuery);
To elaborate a bit more, I did some small unit tests
This works..
$('.gep-odds', clientObject.liveBetsPane).gep_inputcontrol({
type: 'PRICE',
value: 5,
decimalValue: 5,
onMouseWheeled: function (e, ev) {
gep.inputControlWheeled(e, ev);
gep.calculateRowProfit(e, false);
return false;
},
onArrowClicked: function (e) {
gep.onArrowClick(e);
return false;
}
});
This does NOT work...(Only puts TEXT box in last row) But I need to do it this way as I need values of each row.
$('.gep-odds', clientObject.liveBetsPane).each(function () {
$(this).gep_inputcontrol({
type: 'PRICE',
value: 5,
decimalValue: 5,
onMouseWheeled: function (e, ev) {
gep.inputControlWheeled(e, ev);
gep.calculateRowProfit(e, false);
return false;
},
onArrowClicked: function (e) {
gep.onArrowClick(e);
return false;
}
});
});
I removed dollar from the template and it worked fine.
var _templatePrice = $('<table cla...
is now
var _templatePrice = '<table cla...
Although it sets the html for the last row it was moving for the other rows.
Thanks to me.... :)

Categories

Resources