[jQuery] Re: Passing value from function
On Feb 18, 9:15 pm, Charlie22 ch...@post.cz wrote: Hi all, I have trouble passing value as selector value to other function. $(document).ready(function(){ var id = 'Test'; $('#Name').keyup(function(){ id = '#Mobil'; If you want variables to be local to their enclosing function, declare them with var. The variable id has a closure to id in the outer function. Before the keup runs, id is 'Test'. Afterward, its value is #Mobil. }); $(id).click(function(){ I guess that should be: $('#' + id).click(function(){ console.log(id); This id also has a closure to the outer id. }); }); I am getting on console value #Mobil but $(is) is using value Test. Thx for help in advance. All the id variables above refer to the same property of the same activation object (i.e. they are essentially the same variable). Modifying any one of them modifies the others. -- Rob
[jQuery] Re: What is the proper way to write this if statement?
On Jan 14, 11:00 am, Matt Maxwell leftwithoutli...@gmail.com wrote: [...] var that = this; // scope The value of the this keyword has nothing whatever to do with scope. -- Rob
[jQuery] Re: ANNOUNCE: new rev of credit card validation extension
On Jan 14, 3:29 am, Jack Killpatrick j...@ihwy.com wrote: Hi All, We've released a new version of our jQuery Validation plugin credit card extension. It is likely that such validation is more hassle than it's worth... Changes include: 1. updated card prefixes (including latest Discover Card changes) 2. support for LaserCard ...because you have to keep upadting the data and possibly the algorithms and the data object structure if it turns out it isn't suitable - perhaps cards have different rules depending on the prefix or number of characters, the plugin data structure can't handle that. If this is intended for an online payment system, it is more effective to just give the data to the payment system and let it work it out. Otherwise you are potentially preventing users from accessing the payment system even though their details are valid and you can't be sure that you've prevented invalid data being sent - so what do you really gain? The code itself seems a bit verbose and has redunant checks, e.g. value = value.replace(/[\s-]/g, ); // remove spaces and dashes if (value.length == 0) { return false; } // no length /* RG This test is redundant. If the cardNumber has fewer than the required number of digits it will fail the test below. */ var cardNo = value; /* RG value has already beem modified from the value passed, there doesn't seem much point in protecting its value now. */ var cardexp = /^[0-9]{13,19}$/; if (!cardexp.exec(cardNo)) { return false; } // has chars or wrong length cardNo = cardNo.replace(/\D/g, ); // strip down to digits /* RG cardNo has already had spaces removed and been checked to ensure that it contains only digits. What is left to remove? Also, the two tests use different (though likely practically identical) patterns: [0-9] vs \D. */ The code implementing the Mod 10 algorithm is inefficient and verbose, some comments: var checksum = 0; var mychar = ; mychar is not used. var j = 1; var calc; for (i = cardNo.length - 1; i = 0; i--) { calc = Number(cardNo.charAt(i)) * j; There is no need for the call to Number(), multiplication will convert the string to a number anyway. if (calc 9) { checksum = checksum + 1; calc = calc - 10; } checksum = checksum + calc; All of that can be replaced with: checksum += (calc 9)? calc - 9 : calc; The line: if (j == 1) { j = 2 } else { j = 1 }; That can be: j = (j%2) + 1; } if (checksum % 10 != 0) { return false; } // not mod10 Consider: return !(checksum%10); or perhaps: return /0$/.test(checksum); If the function is called frequently, the regExp can be stored in a closure - whatever suits. An alternative Mod 10 implementation is: var acc = cardNo.split(''); var i = acc.length; var j = 0; var n; var sum = 0; while (i--) { n = (j++ % 2)? acc[i] * 2 : acc[i]; sum += (n 10)? n - 0 : n - 9; } return !(sum%10); The prefix and length checks can also be done in less code (4 or 5 lines) and more efficiently using regular expressions. -- Rob
[jQuery] Re: long-term browser support strategy
On Jan 12, 1:24 pm, Nathan Klatt n8kl...@gmail.com wrote: IE 6 use is 3 times that of Safari (all versions) depending on whose statistics you believe. Why not drop support for Safari while you're at it? And Opera and Chrome? Because you don't have to do anything to support Safari or Chrome or Opera There are at least 5 Safari-specific quirks catered for in jQuery (I just searched for Safari in comments), there are likely others. Admittedly that's far fewer than are required for IE, but since IE 6 is now about 10 years old, surely it's quirks are well known and catered for? - they actually work. To stop supporting them you'd have to stop supporting standards. Browsers will continue to evolve. If appropriate feature detection is already in place and effective alternatives provided to handle quirks, you may find that you are handling some new quirks without having to write a single line of code. :-) For example, while the bit in jQuery that checks if the event.target is a textNode is meant for Safari (pre version 3 I think), it will work for any browser that has such behaviour. Safari's behaviour was actually compliant with the spec, the far more common behaviour (i.e. that event.target is always a nodeType 1) is not compliant. I work with several clients that do not want to lead the way in this respect, and need to support IE6 as long as it has a fair usage share, which may be for several more years.] That is a sensible decision Anyone clinging to IE6, at this point, has gone wy beyond not leading the way! If w3schools' statistics are at all accurate, there are about the same number of people using IE 6 as either IE 7 or 8. Of course support might mean whether new functionality is provided for old browsers and whether they continue to be part of a test suite. New functions that aren't tested in old browsers can simply be marked in the documentation, or simply features add after version x.y have not been tested in browser X so users know not to use them. -- Rob
[jQuery] Re: Argh!! IE8!
On Jan 12, 5:51 am, Valerij valeri...@gmail.com wrote: Hey guys, I have this popup menu that works.. great! In Chrome, Safari, Firefox AND it USED to work in IE8, until I added just 1 div. [...] This works in all the browsers great even after I added this div, but in IE8 it suddenly stopped. a id=acc class=baritem href=javascript:void(0);div class=textupMy Account/div/a Your markup is invalid, div elements don't belong inside a elements. [...] Is there a fix for this? Start with valid markup: URL: http://validator.w3.org/ -- Rob
[jQuery] Re: long-term browser support strategy
On Jan 11, 10:47 pm, mikewse mike...@gmail.com wrote: What is jQuery's long-term strategy for browser support - cut off browsers after a certain number of years or when going below a certain market share? [I'm asking because of the current trend (among some webdevs and also library developers) advocating to remove IE6 support and force these users to upgrade their browser. IE 6 use is 3 times that of Safari (all versions) depending on whose statistics you believe. Why not drop support for Safari while you're at it? And Opera and Chrome? I work with several clients that do not want to lead the way in this respect, and need to support IE6 as long as it has a fair usage share, which may be for several more years.] That is a sensible decision - they should not care what browser their visitors are using any more than the colour shoes they might be wearing. If support for the quirks of a particular browser is already built into a library, and the library architecture efficiently implements capability and feature detection to work around them, why go to the effort of removing support? -- Rob
[jQuery] Re: looping through form elements.
On Jan 8, 8:33 am, rich dottedq...@gmail.com wrote: Hello all, I'm relatively new to JavaScript. I would like to loop through all the elements within a form and grab their values and what type of input they are. So far I came up with: $(':input').each(function(idx, item) { alert(idx); }); There are lots of form controls that aren't input elements. They are all in the form's elements collection. The alert is placed there to see if it loops and it works as expected. I'm not sure how to alert the input's value and what type it is. Any help is greatly appreciated. A form element's value is stored in its value property, its type is stored in its type property. So: var el, elements = document.forms[formName].elements; for (var i=0, len=elements.length; ilen; i++) { el = elements[i]; alert( el.type + ': ' + el.value); } -- Rob
[jQuery] Re: Convert a string version of a json array to an actual json array
On Jan 5, 8:10 pm, Dave messedupp...@gmail.com wrote: Hi Wonder how I can convert a string to a json array. From what you've posted below, you want to process a string and treat parts of it as JSON objects. //start code var arrCss = [a___{'color':'red','font-weight':'bold'}, h1,h2___ {'color':'blue'}]; Why not create it as a valid JSON object? for(var i = 0; i arrCss.length; i++){ var snip = arrCss[i].split(___); $(snip[0]).css(snip[1]); } //end code The problem is that .css() treats snip[1] as a string but I need it to handle it as a json array. You don't want it to be a json[sic] array, you want parts of the string converted to an object with properties and string values, which might be called a JSON object. You could use: ...css(eval('(' + snip[1] + ')')); A better solution might be to use a JSON object for the whole thing, e.g.: var xString = { + 'a':{'color':'red','font-weight':'bold'}, + 'h1,h2':{'color':'blue'} + }; var xObj = eval('(' + xString + ')' ); for (var selector in xObj) { alert(xObj[selector].color); // red, blue } Which might be used in your posted code as: var xObj = eval('(' + xString + ')' ); for (var selector in xObj) { $(selector).css(xObj[selector]); } Bad: .css({'color':'red','font-weight':'bold'}); Good: .css({'color':'red','font-weight':'bold'}); -- Rob
[jQuery] Re: js function to jQuery
On Dec 23, 2:06 pm, Leonardo Balter leonardo.bal...@gmail.com wrote: Nah, make it sexier, use parenteses (tip from the new John Resig's ebook): ( var $ = window.jQuery; $(#CollapseExpandTd).click( function() { $(#TreeviewTd).toggle(); $(#MenuBarTd).toggle(); }); ); $ will be a local variable and unicorns will come to see the magic running around. Yeah, maybe they can read and will tell you what the syntax error is all about. -- Rob
[jQuery] Re: js function to jQuery
On Dec 23, 6:58 am, jqHunter tinu.punn...@gmail.com wrote: Hi All, I have the following js function used in an old web app. How can I translate this to equivalent jQuery code? Appreciate your help! function expandCollapse_onclick() { var treeCell = document.getElementById(TreeviewTd); var topmenuCell = document.getElementById(MenuBarTd); var collapseExpandCell = document.getElementById (CollpaseExpandTd); if (treeCell.style.display == '') { treeCell.style.display = 'none'; topmenuCell.style.display = 'none'; } else { treeCell.style.display = ''; topmenuCell.style.display = ''; } } You could consider re-factoring the functions into a library so you write less code, e.g. function toggle() { var i = arguments.length, el, s; while (i--) { el = getEl(arguments[i]); s = el el.style; if (s) { s.display = (s.display == 'none')? '' : 'none'; } } } function getEl(id) { return (typeof id == 'string')? document.getElementById(id) : id; } Now the click function becomes: toggle('TreeviewTd','MenuBarTd'); -- Rob
[jQuery] Re: jQuery website search function
On Dec 22, 10:51 pm, Schalk Neethling volume4.sch...@gmail.com wrote: Hi there, I was wondering whether anyone knows if the jQuery website has some sort of API to access the search functionality of the site? Stimulus, response... form action= div input type=text name=queryText value=events input type=button value=Search... onclick= searchDocs(this.form.queryText); /div /form script type=text/javascript function searchDocs(el) { document.location = 'http://docs.jquery.com/Special:Search?ns0=1search=' + encodeURIComponent(el.value) + 'go='; } /script -- Rob
[jQuery] Re: AND OR Expression
On Dec 11, 5:46 am, MorningZ morni...@gmail.com wrote: This isn't working out for me Expecting it to? First post you were comparing: string string... which isn't going to work Why not? If the strings are digits that convert to numbers, it will work. Granted it isn't particularly robust, but: '2' '4' and 2 '4' produce exactly the same result, read ECMA-262, 11.8.5. Follow up post after blowing right over Richard's suggestion, you are comparing string number, which *still* isn't going to work... Provided both convert to expected integers, it will (see above). and this line doesn't make any sense var td4th = parseInt($('td:nth-child(4)', jQuery (this))); as you are parseInt-ing a jQuery object It will most likely cause the result to be NaN (ECMA-262 15.1.2.2 #6~8) -- Rob
[jQuery] Re: Selectors and Internet Explorer
On Dec 11, 7:12 am, Josh Nathanson joshnathan...@gmail.com wrote: Maybe try closing the option tag? The closing tag is optional, there are numerous elements that don't need closing tags in HTML. -- Rob
[jQuery] Re: Replacing brs in a div
On Dec 10, 3:24 am, T.J. Simmons theimmortal...@gmail.com wrote: Yeah, I wasn't really sure it would work, but thought it was worth a try. And the br/ br thing I think depends on the browser used and the rendering mode it's forced into. What doctype are you using? And for some more thought, Firefox (using !doctype html) renders br as br, but IE8 will show them as BR, so.. see what you're getting and do a replace on all possible combos, that's my thought. So by trying to use an inappropriate method, you slowly build increasing complexity where there should be none. If the intention is to collect text nodes and replace BR nodes with new lines, then: function specialGetText(el) { var text = '', node, nodes = el.childNodes; for (var i=0, iLen=nodes.length; iiLen; i++) { node = nodes[i]; if (node.nodeType == 3) { text += node.data; } else if (node.tagName.toLowerCase() == 'br') { text += '\n'; } } return text; } Should do the job. -- Rob
Re: [jQuery] New site with jquery: Cpluv
Escape-Artist wrote: Which site are you talking about? You can check out more about us: Shaperstudio on http://www.shaperstudio.com our site There's no flash on the cpluv site. Great, but the home page is over 800kb, half of which is script. Good luck. -- Rob
[jQuery] Re: New site with jquery: Cpluv
On Dec 8, 10:51 am, Escape-Artist tho...@shaperstudio.com wrote: Hey all! We just finished a site that is using a whole lot of jquery ( for ajax submit, tabs, dialogs, transitions, DOM manipulations, ... ) Yeah! Great site! All I got was: Sorry, you need the flash player to see this page! ( or upgrade your flash player version ) Enabling scripting lead to a large Flash download. Sorry, didn't wait. And here I was hoping Flash-based splash pages were a thing of the past. It says to your visitors: We think your time is so worthless, we're going to waste quite a bit of it making you wait to see our advertising. -- Rob
[jQuery] Re: Stop a button within an li taking the li event?
On Dec 2, 8:33 pm, Rich reholme...@googlemail.com wrote: I have an unordered list which slidesdown to reveal a sub list on click event. In the first li there is also a button that takes you to another page. When this button is pressed I don't want the slide down to start, which it currently does as the button is within the li. Click events bubble. If you don't want them to, cancel bubbling. Your markup is invalid, it has several serious errors. In particular, a form can't be a child of a span element, nor can an input be a child of a form element. Use a validator: URL: http://validator.w3.org/#validate-by-input [...] -- Rob
[jQuery] Re: Best Practices or unobtrusive Javascript
On Dec 1, 12:41 am, Scott Sauyet scott.sau...@gmail.com wrote: On Nov 29, 8:21 pm, breadwild breadw...@gmail.com wrote: I have seen several examples on jQuery plugin sites that have the script tag and Javascript within the body and not the head where I thought it was supposed to go. Supposed to go is a subjective consideration. The rationale for putting it at the bottom of the body is a fairly simple, and fairly persuasive, argument about performance. A nice short version of that is here: http://developer.yahoo.com/performance/rules.html#js_bottom But it doesn't tell the full story - the page will take the same amount of time to load. Putting scripts at the bottom means that the page is (possibly) displayed faster and the user has the impression that it loaded faster. The best way to improve performance is to reduce images to the minimum practical size, use plain HTML as much as possible, reduce script to a minimum and put it into as few files as possible (one or none). The rationale for putting it in the head is really one about being unobtrusive. Unobtrusive seems to mean different things to different people. URL: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript If JavaScript is used unobtrusively, then JS is never plain data, but always metadata. And the head is the place for metadata. Javascript is not metadata, it is program code: URL: http://www.google.com.au/search?q=define%3A+metadataie=utf-8oe=utf-8aq=trls=org.mozilla:en-GB:officialclient=firefox-a -- Rob
[jQuery] Re: selector performance
On Nov 12, 6:11 am, Karl Swedberg k...@englishrules.com wrote: Are those tests really using jQuery 1.1.4? If so, they're hardly relevant now, unless you're using a very old version of jQuery. The tests are relevant in the context of the article. The point is really about improving performance by not making calls that don't do anything, which is stating the obvious. -- Rob
[jQuery] Re: How to determine number of elements after dom manipulation ?
On Nov 4, 6:22 am, bakman bakman.bak...@gmail.com wrote: I am generating elements (img's) based on data from an xml file. Once that is done, I want to determine the number of icons that were generated. as naive as i am, i do a: alert($('img').size()) result: 0, which isn't the case how can i determine them after they have generated ? Why not: document.images.length Or increment a counter as you go. ** function dataloader(location,service,div){ $.ajax({ type: GET, url: includes/data.xml, dataType: xml, success: function(xml) { $(xml).find('group').each(function(){ if($(this).attr(name) == service){ $(this).find(Service).each(function(){ the $() function is expensive to run, so run it as infrequently as possible, e.g. $(xml).find('group').each(function(){ var element = $(this); if (element.attr(name) == service) { element.find(Service).each(function() { var type = $(this).find(Type).text() var host = $(this).find(Host).text() var name = $(this).find(Name).text() var site = $(this).find(Site).text() var service = $(this); var type = service.find(Type).text(); var host = service.find(Host).text(); var name = service.find(Name).text(); var site = service.find(Site).text(); and so on. -- Rob
[jQuery] Re: How to tell if option is selected when it always defaults to first value?
On Oct 25, 4:37 pm, Giovanni Battista Lenoci gian...@gmail.com wrote: nick ha scritto: select id=one option value=1 selectedone/option option value=2two/option option value=3three/option /select The right syntax is : option value=1 selected=selectedone/option Only if the OP is serving XHTML as XHTML, which is rare on the web. If the markup is being served as HTML (which covers the vast majority of web pages) then what the OP posted is valid markup. If there is no selected then it always defaults to first value. How can I tell if the page has loaded and no options have been selected? The selectedIndex value of the select element will be -1: URL: http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-85676760 This is the way the select element works, there is always a selected element, even if you don't interact with the element. There is no requirement for an option to be selected by default: URL: http://www.w3.org/TR/html401/interact/forms.html#edef-SELECT therefore you should not expect that one will be. It is prudent to include the selected attribute for the option that should be selected by default, even if it's the first one, as suggested by the HTML specification: | 17.6.1 Pre-selected options | | Zero or more choices may be pre-selected for the user. | [...] | Since user agent behavior differs, authors should ensure that each | menu includes a default pre-selected OPTION. -- Rob
[jQuery] Re: Jquery issue with IE 6 (works in chrome and firefox)
On Oct 25, 12:06 am, ram sriva...@gmail.com wrote: This works fine in chrome and firefox but does not in IE6. i am yet to try it out in IE 7. As you can see, i have an input field and when user enters a value and clicks on Save, Jquery $(span.saveLink).click (function() gets invoked which populates the SaveUserForm(pls note my input field is outside and its not enclosed in a form). The issue is, form gets submitted but except isNew set to 0 or 1, all other fields in Struts action show (empty string) when i do this in IE6 where as in Chrome and Firefox, form values get populated correctly in Struts. Action. I tried Firebug and did not complain of any javascript errors. What am i doing wrong? Please respond quickly as testing is blocked. I tried to replace $(form#saveUserForm input#userGuid).val(id); Why wouldn't you use: $(#userGuid).val(id); $(form#saveUserForm input#amount).val(value); $(form#saveUserForm input#totalAvailableStorage).val (totalAvailableStorage); with document.saveUserForm.userGuid=id; document.saveUserForm.amount=id; document.saveUserForm. totalAvailableStorage =id; but IE6 complains that those properties are undefined. The syntax you have used only works in IE if saveUserForm is the form's name, not its ID. Either change the attribute to the name, add a name attribute with the same value or use the following: document.forms['saveUserForm'].elements['userGuid'].value = ...; -- Rob
[jQuery] Re: Don't use onclick
On Oct 13, 1:34 pm, expresso dschin...@gmail.com wrote: I don't think it's too hyped. Having calls to javascript in your elements defeats the purpose of unobtrusively maintaining and using libraries like jQuery. The mechanism frequently used to attach such listeners is to add a class, id, name or some other attribute value designed to make the element identifiable specifically to add a listener. How is: div class=mySpecialClass ... hugely different to: div onclick=mySpecialListener() ... when both attributes can be added using exactly the same server logic, static template or whatever? The only difference is that in the first case, the client must do extra work to attach listeners that could have been added on the server directly. Consider also that in the second case, you don't care about a document ready or load event, or whether the user must wait for elements to be enlivened while other content loads. Not hip, not cool or funky, but very robust and avoids a bunch of issues. Adding listeners at the client simply because the chosen development library supports it is not a particularly convincing argument. -- Rob
[jQuery] Re: Don't use onclick
On Oct 13, 10:49 am, CoffeeAddict dschin...@gmail.com wrote: Am I wrong to say you should never use onclick in an element as this would be contrary to the purpose of using jQuery I think you have your design priorites backward. Firstly determine the functionality required, then how to best implement it. If that means using a library, then use it. If the library driving your design decisions, you might need to rethink using the library. which means onclick would totally bind mark-up to javascript? In a way that using a CSS selector to attach handlers doesn't? So it would not be unobtrusive in that case. The concept of unobtrusive javascript (i.e. attaching listeners at the client, rather than the server) is an implementation methodology that has been much hyped but probaby creates as many issues as it solves. -- Rob
[jQuery] Re: Select element in form?
On Oct 12, 7:12 am, zephyr marc.at.comp...@gmail.com wrote: Hi, I have a form and want to select a text input element _in that specific form_. This is my code: $(form [name= +formName + ] :text[name= +textInputField+ ])) Why not: $(document.forms[formName].elements[inputName]) -- Rob
[jQuery] Re: Unexpected $(document).ready() behavior when jQuery is loaded after the page
On Oct 8, 10:04 am, Ryan Crumley crum...@gmail.com wrote: I am experiencing unexpected behavior using $(document).ready() on a page where I inject jQuery after the page has loaded and then attach listeners to the ready event. The ready() event is never called using Firefox and Safari however it is called using IE. [...] function loadjquery() { var url = http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/ jquery.js; var head = document.getElementsByTagName(head)[0], done = false; var script = document.createElement(script); script.src = url; script.onload = script.onreadystatechange = function() { There is no onload attribute for script elements defined in HTML 4.01, therefore you should not expect that a script element will fire a load event. The fact that some browsers do and some don't should be enough to tell you that browser behaviour is inconsistent. You are unlikely to be able to reliably fix that with script. If you want a reliable indicator that a script has finished loading and is ready for use, put a statement at the bottom like: var SCRIPT_LOADED = true; -- Rob
[jQuery] Re: format number
On Oct 5, 12:13 am, Donny Kurnia donnykur...@gmail.com wrote: [...] 15,000 should only displayed to user. You should keep 15000 somewhere in the document. My favorite is using alt span alt=15000 class=format15,000/span alt is not a valid attribute for span elements. -- Rob
[jQuery] Re: jQuery - Random Selection
On Oct 4, 7:06 am, Charlie charlie...@gmail.com wrote: put all the bios in containers with same class, use javascript random() function to create a random index to show one of the bios $('.bioClass').hide() var bioIndex=Math.round(Math.random()*5) Using that formula, indices 0 and 5 have only half the chance of being returned as indices 1 to 4, so not a very random selection. Use floor or ceil for an even distribution, for speed use: var bioIndex = (Math.random()*6) | 0; which is the same as using Math.floor. To return a random integer between 0 and n, use: function getRandomInt(n) { return Math.random()*n | 0; } -- Rob
[jQuery] Re: jQuery - Random Selection
On Oct 4, 2:45 pm, RobG robg...@gmail.com wrote: [...] which is the same as using Math.floor. To return a random integer between 0 and n, use: That should have been: between 0 and n-1 inclusive. function getRandomInt(n) { return Math.random()*n | 0; } -- Rob
[jQuery] Re: Strip out all of the commas in numeric text field
On Sep 30, 6:27 am, factoringcompare.com firstfacto...@googlemail.com wrote: Thank you. JQuery is completly new to me. OK how des the belo code look? script $(document).ready(function(){ $(#test').blur(function () { $('#test').val($('#test').val().replace(/,/g,'')); You could do: this.value = this.value.replace(/,/g,''); and save yourself a few keystrokes (and a gazillion CPU cycles) :-) -- Rob
[jQuery] Re: window close function _
On Sep 30, 11:21 am, -JD- juhand...@gmail.com wrote: Al cerrar una pagina necesito llamar a otra para poder hacer algunos cambios en mi DB. Intenté con esto: $(window).unload( function () { alert(Bye now!); } ); Which is so much simpler than: window.onunload = function () { alert(Bye now!); }; -- Rob
[jQuery] Re: window close function _
On Sep 30, 2:02 pm, Mike McNally emmecin...@gmail.com wrote: In that it handles the case where distinct independent (mutually unaware, even) portions of the page may want their own unload callbacks invoked, I'd say so. If you like breaking fast history navigation, go for it. Better to avoid unload listeners altogether. -- Rob
[jQuery] Re: keepp getting NaN vlue
On Sep 28, 9:21 pm, runrunforest craigco...@gmail.com wrote: Hi, I'm making a calculator for freight customer It seems I'm on the right path. But there is two bugs i need help. The TOTAL TO PAY value always seem to appear as NaN at first instead of default 3. And the function of TOTAL TO PAY only work after checkbox is checkd, I need it work regarding to changing of input value not just checkbox. Consider something like; script type=text/javascript var updater = (function() { var distanceEl, weightEl, wresultEl, priorityEl, presultEl, grandtotalEl; var intRe = /\D/; var firstK = 3; var nextK = 1000; // Get the value of el function getValue(el) { var val = el.value.replace(/ /g,''); return !intRe.test(val)? Number(val) : NaN; } // Return reference to element using id function getEl(id) { return document.getElementById(id); } return { setup: function() { distanceEl = getEl('distance'); dresultEl = getEl('dresult'); weightEl = getEl('weight'); wresultEl = getEl('wresult'); priorityEl = getEl('priority'); presultEl = getEl('presult'); grandtotalEl = getEl('grandtotal'); updateEl = getEl('updateCell'); resetEl = getEl('resetButton'); distanceEl.onchange = updater.run; weightEl.onchange = updater.run; wresultEl.onchange = updater.run; priorityEl.onchange = updater.run; distanceEl.onchange = updater.run; resetEl.onclick = updater.runLate; if (updateEl) { var el = document.createElement('input'); el.type = 'button'; el.value = 'Update total'; el.onclick = updater.run; updateEl.appendChild(el); } updater.run(); }, run: function() { var d = getValue(distanceEl); var w = getValue(weightEl); var dCost = 0; var wCost = 0; var pCost = 0; // Check for errors, don't continue if found if ((!d d != 0) || d 0) { alert('Invalid distance, must be an integer.'); return; } else if ((!w w != 0 ) || w 0) { alert('Invalid weight, must be an integer.'); return; } // Calculate cost for distance if (d 0) { dCost = 3; --d; } dCost += d * 1000; dresultEl.innerHTML = 'USD' + dCost; // Calculate cost if (w 5) { wCost = (w - 5) * 5000; } wresultEl.innerHTML = 'USD' + wCost; // Add extra if priority if (priorityEl.checked) { pCost = 5000; } presultEl.innerHTML = 'USD' + pCost; grandtotalEl.innerHTML = 'USD' + (dCost + wCost + pCost); }, runLate: function() { window.setTimeout(updater.run, 0); } } })(); window.onload = updater.setup; /script form table tr td colspan=4Please enter whole numbers only. tr tdDistance (km) tdinput type=text id=distance value=1 td id=dresult td First km is USD30,000, additional km are USD1,000 each tr tdWeight (kg) tdinput type=text id=weight value=0 td id=wresult tdNo extra fee for goods under 5kg tr tdUrgent? tdinput type=checkbox id=priority td id=presult tdUrgent goods USD5,000 extra tr tdTotal to pay: td td id=grandtotal td tr tdinput id=resetButton type=reset tdinput type=submit td id=updateCell td /table /form -- Rob
[jQuery] Re: dans blog jquery calculate installment
On Sep 28, 1:26 pm, runrunforest craigco...@gmail.com wrote: Hi, I've got a script from dansblog (link herehttp://blog.pengoworks.com/index.cfm/2008/1/23/jQuery-Calculation-Plu...) I copied and presented it as below, its doesn't work. What I've done incorrectly ? Most such scripts are worth what you pay for them, or less. !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd; html xmlns=http://www.w3.org/1999/xhtml; head script type=text/javascript src=js/jquery-1.3.2.min.js/script script type=text/javascript $(function(){ // bind the recalc function to the quantity fields $(input[name^=qty_item_]).bind(keyup, recalc); Using the keyup event is not a good idea. You are running the listener far more often that it needs to, you only need to run it when the user has finished their input for a particular field (e..g. run it using blur). function recalc(){ // run the calc() method on each of the total fields $([id^=total_item]).calc( Where is calc() defined? User input should always be validated - what will happen if they input # instead of 3? // the equation to use for the calculation qty * price, // we now define the values for the variables defined in the Beware of those who talk about we. equation above { // instead of using a static value, we use a jQuery object which grabs all the quantities It grabs exactly the same set of inputs every single time the keyup event occurs. Why would you do that except to waste CPU cycles? qty: $(input[name^=qty_item_]), // now we define the jQuery object which reads in the price from the table cell price: $([id^=price_item_]) }, // this function is execute after the calculation is completed, which allows us to // add formatting to our value function (s){ // return the number as a dollar amount return $ + s.toFixed(2); In some implementations, toFixed is buggy, though likely it doesn't matter here. URL: http://www.merlyn.demon.co.uk/js-rndg1.htm#toF }, // once all calculations are completed, we execute the code below function ($this){ // now we get the sum() of all the values we just calculated var sum = $this.sum(); Where is sum() defined? Does it validate user input? // now that we have the grand total, we must update the screen $(#grandTotal).text( // round the results to 2 digits $ + sum.toFixed(2) If the values have already been rounded, their sum does not need to be rounded again. ); } ); }}); /script /head body table width=500 col style=width: 50px; / col / col style=width: 60px; / col style=width: 110px; / tr th Qty /th th align=left Product /th th Price /th th Total /th /tr tr td align=center input type=text name=qty_item_1 id=qty_item_1 value=1 size=2 / /td td /td td align=center id=price_item_1 $39.99 /td Somewhere there must be a calc() function that takes an input element and gets its value, then any other type of element and gets its text content (or value perhaps), strips off the currency sign, multiplies the two and returns the result. Maybe it does some checking of the values it's been passed. Or not. It seems strange that a function called sum would not do rounding. How is invalid input handled? -- Rob
[jQuery] Re: 'this' keyword in a custom object
On Sep 22, 8:17 pm, Alex Wibowo alexwib...@gmail.com wrote: Hi... I'm trying to write object-oriented style javascript as follows: - function HtmlFormUtil(formId){ this.formId=formId; this.dirtyInputs=new Array();} HtmlFormUtil.prototype.trackForChanges=function(){ var dirtyInputs = this.dirtyInputs; $(:input,#+this.formId).change(function(){ this.dirtyInputs[this.dirtyInputs.length]=$(this); dirtyInputs[dirtyInputs.length] = $(this); and so on. Why you need to use $(this) is beyond me, just store a reference to the element. Get its value by direct access to the DOM property. });} HtmlFormUtil.prototype.isDirty=function(){ return this.dirtyInputs.length 0;} Seems you are using this array as nothing more than a glorified counter. Why not just increment a global counter, rather than creating a global object with circular references to every input element in the page? e.g. something like function addOne() { numChanged++; } var numChanged = 0; var inputs = document.getElementsByTagName('input'); var i = inputs.length; while (i--) { inputs[i].onchange = numChanged; } inputs = null; --- The intention is to use it to track any changes to the form fields... and warn user on window unload, if there's any dirty inputs (i.e form value has changed) It will be problematic. If the user re-sets the form, do you reset the dirtyInputs array? If the user changes the value back to the original, do you remove the input from the array? If they paste data into the input, will the change event fire before it navigates away? If there is only going to be one instance of this object in the page, why use a constructor? Just use a plain object and give it the methods you are putting on the prototype. Not as hip, funky or cool, but cleaner and less problematic. Unfortunately, the code above doesnt work... because in this.dirtyInputs[], the this keyword refers to the element that has the value changed (i.e. jquery object) No, the DOM element. , and not 'this instance of HtmlFormUtil'. You'll find it's not particularly useful anyway. Just compare each input's value to its defaultValue. If they're different, the user changed it. You don't even care *how* they changed it. Note however that an onunload listener will break fast history navigation in some browsers. Has anyone ever done this before? A thousand times. What is the best way to solve my problem above? Use something like: if (input.defaultValue != input.value) { // value has changed. } -- Rob
[jQuery] Re: 'this' keyword in a custom object
On Sep 22, 9:04 pm, RobG robg...@gmail.com wrote: [...] e.g. something like function addOne() { numChanged++; } var numChanged = 0; var inputs = document.getElementsByTagName('input'); var i = inputs.length; while (i--) { inputs[i].onchange = numChanged; Ooops: inputs[i].onchange = addOne; } inputs = null; -- Rob
[jQuery] Re: Browser sniffing - the correct way?
On Sep 22, 1:30 am, Mike McNally emmecin...@gmail.com wrote: Advice to never use browser detection is good advice, but in my experience it's simply impossible to follow. The bad behaviors of old IE browsers - behaviors that are, in effect, bugs, and therefore not features that obey any particular logic - are numerous and pervasive. Facile advice like avoid troublesome features constitutes a grim curse on site design: don't do anything that doesn't work reliably in IE6 is what that amounts to, and I think that's terrible. There are, and will always be, features that are available in some browsers but not others. An evaluation must be made whether a particular feature supported by certain browsers is worth having so badly that it is OK to offer a lesser experience, or even deny access, to users of other browsers. Are transparent PNG images *that* important? Is there *no* other option? Is javascript the only, or best, solution? A common fix for the PNG issue is to use conditional comments to sniff for IE and insert a different stylesheet that replaces the PNG images with others. That solution suits some (I guess it suits IE users at least), but if the replacement images are OK for IE users, they are probably fine for others too. And at the same time life has been made better for every browser that doesn't support transparent PNG images (there are likely a number of mobile browsers that don't support them either). There are always those who wish to push the boundaries of what can be done on the web, good for them. However, for everyday business web sites, simpler is better and flashiness just distracts from the job at hand. In a few years time, well look back at accordions, carousels, show/hide effects and such much the same way as we look at blink and marquee elements now. They are annoying distractions that rarely add to the functionality or usefulness of a site. For example, here's the home page of my ISP: URL: http://www.iinet.net.au/customers/ The primary purpose of this page is to allow their customers to login to the site. You'll note that the focus is automatically put in the login field. A username can be entered, tab pressed, then a password, but it is impossible to navigate to the toolbox button without using a mouse. Whoever designed it was clever enough to create those wonderful buttons (which always leave me wondering which is on and which is off) but was incapable of maintaining keyboard navigation supported natively by every desktop browser since Netscape 1.0. So you can see that I have a slight bias when functionality is restricted just because someone decided to poorly implement a pretty UI component. :-) Similarly, the second set of login links at the top are impossible to use without a pointing device - they can't be selected with a tab key. The page is spectacularly bad at the one function it is supposed to perform. And they don't use transparent PNGs anywhere! ;-p The point here is not necessarily to build every site to the lowest common denominator, but to not deliberately do things that break functionality that has been available in just about every browser for a very long time. Javascript and CSS should enhance the user experience, not break it. -- Rob
[jQuery] Re: How do you make text selectable when using IE browser?
On Sep 19, 6:53 am, amtames matt.a...@tnmed.org wrote: Hi, We recently had our site redeveloped by a professional firm. We originally requested that users not be able to copy and paste text from our site. This has created an outcry and we would like to have text be selectable. I see that they achieved this by using jquery which I am not familiar. I believe that I have found the snippet of code that turns this ability off/on but I do not know how to write the correct code to allow selection of text. You don't have to do anything to *allow* selection of text, you just have to stop trying to prevent it. The simple solution is to turn off javascript, but likely your users don't know how to do that. This is an IE specific issue, not a problem in Firefox. Look for something like: document.onselectstart = function() {return false;} and remove it. -- Rob
[jQuery] Re: Browser sniffing - the correct way?
On Sep 18, 1:32 am, ldexterldesign m...@ldexterldesign.co.uk wrote: [...] This still leaves the issue of targeting browsers with JS/jQuery. You still seem to be missing the message: trying to compensate for browser quirks by detecting specific browsers is a flawed strategy. Browser detection is usually based on the user agent string, of which there are over 30,000 registered at TNL.net. A friend of mine just recommend:http://www.quirksmode.org/js/detect.html Don't use it. Don't even consider detecting specific browsers for javascript quirks. For HTML or CSS hacks, go to relevant forums. Often the best solution is to simply avoid troublesome features. -- Rob
[jQuery] Re: Get the onclick method of an element
On Sep 15, 6:09 pm, sirrocco xavier...@gmail.com wrote: Let's say you have a : a href=# onclick='DoSomething(this);'asd/a I want to get the onclick text in a variable - something like var onclick = $('a').attr('onclick'); The problem is that the onclick variable now is a function and if I try to execute , this wil be the document instead of the link . That is (in part) because the attr method returns a reference to the function object, i.e. it returns the DOM property, not the HTML attribute. How can I get only the text, You could try the getAttribute method, but it's buggy in IE: var listenerCode = element.getAttribute('onclick'); so I can later reattach it to the link ? There are a couple of methods, buy you need to change how your function works and understand the difference between an HTML attribute and a DOM element property. The text supplied in the onclick attribute is converted to a function and is called by the onclick handler when a click event occurs. When attached inline, the handler sets the function's this keyword to a reference to the element that the handler belongs to. When attached as a property of a DOM element, browsers like Firefox continue to set this to the element, but browsers like IE don't so this resolves to the global object (per the ECMAScript specification). One way to fix the issue is to use the event object rather than the this keyword so the function can be assigned to other elements simply by assigning it to the appropriate DOM property, e.g. script type=text/javascript window.onload = function() { var el0 = document.getElementById('a0'); var el1 = document.getElementById('a1'); el1.onclick = el0.onclick; } function foo(evt) { var evt = evt || window.event; if (!evt) return; var el = evt.target || evt.srcElement; alert('id: ' + el.id); } /script a id=a0 href=# onclick=foo(event);a0/a a id=a1 href=# a1/a Another method is to use event delegation and listen for the event higher up the DOM tree so you don't need to assign the listener to new elements. -- Rob
[jQuery] Re: HTML code inside script tag, how access to it with DOM???
On Sep 10, 9:49 am, Mr Speaker mrspea...@gmail.com wrote: I think it's perfectly valid to have a div inside a script tag (or at It is never valid markup in an HTML document, a div element can't be a child of a script element. least useful), if a div makes sense to the TYPE you defined for the script. If you want to discuss HTML markup, then an HTML group would be a much better place to do that: URL: http://groups.google.com/group/comp.infosystems.www.authoring.html/browse_frm/thread/73b5d54124d8c0dc# The content of a script element is not considered markup, it is script. For example, John Resig uses a script tag with type text/ html in his micro-templating solution:http://ejohn.org/blog/javascript-micro-templating/ I think that is a very bad idea for a web page. What advantage does that approach have to assigning the string to a variable and using a script language that the browser understands? He demonstrates that a script element can contain random text, and sets a trap for any browser that dares to be standards compliant and end the script element at the first occurrence of /. In this instance though (and in reply to the original author) you add an ID to the SCRIPT tag, While browsers tolerate that, it is invalid markup. -- Rob
[jQuery] Re: remove() and empy() not work for xml
On Sep 7, 3:42 pm, g...@iec abhi.pur...@gmail.com wrote: Hi.can anybody help me out to come out of this You many need to use getElementsByTagNameNS('*',tagName). To remove nodes try: this.parentNode.removeChild(this); -- Rob
[jQuery] Re: How can I get current Index?
On Sep 6, 12:28 pm, din dingl...@gmail.com wrote: TR TD1/TD TDJM-53/TD TD--/TD TD--/TD TD--/TD TDA href=#ROHs/A/TD/TR TR TD2/TD TDJM-54/TD TDA href=#ROHs/A/TD TD--/TD TD--/TD TDA href=#ROHs/A/TD/TR I want the value of href in first tag A is equal to JM-53_5.htm. And the the value of href in 2nd tag A is equal to JM-54_2.htm. The value of href in 3rd tag A is equal to JM-54_5.htm. HOW can I get the current Index of the tag A,and HOW TO get the value of the current 2nd tag TD. It seems that what you want to do is use the text from the 2nd cell and the cell index of the cell that the a element is in to create an href value for the link. Your server knows all this information before the page is sent, why don't you do it there? Getting client-side scripting to do this stuff just creates a dependancy where none is required. Making this stuff dependant on the layout creates maintenance headaches - every time the layout changes, your script must change too. Something like the following will do the job, however it has no feature detection and will break if dependant parts of the layout change: var getText = (function() { var el = document.createElement('p'); if (typeof el.textContent == 'string') { return function(el) { return el.textContent; } } else if (typeof el.innerText == 'string') { return function(el) { return el.innerText; } } })(); function trim(s) { return s.replace(/(^\s*)|(\s*$)/g,''); } function fixLinks(id) { var text, a, aLinks, j; var row, rows = document.getElementById(id).rows; var i = rows.length; while (i--) { row = rows[i]; aLinks = row.getElementsByTagName('a'); j = aLinks.length; text = trim(getText(row.cells[1])); while (j--) { a = aLinks[j]; aLinks[j].href = text + '_' + a.parentNode.cellIndex + '.htm'; } } } -- Rob
[jQuery] Re: jQuery.support : Test if browser return nodes of type Text_Node
On Sep 6, 1:38 am, jeanph01 jeanp...@gmail.com wrote: Using jQuery.support and without using jQuery.browser how would I know if the browser would return nodes of Type of Text_Node ? I don't think you need to know that at all - why do you think you need to? IE do not return text nodes. My only idea would be to create on the fly some structure in memory with text nodes and test with $(this).contents() if there is text nodes returned. Deal with empty text nodes explicitly, don't use browser detection or other detection kludges. -- Rob
[jQuery] Re: Strange behaviour when de-activating form
On Sep 3, 3:32 am, burlistic burlis...@yahoo.co.uk wrote: Hi All, Not sure this is the best place for this question, but I hope someone can help. I have a form which requires a lot of client side validation. As this takes a while I am using an overlay to stop access to the form. That is probably pointless. The problem is, the overlay only appears after all valition code has exectured. Thus rendering it useless. Standard stuff really... Large div with a class that has display: none; Form submit (onsubmit=validate(); return false;) calls the The usual way would be to use something like: form onsubmit=return validate(this); ... validation code, which also submits the form if there are no errors. See code below; function validate() { $('#messageOverlay span').text('Validating'); var messageOverlay = $('#messageOverlay'); $(messageOverlay).removeClass('hide'); //VALIDATION CODE GOES HERE } Strangly the overlay appears if I place an alert in the validation code?? Browsers usually don't update the document while scripts are running, they do it all at the end, which makes a lot of sense as they have no idea what the script will do to it. An alert provides a pause so the document is updated. I would really expect the overlay code to run first and dispaly the message. Why does it only happen after all the code has executed? See above. I've tried so many things.. Like attaching the overlay code to the button click and using bind() to attached the method calls seperatly. Any help greatly appreciated.. If you sovle my problem and live / work in London I will by you many beers! I don't live anywhere near London. You will have to do something like: cancel form submission, set the overlay, call validation using a short setTimeout, at the end of validation submit the form (or not) and remove the overlay. But you run the risk that if the overlay doesn't block access so the user can submit the form while validation is running or start a second process and submit it multiple times... you are adopting a brittle strategy. Just validate the form and return false if it fails. The script wil block the UI anyway. You have to validate on the server anyway, the only reason to validate on the client is to make life easier for users. Your approach may well make it more difficult. -- Rob.
[jQuery] Re: Is this quirk of jQuery still true?
On Sep 4, 11:28 am, p_W paulwoolcoc...@gmail.com wrote: I just wanted to address setAttribute real quick...correct me if I'm wrong, but I was under the impression that IE does not support setAttribute(), that you had to use dot notation for IE (so element.attribute = value instead of element.setAttribute(attribute, value)) setAttribute works in IE as far back as 6 at least, but has quirks (try using it to set an onclick listener). There is rarely any need to set HTML attributes when dealing with an HTML DOM, just set the appropriate property. setAttribute and getAttribute are useful for DOMs that are not HTML, or for non-standard attributes in an HTML DOM - though that makes the markup invalid and so shouldn't be used. Again, just use standard object property access methods (dots or square brackets). -- Rob
[jQuery] Re: Is this quirk of jQuery still true?
On Sep 3, 6:55 am, Rick Faircloth r...@whitestonemedia.com wrote: I read that in an article dated October 17, 2008, that it was not possible to change the actual HTML in the DOM There is no HTML in the DOM. HTML is used to create a DOM. of the value attribute of a text input using $(this).val('myNewValue'); Because that changes the DOM value property, not the HTML value attribute. The HTML value attribute (if present) is used to set the DOM defaultValue property and provide an initial value for the value property. User initiated changes to the input's value will change the DOM value property. Setting the value property will change the displayed value. If the input is in a form and the form is submitted, the value of the value property is submitted (assuming the input is successful). The defaultValue is used to set the value of the input if the form's reset method is called and can be changed by assigning a new value to it programmatically. The HTML attribute value can be changed using setAttribute. There is no specification for how to generate HTML from a DOM, what you'll get is dependent on the browser and the method or tool (e.g. the browser-dependent innerHTML property[1]) Using innerHTML as the tool to convert DOM to HTML, it can be seen that in IE changes to the element's value property are reflected in the value attribute but not in Firefox. Other tools may have different results. If you want consistent behaviour in that regard, do the DOM to HTML transformation yourself. My experiments just now bear this out. Is this still true? The writer of the article developed a work-around using a hidden input and manipulating its value with a rel to the original input. Is this still the best way? If you want to reliably set the HTML attribute value, use setAttribute as it is specified as doing that (and realise that setAttribute is broken in IE in places). 1. innerHTML is a widely copied IE proprietary property that has no public specification and is known to be implemented differently in different browsers. -- Rob
[jQuery] Re: validation: how do I make sure a radio button is picked?
On Sep 3, 6:17 am, Matt Wilson m...@tplus1.com wrote: I have a list of radio buttons, all with the same name, and each has a different value. I want a validator that tests if one is picked. How do I do this? Set one as checked by default (as suggested by the W3C HTML specification), no script or validation needed. -- Rob
[jQuery] Re: Is this quirk of jQuery still true?
On Sep 3, 1:25 pm, Rick Faircloth r...@whitestonemedia.com wrote: Thanks for the explanation, Rob. I'll have to check into setAttribute...am I correct in assuming that setAttribute is a Javascript function, but not jQuery? setAttribute is a DOM Core method of the Element interface[1]. jQuery wraps a great many such methods, but not this one. There is rarely any need to use it for HTML documents, particularly as it is broken in parts in IE. There is also little use for it as setting the DOM property directly is simpler (and likely much faster as it doesn't require a method call). setAttribute may handy for XML documents though. Also, your statement, There is no 'HTML in the DOM'. HTML is used to create a DOM. seems like semantics. Yes, it is, but in a technical group I think it is important. It is impossible to know the OP was just a bit lazy or doesn't fully understand the concepts. Better to be sure than make a wrong assumption. So is it correct to say that a DOM contains no HTML? Yes. HTML is a markup language, it is interpreted by browsers to generate a DOM. Javascript interacts with the DOM, not the markup. An analogy is that a plan is used to build a house. Instructions to tradesmen to change the design might be reflected in the house, but aren't automatically reflected in the plans unless you also tell the draughtsman to change them. innerHTML and other DOM inspection tools are like an as built plan of part of the house. 1. URL: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-F68F082 -- Rob
[jQuery] Re: .html() ignoring updated input value
On Aug 19, 3:29 am, resetstudio navy...@gmail.com wrote: Hi everybody, how are you? I have to save the state of a form in a var before submitting it with the whole html, but if I alert the var, I get the original html without the updated input fields. Example: I have div input type='text' name='test'/ /div and I fill that field with hahahah, on $(div).html() i get input type='text' name='test'/ and not input type='text' name='test' value='hahahah'/. Likely that varies by browser. Can someone help me? jQuery's html method essentially just returns the value of the innerHTML property of an element. innerHTML is a proprietary IE property that has been widely copied by other browsers. It has not been standardised, nor does it have a published specification, therefore its value is implementation dependant. You should not rely on innerHTML (or the html method) returning the same property across browsers where the content is anything other than trivial. Form controls (or elements that can be form controls) are particularly problematic. -- Rob
[jQuery] Re: How to access the member of $.each() when Key has space?
On Aug 12, 2:23 pm, Ming mcpm...@gmail.com wrote: [...] For example: $.each(eval(response),function(key, item) { alert(item.Account); //Work alert(item.Amount); //Work alert(item.Reference Date); //Fail }); I have try alert(item('Reference Date')); alert(item['Reference Date']); alert(item[0]); //Assume it is on index 0 all of them are not work. URL: http://www.jibbering.com/faq/faq_notes/square_brackets.html -- Rob
[jQuery] can't return value after $.ajax call
Hi i'm currently using the dialog functionality (modal form) from UI library to submit data to the database. All the validation checks have been running ok until one of the validation checks requires a ajax call to check if a username exsist in the database. I'm fairly new to both javascript and jquery so this could be a fairly basic blunder. Initially, i thought it was an sycronicity problem, but I changed the $.ajax async option to true but still no joy, so maybe it something to do with scope etc? Here's the code and thanks for any help in advance. function checkIfUsername() { $.ajax({ type: POST, url: +CI_ROOT+index.php/admin/check_if_username, data: ({username: username.val()}), async: false, dataType: json, success: function(data){ returnUsernameBool(username, data); } }); } function returnUsernameBool(o, data) { if(data.bool == true){ o.addClass('ui-state-error'); updateTips(Your username must be unique); alert('false'); //this works return false; //still can't return bool } else{ alert('true'); //this works return true; //still can't return bool } } bValid = bValid checkIfUsername(username); alert(bValid); //still gives undefined
[jQuery] Re: can't return value after $.ajax call
Hi Steven, Thank you for your reply but i'm not sure i understand what you mean? By having async set to false the script does wait for the value to come back from the server before executing the rest of the script (i can tell it does this because all the alerts i run to test it, run in the order i would expect). The return function is set in the success option of the $.ajax method which calls the returnUsernameBool function. Initially(see below), i had just one function but tried breaking it in two to see if that would give me some clue as to why it wasn't working function checkIfUsername(o) { $.ajax({ type: POST, url: +CI_ROOT+index.php/admin/check_if_username, data: ({username: username.val()}), async: false, dataType: json, success: function(data){ if(data.bool == true){ o.addClass('ui-state-error'); updateTips(Your username must be unique); return false; } else{ return true; } } }); } //check id username already exsists bValid = bValid checkIfUsername(username); On Aug 10, 11:25 am, Steven Yang kenshin...@gmail.com wrote: aside from the fact that checkIfUsername does not have a return ajax function is not going to waitwhen you finished calling $.ajax your function has already ended(returned) then when server responded your returnUsernameBool will be called but thats already too late for your alert(bValid) thinking as $.ajax is creating another thread and your callback is run in it might help (eventhough javascript is single threaded)
[jQuery] Re: can't return value after $.ajax call
Thank you, that has worked. I tried exactly the same thing before because i though that returning the boolean from within the $.ajax method might not work. However instead of using bool = true; i was using var bool = true;. Have you any idea why using the prefix of var would stop this working? On Aug 10, 11:52 am, Steven Yang kenshin...@gmail.com wrote: if thats the case try function checkIfUsername(o) { var bool; $.ajax({ type: POST, url: +CI_ROOT+index.php/admin/check_if_username, data: ({username: username.val()}), async: false, dataType: json, success: function(data){ if(data.bool == true){ o.addClass('ui-state-error'); updateTips(Your username must be unique); //return false; bool = false; } else{ //return true; bool = true; } } }); return bool; } i am not very familiar with the case that async:false but from what you described, this should work
[jQuery] Re: jQuery and the 'this' keyword
On Jul 31, 5:44 am, #micah micah.a.sm...@gmail.com wrote: I've created a javascript object like so: var myObj={ // internally used OtherFunction: function(){ alert('hi');}, // externally used EditInfo: function(){ this.OtherFunction(); } }; if i bind EditInfo to a button, like so: There is no such thing as bind in javascript. You are assigning the function to a listener. $('#myButton').click(myObj.EditInfo) Then (this) is pointing to the button, not to myObj. Why is that? The value of a function's this keyword is set *when the function is called*, not when you define the function. The handler that calls EditInfo sets its this keyword to the button. Note that the handler is passed a reference directly to the function, it doesn't call it as myObj.EditInfo(). Perhaps you need: ...click(function(){myObj.EditInfo();}) Now EditInfo is called as a method of myObj and its this keyword will be set as you expect. Incidentally, it is a convention that only functions intended to be called as conststructors start with a capital letter. If that was the case here, its this keyword would be a reference to the new object and your issue goes away. I'm using FF3.5 Not relevant to this issue, though there are differences in how the this keyword is set for listeners between IE and other browsers. -- Rob
[jQuery] Re: How to deterine number of words in a string?
On Jul 28, 5:09 am, Liam Byrne l...@onsight.ie wrote: A letter count is FAR easier - just get the string's length. The length of the string will give you a *character* count. I would not inlcude punctuation, white space, etc. in a *letter* count. For number of letters, try: s.replace(/[^a-zA-Z]/g,'').length; -- Rob
[jQuery] Re: newbie question.
On Jul 28, 5:53 am, James james.gp@gmail.com wrote: This: (function() { do some stuff } )(); is known as a closure. You have a warped view of a closure. It is an example of the module pattern, which can create closures, but doesn't necessarily do so. URL: http://www.jibbering.com/faq/faq_notes/closures.html It just runs once and it does not leave around any global variables (that is, if you also don't set any inside this function also). More or less. Compared to this: function doSomething() { // do some stuff }; The doSomething variable will exist (globally) to be available for access again. There are many ways to created global variables, declaring a function in the global scope is one. It will exist in memory, and may possibly pollute the global namespace. This is usually a problem if you have a lot of other Javascript that may have same variable name conflicts (e.g. multiple Javascript libraries). In the first example, no such global variable will exist. It will run once, and disappear. Maybe. There are other methods for avoiding name collisions. In your example: (function($) { do some stuff } )(jQuery); The $ variable (local) has the value of the jQuery (global) variable, therefore, inside your closure, you can use $ as your jQuery variable. There is no closure unless do some stuff creates one (which would require a function declaration or expression inside the anonymous function at least). It is the fact that $ is created as a local variable and assigned a reference to the jQuery function that protects it from collisions outside the function. -- Rob
[jQuery] Re: Looking for some help converting this to jquery
On Jul 24, 3:20 am, sleepwalker danielpaulr...@gmail.com wrote: Eric you rock that's what I'm talking about!! Beautiful code man thanks so much. Learning is fun. Don't confuse less with better, it is often slower to execute and harder to maintain. The code I posted could be written as: function setButtonClass() { var el, inputs = document.getElementsByTagName('input'); var i = inputs.length; while (i (el = inputs[--i])) { if (/button|reset|submit/.test(el.type)) { var word = el.value.split(/[a-z]/).length/2 + el.value.length; el.className = word11?'mb':word4?'sb':word0?'b':''; } } } but I would not do that. Would you trust the newest coder in the office to maintain it? Or accept the totally unnecessary performance hit just to save a few lines? -- Rob
[jQuery] Re: Looking for some help converting this to jquery
On Jul 23, 6:42 am, sleepwalker danielpaulr...@gmail.com wrote: Hi, I have a old script that adds a class to a button/submit/reset based on the length of its value and I'd like to convert it to jquery. I'm just looking for any suggestions on the best way to rewrite it. Instead of code, can you provide a concise statement of what the code is expected to do? It may be different from what it actaully does. Thanks in advance for any help function setbuttonclass() { if(document.getElementById document.createTextNode) { var x = document.getElementsByTagName('input'); It doesn't seem sensible to infer the availability of a particular method by testing a random selection of other methods. To determine if getElementsByTagName is supported, test it directly. for (var i=0;ix.length;i++) { var s = x[i].value; var nolower = s.split(/[^A-Z\W]/); If the intention is to split on lower case characters, why not: var nolower = s.split(/[a-z]/) var word = (nolower.length/2 + s.length); Surely there is a simpler way to determine the class that is to be applied to buttons? if (((x[i].type == ('button'||'reset'))||(x[i].type == 'reset')||(x The expression - ('button'||'reset') - will always return the value button. When posting code, manually wrap it at about 70 characters so that auto-wrapping doesn't introduce more errors. [i].type == 'submit')) ((word) = 12)){ The test to see if the input is of type button, submit or reset can be done once, then the other logic applied. Getting x[i] every time in every expression is very inefficient: store a reference and re-use it. x[i].className = 'mb'; } else if (((x[i].type == 'button')||(x[i].type == 'reset') ||(x [i].type == 'submit')) ((word) = 4) (word != 0)){ x[i].className = 'b'; } else { if (((x[i].type == 'button')||(x[i].type == 'reset') ||(x [i].type == 'submit')) (word != 0)){ x[i].className = 'sb'; Those tests seem out of sequence, and all the brackets make it very hard to read. The code can be greatly simplified (see below). } } } } } Consider: function setButtonClass() { if (document document.getElementsByTagName) { var inputs = document.getElementsByTagName('input'); var reType = /button|reset|submit/; var reSplit = /[a-z]/; var i = inputs.length; var el, nolower, s, word; while(i--) { el = inputs[i]; // Calculate word s = el.value; nolower = s.split(reSplit); word = (nolower.length/2 + s.length); // If input is of type button, reset or submit if (reType.test(el.type)) { // If word is 12 or greater, assign mb if (word 11) { el.className = 'mb'; // Else if word is less than 12 but greater than 4 // assign sb } else if (word 4 word 12) { el.className = 'sb'; // Else if word is greater than zero (but less than 5) // assign b } else if (word 0) { // el.className = 'b'; } // If word less than 1, no className is assigned } } } } -- Rob
[jQuery] Re: My new website AllJobsXChange.com developed with Jquery
On Jul 18, 9:40 am, son sco0...@yahoo.com wrote: Thank you Rob. I can't remember what make me use the XHTML doctype, I thought I had some problem with running some jquery stuff, but not sure. what is the ideal doctype the will work well with JQuery? jQuery is irrelevant, the best (and only) DOCTYPE to use on the web is HTML 4.01 strict. You may use others for specific purposes, but they are not suitable for a general web site. The vast majority if web sites using an XHTML DOCTYPE are served as HTML because about 70% of web users are using IE, which does not understand XHTML. URL: http://hixie.ch/advocacy/xhtml -- Rob
[jQuery] Re: My new website AllJobsXChange.com developed with Jquery
On Jul 17, 11:19 am, son sco0...@yahoo.com wrote: Hi. My website,www.alljobsxchange.comwas developed with the use of JQuery. Yet another site using an XHTML doctype served as text/html, even to browsers that understand XML. The W3C validator found 62 errors: URL: http://validator.w3.org/check?uri=http%3A%2F%2Fwww.alljobsxchange.com%2Fcharset=%28detect+automatically%29doctype=Inlinegroup=0 Not good for a site with a few lines of text and a single input element. Why is javascript and browser sniffing used at all? -- Rob .
[jQuery] Re: How to add an element to an object?
On Jul 15, 3:25 am, yasmine yasmina.ez...@gmail.com wrote: Thanks, I didn't know about the javascript associative arrays. Because javascript doesn't have them, it has objects that are simple name/value pairs. -- Rob
[jQuery] Re: Determine content type in $.post callback
On Jul 13, 9:29 am, dnagir dna...@gmail.com wrote: Anybody? How can I check the ContentType header in the $.post callback? Try the W3C XMLHttpRequest Object specification: URL: http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/#dfn-getresponseheader -- Rob
[jQuery] Re: function scope
On Jul 7, 11:04 am, Josh Nathanson joshnathan...@gmail.com wrote: You can't. Of course you can. You'll have to create a global variable outside document.ready: var myFuncs = {}; Or just: var foo; or from within the ready function: var global = (function(){return this;})(); global.foo = function(){...}; $(document).ready(function() { myFuncs.foo = function() { Then myFuncs.foo won't be available until the ready function is called. If foo is declared outside the function, assign the value at the same time. -- Rob
[jQuery] Re: how to change 2,5 to 2,50 ?
On Jul 7, 8:11 pm, weidc mueller.juli...@googlemail.com wrote: hi, thats my code: endpreis =Math.round(endpreis*100)/100; to round the price of something but i'd like to have 2,00 or 2,50 instead of 2 and 2,5. i'd be happy about any help. To format a number in javascript with exactly two decimal places it is a good idea to try a resource dedicated to javascript: URL: http://www.jibbering.com/faq/#formatNumber -- Rob
[jQuery] Re: how to change 2,5 to 2,50 ?
On Jul 8, 1:59 am, mkmanning michaell...@gmail.com wrote: There are also some currency formatting plugins: http://plugins.jquery.com/project/currencyFormat That appears to make extensive use of toFixed(), which is known to be buggy in some browsers for certain values. Try: alert( (0.0625).toFixed(1) ); Firefox shows 0.1 (correct) IE 6 shows 0.0 (wrong). URL: http://www.merlyn.demon.co.uk/js-rndg1.htm -- Rob
[jQuery] Re: how to change 2,5 to 2,50 ?
On Jul 7, 9:14 pm, Massimo Lombardo unwiredbr...@gmail.com wrote: [...] As I see you're dealing with cents, money and stuff, I have to remember you that JavaScript use IEEE 754 Floating Points as its own internal number type, so 0.1 + 0.2 !== 0.3: people tend to be very picky when dealing with money, especially if it's *their* money! :) So: be careful. And if you're relying on JavaScript logic to handle people's money, change programming language, JavaScript is not good at it. The language is not the issue as such, any language using IEEE-754 numbers will have exactly the same problem - certain decimal values can't be represented exactly. The solution is to understand the issue and deal with it, not live in fear. URL: http://www.jibbering.com/faq/#binaryNumbers -- Rob
[jQuery] Re: Object as Function argument
On Jun 24, 4:07 pm, Nic Hubbard nnhubb...@gmail.com wrote: I have used an object in the past as a function argument, but this was for a plugin that I wrote. Using it in the architecture of a plugin it worked. BUT, this time, I just want to write a normal function, but still use an object to set defaults and pass in changes to those defaults through as a param. Is this possible, or do I have to make this a jQuery function like $.myfunction() ? I am trying: function test(defaults) Including an identifier name in the formal parameter list is equivalent to declaring that parameter in the body of the function. { var defaults = { Here you declare the variable again - there is no need for that. test: '' }; and assign it a value. Whatever was passed to the function as the value of defaults has now been replaced by this assignment. alert(defaults.test); } test({test: 'It works!'}); The above does not seem to work, Where work has some special meaning for you. It does exactly what it is coded to do: the object you pass to the function is replaced by the internal assignment before the alert is called, so you see the internally assigned value, not the one you pass. and replace the default with that was passed in the function. What am I doing wrong here? function test(defaults) { if (typeof defaults == 'undefined') { // no useful parameters were passed to the function, // assign a default value to defaults defaults = {test: 'default value'}; } alert(defaults.test); } -- Rob
[jQuery] Re: return value of nested functions is always undefined
On Jun 23, 4:31 pm, anawak82 anawa...@googlemail.com wrote: Hi Rob, thank you for your quick reply! Add a return statement to getPrice, maybe something like: function getPrice(id) { return $.get('db.xml', function(d){ ... }); I am sorry to say that this only return a XMLHttpRequest but not the value of the variable price. Your original function appears to be extremely inefficient, but anyhow, without knowing the structure of the XML document you are dealing with, use: function getPrice(id) { var price; ... price = $data.find(preis).text().trim(); ... return price; } Note that price is declared in the outer function and not in the inner function. -- Rob
[jQuery] Re: return value of nested functions is always undefined
On Jun 23, 6:24 am, anawak82 anawa...@googlemail.com wrote: Hi, I am just trying to learn a little bit about jQuery. Now I have a problem with returning a value from a function. The following code works fine, when I tested it with alert(price) or any other way of echoing the value directly. But if I try something like var test = getPrice(324), the variable test would always be undefined. function getPrice(id) { $.get('db.xml', function(d){ $(d).find('data').each(function(){ var $data = $(this); if ($data.find(id).text() == id) { var price = $data.find(preis).text().trim(); return price; } }); }); }; A semi-colon after a function declaration is an empty statement. The getPrice function doesn't have a return statement, so its return value will always be undefined (provided it executes without error). I assume that the nested functions are part of the problem, but I don't know how to solve it. Add a return statement to getPrice, maybe something like: function getPrice(id) { return $.get('db.xml', function(d){ ... }); } -- Rob
[jQuery] Re: selector, second to last row of table
On Jun 17, 3:46 am, theprodigy tigerseyet...@gmail.com wrote: I've been trying for a while to alter the second to last row of a table. I've tried several ways. The number of rows is dynamic so I can't hard code a number into nth-child. I used $rowNeeded = $thisRow.parents('table:first').children().children().length - 1 to get the second to last row, but it doesn't seem like I can pass this variable into nth-child either. How can I select the second to last row of a table? In browsers compliant with the W3C DOM 2 HTML specification, table elements have a rows collection that contains all the rows in the table. That collection has a length attribute, so, where - table - is a reference to a table element: var rows = table.rows; var secondLastRow = rows[rows.length - 2]; Since rows is a live collection, you can get a reference once and keep it, it will dynamically updated regardless of how many rows are added or removed from the table. Note that the above will error if there are less than two rows in the table, use with care. -- Rob
[jQuery] Re: Loop only handling last item in the array
On Jun 10, 7:44 am, psc petercar...@gmail.com wrote: I am very new to javascript/jquery so bare with me. I am using this loop code below with a populated array called listarray: for(var i in listarray){ Don't use for..in to iterate over an Array, it can be problematic unless you have complete control over the environment. Use a normal for, while or do loop. var currententry = listarray[i]; var finalurl=phpscript.php?entry=+currententry; jQuery.ajax({ url: finalurl, Here, the value of finalurl has a closure to the outer finalurl... success: function(serverreply){ alert(currententry); } }); Your AJAX request likely runs asynchronously, so the loop has finished before the first request is sent. At that point, finalurl has the last value it was assigned for all the waiting xmlHTTPRequests. You can either make the calls synchronous (probably a bad idea) or break the closure. } The alerts will always be the exact same: the last item in the array. So if there are 10 items in the array, it will alert the last one... 10 times. I'm trying to work with each entry, but I think my code might be mixed up. Classic symptoms of an unexpected closure. The script is a very dumbed down version of what I'm working on, but it's where I'm having my problem. I need to be able to see the ajax reply, and depending upon what that reply is, do something with the current array entry. If I alert() the serverreply instead... that works fine and gives different responses each time... but when I alert () the currententry it's the last item in the array every time. Likely the alert pauses the loop long enough for the request to be sent with the current value of finalurl. Read about closures (the following article is long and detailed, but stick with it as you'll learn a lot about ECMAScript in the meantime): URL: http://www.jibbering.com/faq/faq_notes/closures.html -- Rob
[jQuery] Re: How to get option's position
On Jun 9, 11:23 am, David .Wu chan1...@gmail.com wrote: if I have a menu, how to get the position of the option after I select one of it? for example, if I choose b, and the position should b 2. select optiona/option optionb/option optionc/option /select Select elements have a (zero indexed) selectedIndex property that tells you which option is selected. If no option is selected, it has a value of -1. If b is selected above, the select's selectedIndex property will return 1. -- Rob
[jQuery] Re: Even Odd Rows
On Jun 6, 11:25 pm, Karl Swedberg k...@englishrules.com wrote: You can make that first line a bit more compact: $(li).removeClass(even odd) It's still very inefficient. All that is required is for the LIs below the deleted one to have their class swapped from odd to even and vice versa. -- Rob
[jQuery] Re: looping through all elements of a form and keeping track of different font size
On Jun 3, 6:48 pm, Mr J regis...@pharmeon.nl wrote: hi all, here is the scenario: i have created an option on a website to give the possibity to the user to change the font size (smaller, bigger, reset), A complete waste of time. Modern browsers allow the user to control the size of text using one or more of: 1. User-defined style sheets 2. Browser preferences for minimum and standard font sizes 3. Zoom text sizes using ctrl+ or ctrl- 4. Reset font sizes using ctrl-0 like the famous x3 'A' that we see in most of the websites. Not one web site that I frequently visit uses any such script. Even if it did, I wouldn't use it. Hardly famous or used by most web sites. the code i have is based on a plugin copywrite to (http://cool-javascripts.com). now i'm facing a problem with different font size for different elements. Forget it. Ditch the script, let users control font sizes using browser-native tools. [...] any suggestions or something that will put me in the right path will be very appreciated. See above. -- Rob
[jQuery] Re: calling functions between multiple document ready events
On May 31, 8:10 am, Ricardo ricardob...@gmail.com wrote: myFunction() and window.myFunction are not necessarily the same. the first one will look up the scope chain and use the first ocurrence, it doesn't go directly to the window object. The second looks up the scope chain too and uses the first property named window that it finds. It may not be the window you think it is. var x = 3; (function(){ var x = 5; alert(x);})(); alert(x); Again, this is basic javascript Basic ECMAScript. -- Rob
[jQuery] Re: Selecting lowest element containing text
On May 29, 5:32 am, David david.kar...@gmail.com wrote: I need to select the lowest element containing a given string. What does lowest mean? The one with the most ancestors, or the one whose ancestors have the largest index of their siblings? e.g. div id=d0 div div p id=p0 /div /div div p id=p1 /div /div Given the document tree blow d0, which is lower, p0 or p1? -- Rob
[jQuery] Re: input field name include . jquery cann't parse
On May 28, 4:07 am, Karl Swedberg k...@englishrules.com wrote: On May 26, 2009, at 9:05 PM, RobG wrote: The choice is clear - the OP can simply stop using jQuery selectors for those elements, or stop using jQuery (or any other CSS selector- based framework) at all. Really? That's the only choice? As others have already noted, you can simply escape the . Which infers simply hard coding all such IDs in the script, not a sustainable strategy in a non-trivial application where the ID is likely more efficiently passed as a parameter and therefore not a viable option IMO. The solution below doesn't require any hard coding and conforms to the first choice proposed above. http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_... Yes, we've seen that earlier in the thread. I commented on it. Given that it's an ID, the OP could use: $(document.getElementById('user.name'))... Which is likely faster anyway. True, but the speed difference is likely negligible. The comment about speed is primarily to indicate that it won't be slower, so the option of quoting the period character has nothing to recommend it. The OP is, of course, free to chose whatever option suits. The jQuery documentation does, after all, refer to them as weird and special characters. If you think there is more appropriate terminology, feel free to change it. The documentation site is a wiki. I'd rather let it stand. It reflects the attitude of the author and seems to have the support of at two posters here. -- Rob
[jQuery] Re: inline script html vs xhtml
On May 27, 10:31 pm, dhoover dh.ferm...@gmail.com wrote: I am a bit perplexed at why a simple bit of code I have is firing in HTML but not in the equivalent XHTML. Because it is extremely likely that your XHTML markup is being treated as HTML, in which case... [...] And here is the XHTML file (that does not work as expected): !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1- strict.dtd html xmlns=http://www.w3.org/1999/xhtml; xml:lang=en lang=en head titleText Demo/title meta http-equiv=Content-type content=text/html;charset=UTF-8 / link rel=stylesheet type=text/css href=stylesheets/default.css / script type=text/javascript src=js/jquery-1.3.2.min.js / is invalid markup. If you are loading the file locally, some browsers will use the DOCTYPE or file extension to determine if the markup as XHTML. However, the vast majority of web servers are configured to serve text/html as the content type in the response header. That overrides the DOCTYPE. -- Rob
[jQuery] Re: input field name include . jquery cann't parse
On May 27, 6:21 am, MorningZ morni...@gmail.com wrote: So if you had: input type=text id=user.name / how would you apply a style to that? Using a class or a selector other than the id. can't say: #user.name { } because that would look for input type=text id=user class=name / yeah, poor choice sure is relative, but why make things more difficult, when a simple dash or underscore would do the same thing (and not cause issues with basic CSS or jQuery) The choice is clear - the OP can simply stop using jQuery selectors for those elements, or stop using jQuery (or any other CSS selector- based framework) at all. Given that it's an ID, the OP could use: $(document.getElementById('user.name'))... Which is likely faster anyway. There is conflict between what is allowed as a value of the ID attribute and what CSS can use to select elements by ID. It remains an issue for anyone wishing to select elements using CSS selectors, regardless of the context. It is also an issue with the W3C Selectors API, a specification to which John Resig (and many others) contributed, yet there is nothing within that specification to address the issue raised in this thread. Clearly they don't think it's worth addressing. The jQuery documentation does, after all, refer to them as weird and special characters. -- Rob
[jQuery] Re: Read Pro JavaScript Techniques?
On May 25, 4:13 pm, Ricardo ricardob...@gmail.com wrote: On May 24, 2:01 am, RobG rg...@iinet.net.au wrote: Still good / applicable? It is not on the recommended list at the comp.lang.javascript FAQ: URL:http://www.jibbering.com/faq/#books The guys at comp.lang.javascript have a very strong bias against J. Resig, jQuery and other JS frameworks, that's not surprising :) Opinions on the book have been expressed in various posts, as have opinions of jQuery and other frameworks. They are on the public record for those who care to read them or respond, John Resig has to some of them. If specific criticisms or opinions on the book are wanted, ask at clj. -- Rob
[jQuery] Re: Read Pro JavaScript Techniques?
On May 23, 1:12 am, finneycanhelp lovefin...@gmail.com wrote: Have you read the book Pro JavaScript Techniques Published December 2006? No. Still good / applicable? It is not on the recommended list at the comp.lang.javascript FAQ: URL: http://www.jibbering.com/faq/#books (book image and links athttp://jspro.org/) Do you know of an active and better email list (or discussion group) for such general JavaScript questions? news:comp.lang.javascript URL: http://groups.google.com/group/comp.lang.javascript/topics?gvc=2 -- Rob
[jQuery] Re: Rollover Effects instead of alternate images
On May 22, 2:43 pm, dnagir dna...@gmail.com wrote: Hi, Just wondering if there's some effect in JQ that we can use to simulate rollover. It doesn't require any javascript at all. Usually when user hovers a mouse over a link/image it changes its src/ background to another one (for example arrow.png - arrow_o.png). Modern rollovers use a single image, not multiple images (you can use a single image for all rollovers if you want). So users feels like it is highlighted or similar. But we always must have 2 images (similar ones). No, you don't. Maybe there's some effect that can simulate this highligting/hover for user so we don't need to have 2 images. Google CSS rollovers - no script required. I understand it will never be as good as alternative image, but still. Good is subjective, but most believe that CSS rollovers are significantly better than script-driven rollovers. -- Rob
[jQuery] Re: What happen with jQuery? Is it slow?
On May 23, 6:48 am, Josh Powell seas...@gmail.com wrote: [...] Also, many of the jQuery examples are poorly constructed, Depending on your point of view. take the 'table' instance: for (var i = 0; i 40; i++) { $(table class='madetable'/table).appendTo(body).html (trtdfirst/td/tr).find(tr).prepend(tdbefore/td);} return $(tr td).length; This should be: var theTables = ''; for (var i = 0; i 40; i++) { theTables += 'table class=madetabletrtdbefore/ tdtdfirst/td/tr/table';} $(body).append(theTables); return $('tr td').length; and there are even quicker methods using array.join can speed it up for example The point of the tests is to test the speed *of the library*, not to write optimised code for a particular task. Adding 40 tables one at a time does that, adding them all in one go doesn't, it's effectively the same as adding one table. -- Rob
[jQuery] Re: traverse complete DOM of a webpage
On May 20, 8:35 pm, Sourabh sourabhmkulka...@gmail.com wrote: Hi I am new to jQuery.I have a problem where I want to traverse through DOM.For example a complete webpage.Is there any jQuery way to traverse complete DOM of the current page where the jQuery script resides ? Traversing the DOM is trivial, using recursion it requires perhaps 4 lines of plain javascript. What do you actually want to do? !DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01//EN http://www.w3.org/TR/html4/strict.dtd; titledomWalk/title script type=text/javascript function domWalk(node) { node = node || document.getElementsByTagName('html')[0]; // do something with node console.log(node.nodeName + ':' + node.nodeType); if (node.childNodes) { for (var i=0, len=node.childNodes.length; ilen; i++) { domWalk(node.childNodes[i]); } } } window.onload = function(){domWalk()}; /script divp/div -- Rob
[jQuery] Re: A better way of writing this code?
On May 15, 5:22 pm, Karthikraj karthik271...@gmail.com wrote: But CSS :hover will not work in IE6. So better use script Rubbish. The OP wants to use it on an A element, which supports :hover in probably every browser since Navigator and IE 4, if not older. -- Rob
[jQuery] Re: A better way of writing this code?
On May 15, 11:35 am, Calvin cstephe...@gmail.com wrote: Hi, I was able to get this script to work and was wondering if there was a better/proper/more efficient way of writing it. Here is the script: $(document).ready(function() { $('li.a').hover(function() { $(this).addClass('move'); }); $('li.a').mouseLeave(function() { $(this).removeClass('move'); )}; )}; Use the CSS a:hover pseudo-class and set your style rules there, no script required. li a:hover { /* insert rules */ } URL: http://www.w3.org/TR/CSS2/selector.html#x32 -- Rob
[jQuery] Re: jQuery too slow on IE!!!
On May 12, 10:42 pm, Chandan learningbychan...@gmail.com wrote: Hi, I recently started using jQuery, thinking that it is FASTER than usual javascript, but i found it is too slow when used with IE. I am using IE 6/7. jQuery is written in javascript, therefore it is unlikely that any jQuery function is faster than an equivalent plain old javascript (POJS) function. Some code snippets using jQuery are very much slower than their POJS equivalent, though the jQuery code itself might require fewer characters to type. It trades off saving a few minutes of writing code for a lifetime of slower performance (where lifetime is the life of the code). -- Rob
[jQuery] Re: val ( ) prefers labels over values?
On May 8, 10:52 am, Marv mcslay...@gmail.com wrote: You may be morally correct And technically correct. but the label attribute of the option tag is not widely supported: Irrelevant. -- Rob
[jQuery] Re: val ( ) prefers labels over values?
On May 7, 9:42 am, Michael B. Williams mbw...@gmail.com wrote: Consider the following select box: select id=test option value=/option option label=XS value=1XS/option option label=S value=2S/option option label=M value=3M/option option label=L value=4L/option option label=XL value=5XL/option option label=0 value=60/option option label=1 value=71/option option label=2 value=82/option option label=3 value=93/option option label=4 value=104/option option label=5 value=115/option option label=6 value=126/option option label=7 value=137/option option label=8 value=148/option option label=9 value=159/option option label=10 value=1610/option option label=11 value=1711/option option label=12 value=1812/option /select If I do a $(#test).val(2) on this I would hope it would select S, but instead it selects 2. Why is this setting the value of the select box based on the label rather than based on the value attribute? It isn't, it is selecting the option with text 2, which just happens to be the one with a label of 2. jQuery works backward through the set of options to find the first with either a text or value property equal to the supplied value and sets the first that it finds to selected. That's a pretty crappy algorithm, a sensible method would be to first check all options for a matching value, then for matching text, and check from the first option onward, not backwards. -- Rob
[jQuery] Re: val ( ) prefers labels over values?
On May 8, 12:20 pm, RobG rg...@iinet.net.au wrote: On May 7, 9:42 am, Michael B. Williams mbw...@gmail.com wrote: Consider the following select box: select id=test option value=/option option label=XS value=1XS/option option label=S value=2S/option option label=M value=3M/option option label=L value=4L/option option label=XL value=5XL/option option label=0 value=60/option option label=1 value=71/option option label=2 value=82/option option label=3 value=93/option option label=4 value=104/option option label=5 value=115/option option label=6 value=126/option option label=7 value=137/option option label=8 value=148/option option label=9 value=159/option option label=10 value=1610/option option label=11 value=1711/option option label=12 value=1812/option /select If I do a $(#test).val(2) on this I would hope it would select S, but instead it selects 2. Why is this setting the value of the select box based on the label rather than based on the value attribute? It isn't, it is selecting the option with text 2, which just happens to be the one with a label of 2. jQuery works backward through the set of options to find the first with either a text or value property equal to the supplied value and sets the first that it finds to selected. That isn't correct (dumb error reading makeArray), it goes through them in order, but leaves the last option with a matching value or text as selected. -- Rob
[jQuery] Re: Resetting the reset button
On May 1, 1:49 am, russellneufeld russellneuf...@gmail.com wrote: Hi all, I've got a set of forms which all act the same way - the form submit is handled by the jQuery form plugin which redirects the output to a div on the page. That means that when the user hits submit, the page in the browser doesn't change. The success or failure of the form submit is displayed on the existing page. The pages all have a submit and a reset button. The issue is that the reset button holds the state of the form when the page was originally sent to the browser. Only if you do that yourself, normally the reset button effectively does nothing more than call the reset method of the form. That means that after someone changes the form and submits it successfully, the reset button returns the form to the previous state when the page was originally sent to the browser. But that state doesn't really reflect the current state of the form variables (as held on the server) since an update has been made. Form controls have either a defaultValue, defaultChecked or defaultSelected property, depending on the type of element, that holds the default value of the control. When the form is reset, the control's value is reset to the relevant default. My question is this - is there a way to update the reset button so that it resets the form to a new state, one that might have changed since the browser originally rendered the page? Change the default[Value|Checked|Selected] property to whatever you want, then the reset button will reset to that value. URL: http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26091157 URL: http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-37770574 -- Rob
[jQuery] Re: Performance of parent child selector vs .children() method
On May 7, 11:54 am, Ricardo ricardob...@gmail.com wrote: On May 6, 10:23 am, Adam flynn...@gmail.com wrote: Essentially, I'd like to know if there is any difference between $(div.grandparent div.parent div.child) and $(div.grandparent).children(div.parent).children(div.child) Does anyone know which of these is more performant or preferred when selecting child nodes? Thanks. Best answer is a test: http://jquery.nodnod.net/cases/353 The overhead of multiple returns and function calls when using children () makes quite a difference. The overhead of such queries is even more significant if plain old javascript (POJS) is also considered. That test page shows the CSS selector takes half the time of children(), but a POJS vesion takes between 1/3 and 1/5 the time of the selector. If performance matters, POJS wins. -- Rob
[jQuery] Re: Disable input button, using wrong HTML code?
On May 7, 12:46 am, Jonathan Vanherpe (T T NV) jonat...@tnt.be wrote: Stephen Korecky wrote: I tried that too, has same results... On May 6, 9:35 am, Jonathan Vanherpe (T T NV) jonat...@tnt.be wrote: stephen wrote: I created a test page here:http://clients.stephenkorecky.com/stephen_korecky/js_test.html But basically the problem is that $(#button).attr(disabled,true); should disable a input button, and it does, HOWEVER it outputs disabled= when it should output disabled=disabled anyone know how to fix this? $(#button).attr(disabled,disabled); -- Jonathan Vanherpe - Tallieu Tallieu NV - jonat...@tnt.be If you're talking about what you see in Firebug: this just shows Gecko's internal DOM tree, which isn't necessarily the same as how the w3c would like it to be. If you change your html to be input disabled=disabled /, you'll see that firebug will drop the value too. Most browsers just ignore the value of disabled and just look at the existence of the attribute Probably because that is what the HTML specification tells them to do. :-) The OP has an XHTML doctype, but is serving the document as text/ html. The document is treated as HTML, any attempt to set a value for the disabled attribute is ignored as junk. The presence of the attribute is sufficient to disable the element. The document isn't valid XHTML anyway: URL: http://validator.w3.org/check?uri=http%3A%2F%2Fclients.stephenkorecky.com%2Fstephen_korecky%2Fjs_test.htmlcharset=(detect+automatically)doctype=Inlinegroup=0 (which you'll have to keep in mind when you use jquery to reenable the button, you'll need to remove the attribute, not just set it to false). the 'correct' way is disabled=disabled, though. Correct if that is being done in XHMLT markup, but not through DOM. If setAttribute could be relied upon, and you were in fact dealing with an XML document, the correct way would be: element.setAttribute('disabled', 'disabled'); However, setAttribute is broken in some browsers and therefore should be avoided in HTML documents. The simplest, cross-browser way is to set the DOM property to true or false. -- Rob
[jQuery] Re: Simple next/prev controls for select
On Apr 29, 6:56 am, René renefourn...@gmail.com wrote: Assuming: select id=selector option value=0 selected=selectedBoth/option option value=1Red/option option value=2Blue/option option value=3Green/option /select a id=prevPrev/a a id=nextNext/a Just wondering if someone has figured a simple jQuery function for moving through the a select list (using the above type of controls). The idea is that the Prev anchor would disappear if the first option is selected, and that the Next ancor would disappear if/when the last option is selected. Why hide the controls? If the last option is selected and the user clicks Next, make the first selected and vice versa: script type=text/javascript function prevNextOption(e) { var b = e? e.target : window.event.srcElement, sel = document.getElementById('sel0'), len = sel.length, n = (b.value == 'Next')? len + 1 : len - 1; sel.selectedIndex = (sel.selectedIndex + n) % len; } window.onload = function() { document.getElementById('inp0').onclick = prevNextOption; document.getElementById('inp1').onclick = prevNextOption; } /script select id=sel0 option selectedone optiontwo optionthree /select input type=button value=Previous id=inp0 input type=button value=Next id=inp1 -- Rob
[jQuery] Re: How to get file name
On Apr 28, 6:36 pm, David .Wu chan1...@gmail.com wrote: img src=images/xxx.gif $('img').attr('src') - This will get images/xxx.gif How to get xxx.gif by jQuery? img.src.replace(/.*\//, '')); -- Rob
[jQuery] Re: How to select one of the many forms i have
On Apr 25, 6:09 am, funkyasl amritas...@gmail.com wrote: Hi all, I'm a jquery newbie. I've been searching around the web a lot, but could not find an answer. My page has multiple forms (forma, formb, formc, etc). I want to select one particular form, say formb, without assigning an id to it, just by its name itself. How can i achieve this? I've tried: $(forms[name=formb]) but it doesnt work. You may be thinking of: var form = document.forms['formb']; where formb is the form's name. -- Rob
[jQuery] Re: Get first child within an element
On Apr 24, 9:43 pm, dgb dgbur...@gmail.com wrote: Hi, I've got a reference to a TableCell and I'd like to use jQuery to get the first instance of an IMG tag within that TableCell, but can't get the syntax right, I understand how it would work if I were to reference the TableCell by and ID or class, but not when I have a direct reference to the cell, I've got: var tdRef = xxx; $(tdRef).html(); ... could somebody let me know what the jQuery syntax should be to get the first img tag within tdRef? It is likely faster to use: var firstImage = tdRef.getElementsByTagName('img')[0]; -- Rob
[jQuery] Re: delaying an action
On Apr 21, 8:33 am, geocalleo gcalde...@gmail.com wrote: Hi all, I was wondering if there is a way in jQuery for me to disable a hover event for a few seconds and then execute it only if the mouse pointer is still hovering over the particular element I have set the hover event to. So the user would hover over a link and if after 2 seconds was still hovering over it, the hover event would then execute. Otherwise, nothing would happen. Put a listener on the mouseover event and use setTimeout to call the function. If there's a mouseout or a mouseover on some other related element before the event fires, cancel the timeout, otherwise let it run. You can also do the same for accidental mouseout events so the cursor can go off the edge for a short time before the mouseout fires. -- Rob
[jQuery] Re: Creating custom attributes in html
On Apr 17, 3:34 pm, RobG rg...@iinet.net.au wrote: [...] OK, here is a dead basic proof of concept. Of course it is nowhere near production code, but I think you can see where it's going. I would wrap the entire thing in the module pattern, but I've just used basic globals at this stage. My intention is to show that efficient DOM manipulation is possible and that access to related data isn't hard. It took me about 45 minutes to write the entire thing (more than half of that was writing the function to generate the test data set), tested in Firefox 3 and IE 6 on a 3.4GHz Pentium 4, Windows XP, the insert runs in less than 500ms. I'll test it on the G4 iBook for reference later. Safari 4 on iBook takes around 132ms, Firefox was around 1900. [...] function showData(evt) { var evt = evt || window.event; var tgt = evt.target || evt.srcElement; var data; if (tgt tgt.tagName tgt.tagName.toLowerCase() == 'a') { data = dataObj[tgt.id]; // Should guard against error here if (typeof data != 'undefined') { // Have data related to this element, do // something with it alert( 'Name: ' + data.name + '\nType: ' + data.type + '\nAbout: ' + data.about ); } } } -- Rob