i am trying calculate the amount but having troble with jQuery .. can you guys please tell me whats wrong with my codes.
my Javascript and jQuery codes are:
i have change this as:
$(document).ready(function() {
$('.home_banner').cycle({
fx: 'fade'
});
$("#tabs").tabs();
});
and calculator codes as:
var u_rate = new Array();
u_rate[0] = new Array();
u_rate[0][0] = 1.022;
u_rate[0][1] = 0.75;
u_rate[1] = new Array();
u_rate[1][0] = 1.034;
u_rate[1][1] = 0.78;
calc();
function calc(){
var result = '';
var id = '';
id = 'u';
curr = u_rate;
var curin_id = jquery("#"+id+"currency_in").attr("selectedIndex");
var curout_id = jquery("#"+id+"currency_out").attr("selectedIndex");
var value_float = parseFloat(jquery("#"+id+"value").val());
if(value_float>0){
result=value_float*curr[curin_id][curout_id];
result=Math.round(result*100)/100;
}
jquery("#"+id+"result").val(result);
return true;
}
but still getting no response .. please check this and let me know
and the html is
please check on ukash2gold.com
please friends let me know how to resolve the issue ..
u will able to see the form under the tab of [Ukash to LR]
typeof jQuery yields "function" but typeof $ yields "undefined". Are you loading jQuery in noConflict mode?
Edit 1
Yes you are; your slideshow code starts off like this:
var $jnav=jQuery.noConflict();
See noConflict.
Edit 2
As far as I can tell, you're not using any other framework that uses the $ variable. In that case, you can safely remove noConflict from your slideshow:
<script type="text/javascript">
$(function() {
$('.home_banner').cycle({
fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
});
$("#tabs").tabs();
});
</script>
If you're using another framework somewhere else on the site, and need to stick to running jQuery in noConflict mode, you'll have to modify your jQuery code to use jQuery rather than the $ shorthand.
jQuery('#'+id+'result').val(result);
... etc.
Edit 3
Now you're seeing the error Uncaught TypeError: Cannot read property 'undefined' of undefined at this line:
result=value_float*curr[curin_id][curout_id];
What this means is, in your case, that curin_id and curout_id are both undefined. Therefore you're trying to access a property 'undefined' (curout_id) at the object 'undefined' (curr[curin_id] which will yield undefined since curin_id is in itself undefined).
The cause for this is the following code:
var curin_id = $("#"+id+"currency_in").attr("selectedIndex");
var curout_id = $("#"+id+"currency_out").attr("selectedIndex");
selectedIndex is not an attribute of the select but a property of it. Although properties are native JavaScript constructions, you can read about them in the jQuery documentation.
A simple fix in your case would be to change from attr() to prop():
var curin_id = $("#"+id+"currency_in").prop("selectedIndex");
var curout_id = $("#"+id+"currency_out").prop("selectedIndex");
Another solution would be to look at the index of the selected element, within its parent:
var curin_id = $('#'+id+'currency_in option:selected').index();
Related
Reading the bootstrap 4 code (how they register pluging in jquery) I can't understand several lines:
https://github.com/twbs/bootstrap/blob/v4-dev/js/src/tooltip.js
1) Why author add to method Tooltip._jQueryInterface the Constructor property ? What kind of functionalyt they try to provide with that?
$.fn[NAME] = Tooltip._jQueryInterface // this is clear
$.fn[NAME].Constructor = Tooltip // mmmmm ?
2) what is done there (added noConflict method, but how it will be used?):
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT
return Tooltip._jQueryInterface
}
Now I know the answer on question two (wth is $.fn[NAME].noConflict = function () {..}).
According to https://getbootstrap.com/docs/3.3/javascript/#js-noconflict
This plugins noconflict method can be used such way:
var bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
I want to call jquery plugin function from my page, but I fail:(. My code is:
var pstps=$('#psteps_simple_horiz_layout').psteps({
steps_width_percentage: true,
alter_width_at_viewport: '1300',
steps_height_equalize: true
});
step_num=2;
pstps.go_to_step(step_num);
The plugin is Pine Steps wizard. It's code is:
function($) {
$.fn.psteps = function(options) {
// Build main options before element iteration.
var opts = $.extend({}, $.fn.psteps.defaults, options);
// Iterate and transform each matched element.
var all_elements = this;
all_elements.each(function(){
var psteps = $(this);
psteps.psteps_version = "0.0.1alpha";
.......................................................
psteps.go_to_step = function(step_num){
var last_active_title = psteps.find('.step-title.last-active'),
.......................................................
};
.......................................................
this.pines_steps = psteps;
});
return all_elements;
};
When I run my code I get error:
Uncaught TypeError: undefined is not a function
It is failing on the following line because go_to_steps is not a jQuery extension (and the return value from psteps() is the original jQuery object:
pstps.go_to_step(step_num);
You need the instance of the actual plugin. Looking at the plugin code, it connects the instance as a property on the DOM element called pines_steps, so you need to get that property as your class instance:
var pstps=$('#psteps_simple_horiz_layout').psteps({
steps_width_percentage: true,
alter_width_at_viewport: '1300',
steps_height_equalize: true
})[0].pines_steps;
Then you can call
pstps.go_to_step(step_num);
Common pattern:
The usual way plugins are authored is to also accept a function name, as a string, in a first parameter, so they can call methods like this:
$('#psteps_simple_horiz_layout').psteps("go_to_step", step_num);
however this plugin is missing the code to do that
I ran yesterday in a problem with a jquery-selector I assigned to a variable and it's driving me mad.
Here is a jsfiddle with testcase:
assign the .elem to my obj var
log both lengths to the console. Result => 4
Remove #3 from the DOM
log obj to the console => the removed #3 is still there and the length is still 4.
I figured out that jquery query is snapshotted? to the variable and can't?won't? be updated
log .elem to the console.. yep Result => 3 and the #3 is gone
Now I update .elem with a new width of 300
logging obj & obj.width gives me 300.. So the snapshot has been updated ? What's interesting is that 3 of the 4 divs have the new width, but the removed #3 doesn't...
Another test: Adding a li element to the domtree and logging obj and .elem.
.elem does have the new li and obj doesn't, because it's still the old snapshot
http://jsfiddle.net/CBDUK/1/
Is there no way to update this obj with the new content?
I don't want to make a new obj, because in my application there is a lot information saved in that object, I don't want to destroy...
Yeah, it's a snapshot. Furthermore, removing an element from the page DOM tree isn't magically going to vanish all references to the element.
You can refresh it like so:
var a = $(".elem");
a = $(a.selector);
Mini-plugin:
$.fn.refresh = function() {
return $(this.selector);
};
var a = $(".elem");
a = a.refresh();
This simple solution doesn't work with complex traversals though. You are going to have to make a parser for the .selector property to refresh the snapshot for those.
The format is like:
$("body").find("div").next(".sibling").prevAll().siblings().selector
//"body div.next(.sibling).prevAll().siblings()"
In-place mini-plugin:
$.fn.refresh = function() {
var elems = $(this.selector);
this.splice(0, this.length);
this.push.apply( this, elems );
return this;
};
var a = $(".elem");
a.refresh() //No assignment necessary
I also liked #Esailija solution, but seems that this.selector has some bugs with filter.
So I modified to my needs, maybe it will be useful to someone
This was for jQuery 1.7.2 didn`t test refresh on filtered snapshots on higher versions
$.fn.refresh = function() { // refresh seletor
var m = this.selector.match(/\.filter\([.\S+\d?(\,\s2)]*\)/); // catch filter string
var elems = null;
if (m != null) { // if no filter, then do the evarage workflow
var filter = m[0].match(/\([.\S+\d?(\,\s2)]*\)/)[0].replace(/[\(\)']+/g,'');
this.selector = this.selector.replace(m[0],''); // remove filter from selector
elems = $(this.selector).filter(filter); // enable filter for it
} else {
elems = $(this.selector);
}
this.splice(0, this.length);
this.push.apply( this, elems );
return this;
};
Code is not so beautiful, but it worked for my filtered selectors.
Clean and generic solution worked properly with jQuery 3.4.1:
My solution is to do the following:
Intercept the selector at the time of jQuery object initialization and in the same time maintain all other jQuery functionalities transparently all this using inheritance
Build refresh plugin that make use of the new "selector" property we added during initialization
Definition:
$ = (function (originalJQuery)
{
return (function ()
{
var newJQuery = originalJQuery.apply(this, arguments);
newJQuery.selector = arguments.length > 0 ? arguments[0] : null;
return newJQuery;
});
})($);
$.fn = $.prototype = jQuery.fn;
$.fn.refresh = function ()
{
if (this.selector != null && (typeof this.selector === 'string' || this.selector instanceof String))
{
var elems = $(this.selector);
this.splice(0, this.length);
this.push.apply(this, elems);
}
return this;
};
Usage:
var myAnchors = $('p > a');
//Manipulate your DOM and make changes to be captured by the refresh plugin....
myAnchors.refresh();
//Now, myAnchors variable will hold a fresh snapshot
Note:
As optimization, object selectors don't need refresh as they are pass by reference by nature so, in refresh plugin, we only refresh if the selector is a string selector not object selector for clarification, consider the following code:
// Define a plain object
var foo = { foo: "bar", hello: "world" };
// Pass it to the jQuery function
var $foo = $( foo );
// Test accessing property values
var test1 = $foo.prop( "foo" ); // bar
// Change the original object
foo.foo = "koko";
// Test updated property value
var test2 = $foo.prop( "foo" ); // koko
Jquery .selector is deprecated, it's better to remeber string with selector value to some variable at the moment when you assign
function someModule($selector, selectorText) {
var $moduleSelector = $selector;
var moduleSelectorText = selectorText;
var onSelectorRefresh = function() {
$moduleSelector = $(moduleSelectorText);
}
}
https://api.jquery.com/selector/
You can also return the JQuery selector in a function, and save this function into the variable. Your code will look a bit different but it works. Every time when you execute the function, your jquery selector will search the DOM again.
In this example I used an arrow function without brackets which will return whatever is next to arrow. In this case it will return the JQuery collection.
const $mySelector = () => $('.selector');
console.log($mySelector().last().text());
$('.parent').append('<li class="selector">4</li>')
console.log($mySelector().last().text()); //RETURNS 4 not 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="parent">
<li class="selector">1</li>
<li class="selector">2</li>
<li class="selector">3</li>
</ul>
If you use remove() it will remove only a part of the DOM but not all the children or related, instead if you use empty() on the element the problem is gone.
E.G.:
$('#parent .child).find('#foo').empty();
Maybe it can be useful to someone!
I'm having a very hard time understanding how to setup an object that allows me to test my jQuery calls. I don't need to mock any Async calls or anything, just basic use. So let me set out my function that I want to test (truncated for simplicity):
listGamesCallback : function(data) {
var gameList = $("#gameList select");
gameList.empty();
$.each(data, function() {
var newOption = $('<option>', {value : this.gameId });
newOption.text(string);
newOption.data("isJoinable", isJoinable);
// Add it to the list
gameList.append(newOption);
});
}
I need to mock the jQuery here to unit test this method, but I'm unable to figure out how to do this in javascript. Even without jsMockito, I don't know how to create an object with the properties that jQuery has in this situation. Any help with this would be appreciated.
I am using jsTestDriver, jsHamcrest, jsMockito and jQuery. However a generalized approach to create a $ object that has these properties would be awesome as well. Thank you!
For those that asked, here is what I came up with that seemed to kinda work..but I don't understand why.
var saved$ = $;
var mockContruct = mockFunction();
var mockedGamelist = mock(jQuery);
var mockedOption = mock(jQuery);
mocked$ = (function() {
var test = function(name) {
var args = jQuery.makeArray(arguments);
return mockContruct.call(test, args);
};
$.extend(test, $);
// This is what confuses me. This worked, but it's wierd
// It allows me to use the regular jQuery functions like
// $.each, while returning mocked objects when selectors are used.
test.prototype.constructor = test;
return test;
})();
$ = mocked$;
when(mockContruct).call(anything(), hasItem(containsString("#gameList")))
.thenReturn(mockedGamelist);
when(mockContruct).call(anything(), hasItems(containsString("<option>"), both(object()).and(hasMember("value"))))
.thenReturn(mockedOption);
headerFunctions.listGamesCallback([ {
gameId : 1,
isWhitesTurn : false,
isGameOver : false,
whiteUserName : "foobar",
blackUserName : "barfoo"
} ]);
JsMockito.verify(mockedGamelist).empty();
JsMockito.verify(mockedGamelist).append(mockedOption);
$ = saved$;
Ok, here what I came up with that does the job with minimal setup. The .extend is completely necessary here so that the jQuery object is setup correctly. This allows you to mock the constructor to return mocked jQuery objects that you can use to run your tests on. As a spy, jQuery will work as expected in all situations except when you want it to do something else. Here it is:
TestCase("HeaderTest", {
testListGamesCallback : function () {
var saved$ = $;
$ = $.prototype.construct = jQuery.extend(spy(jQuery), jQuery);
var mockGameList = mock(jQuery);
when($)(containsString("#gameList")).thenReturn(mockGameList);
headerFunctions.listGamesCallback([ {
gameId : 1,
isWhitesTurn : false,
isGameOver : false,
whiteUserName : "foobar",
blackUserName : "barfoo"
} ]);
verify(mockGameList).empty();
verify(mockGameList).append(object());
$ = saved$;
}
});
The caveat to this solution is that mocking anything other than the constructor is a bit tricky. You will have to set each individual function that you want to mock, then program the behavior. So:
$.each = mockFunction();
when($.each)(...matchers...).thenReturn(...);
But it still allows for testing what you need to.
As an extension to alpian's answer, you can create DOM elements without having to add them to the page. Make your JS functions take the relevant elements as parameters:
listGamesCallback : function(data, gameListSelectElem) {
var gameList = $(gameListSelectElem);
...
and test them like so:
var fakeSelect = $('<select>'),
data = ...;
listGamesCallback(data, fakeSelect[0]);
equal(fakeSelect.find('option').length, 1, 'must have exactly 1 option');
...
The last line of code above is for qUnit. Take whatever you need, the point is to say you can pass a DOM element that was never added to the page and afterwards investigate that DOM element using jQuery to find whether it was manipulated right.
No sure if i understand what you mean but if you want to create 'data' for you example , this is the method i know:
var data = [ { id : 1 , name : 'foo' } , { id : 2, name : 'bar' ]
but - if you wanted to create a list of options, than you code needs a couple of fixes:
see http://jsfiddle.net/7MMap/
var data = [ { gameId : 1 , name : 'foo' ,isJoinable:true} , { gameId : 2, name : 'bar' ,isJoinable:false}]
listGamesCallback = function(data) {
var gameList = $("#gameList select")
.empty();
$.each(data, function(i,d) {
var newOption = $('<option>', {value : d.gameId })
.text(d.name)
.data("isJoinable", d.isJoinable);
// Add it to the list
gameList.append(newOption);
})
};
listGamesCallback(data);
Mocking jQuery is not what mocking is for. You should only ever be mocking your object's collaborators. jQuery is providing you with some utilities - it's not a collaborator and hence should not be mocked.
What you are collaborating with here is the DOM, or some intermediate object between your code and the DOM. data is a value object and can simply be created in your test as Avi suggests.
In my JS tests, i don't mock the DOM, i use the real DOM and am sure to tear down anything i created between tests and this seems to work pretty well.
I don't think I'm the first one to run into this issue but I haven't find a way to search for this without getting results that have nothing to do with the issue.
I adopted the not so extended good practice of "caching" repetitive jQuery selections into vars like var element = $('#element'); to prevent "DOM pool searching" for every repeated use of the element
The problem I'm having is that now I'm doing this caching inside a function. Something like:
function functionname (id) {
var id = $('#'+id);
//extra stuff
}
I'm not expert in variables scopes but I'm not being able to do
functionname ('some-div-id');
some-div-id.dialog('open');
So I'm pretty sure it's because the variable created inside the function is not accesible outside the function itself.
Then I came up with
function functionname (id) {
window.id = $('#'+id);
//extra stuff
}
but if I try to do window.some-div-id.dialog('open'); I get TypeError: 'undefined' is not a function
What am I missing? I'm sure it's a small dumb thing but I'm missing it just in front of my eyes.
Thanks
EDIT
Thanks everyone but you're missing something.
The code suggestions are missing the fact that the inside "global" variable name is dynamic:
var CACHEobject = {};
function doSomething (NAMEHERE) { //note the function parameter
CACHEobject.NAMEHERE = $('#'+NAMEHERE);
}
So the idea is that the function creates a javascript variable with the same name that the #element_id. If I pass a name to the function it should select the html id with that name and "cache it" to a global variable with the same name:
doSomething('myDialogOne'); doSomething('myDialogTwo');
so I can later do
CACHEobject.myDialogOne.dialog('open'); CACHEobject.myBox.dialog('close');
This is what you want (based off the edit):
var CACHEobject = {};
function doSomething(id) {
CACHEobject[id] = $('#' + id);
}
Your idea is fine. Just set up an object for that. Here's an example using STASH as the caching object:
<html>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var STASH = {};
$(document).ready(function(){
// stash your elements
STASH.item = $('#item');
STASH.otherItem = $('#otherItem');
// do stuff to them
STASH.item.css({
color: '#f00'
}); // sets #item to red
alert(STASH.otherItem.text()); // alerts foo
});
</script>
<style></style>
<body>
<div id="item">bar</div>
<div id="otherItem">foo</div>
</body>
</html>
window.some-div-id.dialog('open');
is interpreted as:
window.some - div - id.dialog('open');
i.e. subtracting, which causes three undefined variables, one of which is id.dialog which causes an error when trying to be executed as a function.
For special characters, use:
window["some-div-id"].dialog('open');
And to define:
window[id] = $("#" + id);
Anyhow, I would not advise you to use global variables. You'd better overwrite the jQuery function to implement caching (using an object with the selector as key and the matched element as value).
You could just declare the variable outside the function.
var $foo;
function some_function(id) {
$foo = $('#' + id);
}
function setDialog(selector) {
window.$dialogElem = $(selector);
//window.dialogSelector = selector;
}
var id= 'mensajes';
setDialog('#'+id);
window.$dialogElem.dialog();
//$(window.dialogSelector).dialog();
commented stuff is an alternative that takes less memory. But why the hell use window?? check this fiddle for various simple techniques.