Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us $3,400 per month for bandwidth bills alone, and since we don't believe in shoving popup ads to our registered users, we try to make the money back through forum registrations.
«54 »
  • Locked thread
Iron Squid
Nov 23, 2005

by Ozmaugh


Haystack posted:

Ah, I think I've got it. If I recall correctly, javascript doesn't like it if you stick code in the body of a <script> tag that's also importing a .js file*.

So try putting the the $(document).ready call in it's own script tag, like so:
code:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="hide.js"></script>
<script type="text/javascript">
    $(document).ready({
        hide()
    });
</script>
*Edit: Alternately, it might just be that hide.js doesn't get loaded until its script tag closes. I suppose I could look it up, but

That was a great idea, and changing my code to match yours filled me with optimism. Unfortunately, it doesn't work. When I try to look at the hide.js via Firebug, I don't even see it listed. Just jquery.js. So that might be something right there. :|

Aimee posted:

I'm more curious why you do .css("display","none") in some places but hide()/show() in others. Or why you're outputting your HTML headers via echo with a PHP function but I'll give you the benefit of the doubt on that one

This is quite literally the first PHP/CSS/JS project I've ever done. That JS code was lifted from elsewhere, so I can't really defend it. I output the HTML headers because I want to reuse that code in a couple different places, and just want a PHP function to reduce the amount of time I have to write headers.

Adbot
ADBOT LOVES YOU

Supervillin
Feb 6, 2005



Pillbug

Iron Squid posted:

Nope, didn't fix it. Am I calling the script properly?

No, he was right. Both of your if statements had an extra }); after the } that already closed the if statement (and before the }); which closes the function).

Run your code through jslint to catch the above errors and jsbeautifier for pretty.

code:

function hide() {

    //Hide div w/id extra
    $("#rpg_games").css("display", "none");
    $("#tabletop_games").css("display", "none");

    $("#rpg").click(function () {
        if ($("#rpg").is(":checked")) {
            $("#rpg_games").show("fast");
        }
        else {
            $("#rpg_games").hide("fast");
        }
    });

    $("#mini").click(function () {
        if ($("#mini").is(":checked")) {
            $("#tabletop_games").show("fast");
        }
        else {
            $("#tabletop_games").hide("fast");
        }
    });

}
Don't use GNU style formatting for JavaScript, use One True Brace Style. JavaScript has what's called "automatic semicolon insertion", which (long story short) can break poo poo if you put { on its own line.

Iron Squid
Nov 23, 2005

by Ozmaugh


Supervillin posted:

No, he was right. Both of your if statements had an extra }); after the } that already closed the if statement (and before the }); which closes the function).

Run your code through jslint to catch the above errors and jsbeautifier for pretty.

code:

function hide() {

    //Hide div w/id extra
    $("#rpg_games").css("display", "none");
    $("#tabletop_games").css("display", "none");

    $("#rpg").click(function () {
        if ($("#rpg").is(":checked")) {
            $("#rpg_games").show("fast");
        }
        else {
            $("#rpg_games").hide("fast");
        }
    });

    $("#mini").click(function () {
        if ($("#mini").is(":checked")) {
            $("#tabletop_games").show("fast");
        }
        else {
            $("#tabletop_games").hide("fast");
        }
    });

}
Don't use GNU style formatting for JavaScript, use One True Brace Style. JavaScript has what's called "automatic semicolon insertion", which (long story short) can break poo poo if you put { on its own line.

Ah, okay. That's good to know about the formatting.

I made the changes (well, I just lifted yours) and put it on my page, but its still not executing. When I look at the Javascript panel in Firebug, it should list both the jQuery.js file *and* hide.js, correct? Because its just showing jQuery.js.

Dromio
Oct 16, 2002
Sleeper

Anyone have experience dealing with <input type="file"/> and json in jQuery?

I'm writing a RESTfull service that accepts a JSON object for file uploads. The service accepts an object that should have a filename and a byte-array for the data.

How do I get the binary data from the file into a byte array for my json object? I've been googling around but all I find are jquery plugins to do asynchronous multi-file uploads and stuff. I just want a dead-simple test form that'll take the input, make a json object, and POST it to my service.

Dromio fucked around with this message at Sep 20, 2010 around 21:12

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL


Unfortunately, the only way to read the data from a file input element is to actually submit the form. Browsers don't provide any method to read a local file on the client.

No Safe Word
Feb 26, 2005



Nigglypuff posted:

Unfortunately, the only way to read the data from a file input element is to actually submit the form. Browsers don't provide any method to read a local file on the client.

I believe you meant fortunately there because hoo boy if they did...

Iron Squid
Nov 23, 2005

by Ozmaugh


Got my problem figured out. Turns out I needed to call my document.ready like this:

code:
$(document).ready(function()
Phew!

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL


No Safe Word posted:

I believe you meant fortunately there because hoo boy if they did...
How would this be bad?
code:
var fileInputElement = document.querySelector('input[type=file]');
fileInputElement.readTextData(function (data) {
    alert(data);
});

No Safe Word
Feb 26, 2005



Nigglypuff posted:

How would this be bad?
code:
var fileInputElement = document.querySelector('input[type=file]');
fileInputElement.readTextData(function (data) {
    alert(data);
});

I don't want my browser's javascript engine reading my local files without making it something that I've submitted. Far too vulnerable to privacy/security issues if someone runs malicious javascript. In your example, what's to stop the javascript itself from populating the filepath of the file input element and then reading any arbitrary file on the filesystem?

Dromio
Oct 16, 2002
Sleeper

No Safe Word posted:

In your example, what's to stop the javascript itself from populating the filepath of the file input element and then reading any arbitrary file on the filesystem?

I think it already unable to populate the filepath of the file input element -- (to keep malicious scripts from secretly submitting /etc/passwd). Allowing it to read the data from something I've explicitly chosen seems far less of a problem.

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL


Yep -- the system would be secure, because the path of a file input element is already read-only. Forcing the server to accept an upload, and then echo the file contents back to the client, seems unnecessarily complicated and a waste of bandwidth.

Nigglypuff fucked around with this message at Sep 21, 2010 around 16:12

Senso
Nov 4, 2005

Always working

I'm having a weird issue but it's probably something easy I've overlooked.
I have a calendar form with two submit buttons, so users can add/remove date ranges.

I have a debug alert() in there, the whole thing works but the first time, the alert pops once, the second time you click, it pops twice, etc. It looks like I'm adding a handler every time there's a click and they stack or something like that, right? Maybe I'm doing it wrong and I shouldn't bind on the form buttons AND on the submit?

code:
<div id="note"></div>
<form action="" id="add_period" class="add_period">
  <input type="submit" value="Add Period" class="button" id="add_button" />
  <input type="submit" value="Remove Period" class="button" id="rem_button" />
</form>

$("#add_button").click(function() {aurl = "/ajax/add_period/";});
$("#rem_button").click(function() {aurl = "/ajax/rem_period/";});

$(document).ready(function(){
    $("#add_period").submit(function(){
        var str = $(this).serialize();
        
        $.ajax({type: "POST", url: aurl, data: str, success: function(msg){
            $("#note").ajaxComplete(function(event, request, settings){
                alert(aurl);
                var pmsg = JSON.parse(msg);
                ...
            });    
        }
    });
    return false;
    });
});

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Senso posted:

I'm having a weird issue but it's probably something easy I've overlooked.
I have a calendar form with two submit buttons, so users can add/remove date ranges.

I have a debug alert() in there, the whole thing works but the first time, the alert pops once, the second time you click, it pops twice, etc. It looks like I'm adding a handler every time there's a click and they stack or something like that, right? Maybe I'm doing it wrong and I shouldn't bind on the form buttons AND on the submit?

code:
<div id="note"></div>
<form action="" id="add_period" class="add_period">
  <input type="submit" value="Add Period" class="button" id="add_button" />
  <input type="submit" value="Remove Period" class="button" id="rem_button" />
</form>

$("#add_button").click(function() {aurl = "/ajax/add_period/";});
$("#rem_button").click(function() {aurl = "/ajax/rem_period/";});

$(document).ready(function(){
    $("#add_period").submit(function(){
        var str = $(this).serialize();
        
        $.ajax({type: "POST", url: aurl, data: str, success: function(msg){
            $("#note").ajaxComplete(function(event, request, settings){
                alert(aurl);
                var pmsg = JSON.parse(msg);
                ...
            });    
        }
    });
    return false;
    });
});


Each call to .click() ADDS a handler. The little snippet you posted doesn't look like it's adding multiple handlers, but you truncated it so maybe it's somewhere else. To avoid dupe handlers you can do something like:

code:
jQuery('#someEl').unbind('click').click( function(){ //blah } );

Senso
Nov 4, 2005

Always working

Lumpy posted:

Each call to .click() ADDS a handler. The little snippet you posted doesn't look like it's adding multiple handlers, but you truncated it so maybe it's somewhere else. To avoid dupe handlers you can do something like:

code:
jQuery('#someEl').unbind('click').click( function(){ //blah } );

Ah, I see my error, it wasn't with the buttons click()! I register ajaxComplete() inside the submit() call, so that one would stack each time an AJAX call was made (for every form submit).

I seem to have fixed it by doing what you did, but for ajaxComplete():
code:
$("#note").unbind('ajaxComplete').ajaxComplete(function(event, request, settings){

Iron Squid
Nov 23, 2005

by Ozmaugh


I'm using these [url=]Modal Dialog[/url] tools to do some stuff with jQuery. The problem that I'm running into is that I would like the dialog to appear when the user clicks on a checkbox, instead of a button.

Imagine that I have a fieldset within a form, that has a bunch of checkboxes, like so:

code:
<label for="tt1">Pineapple</label>
<input type = checkbox id="tt1" name="tt1">
<label for="tt2">Bananas</label>
<input type = checkbox id="tt2" name="tt2">
<label for="tt3">Kiwis</label>
<input type = checkbox id="tt3" name="tt3">
What would the jQuery code be to get a modal dialog to pop-up when a user checks a checkbox?

Aimee
Jan 2, 2007



Iron Squid posted:

I'm using these [url=]Modal Dialog[/url] tools to do some stuff with jQuery. The problem that I'm running into is that I would like the dialog to appear when the user clicks on a checkbox, instead of a button.

Imagine that I have a fieldset within a form, that has a bunch of checkboxes, like so:

code:
<label for="tt1">Pineapple</label>
<input type = checkbox id="tt1" name="tt1">
<label for="tt2">Bananas</label>
<input type = checkbox id="tt2" name="tt2">
<label for="tt3">Kiwis</label>
<input type = checkbox id="tt3" name="tt3">
What would the jQuery code be to get a modal dialog to pop-up when a user checks a checkbox?

If you don't care if the checkbox's value is checked or unchecked, it should be handled almost exactly the same way as a button:
code:
$("#your-fieldset-id input[type='checkbox']").click(function ()
{
//code to open your modal dialog
});
The only difference would be that the selector changed from button or input[type='submit'].

if you want it to only happen if it's checked, just a tiny modification to that:

code:
$("#your-fieldset-id input[type='checkbox']").click(function ()
{
 if($(this).is(":checked") {
  //code to open your modal dialog
 }
});

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Aimee posted:



if you want it to only happen if it's checked, just a tiny modification to that:

code:
$("#your-fieldset-id input[type='checkbox']").click(function ()
{
 if($(this).is(":checked") {
  //code to open your modal dialog
 }
});

If you want to save a jQuery lookup, you can also do:

code:
jQuery("#your-fieldset-id input[type='checkbox']").click(function ()
{
 if( this.checked ) {
  //code to open your modal dialog
 }
});

teagone
Jun 10, 2003

Valyrian, motherfucker! Do you speak it?!

Ok, so I'm a pretty big novice when it comes to coding for the web, and I've only dabbled with jQuery/CSS sparingly. I'm trying to implement using jQuery on my new graphic design portfolio site, and I've been doing ok so far. Just one last thing is frustrating the hell out of me.

I've got an "About Me" section that's hidden, and when you click on the "About" link, I have it set to slide down. Now, the problem is whenever I click on a image to bring it up in Fancybox, the hidden "About Me" div automatically slides down on its own. How do I prevent that from happening? I just want it to stay hidden, and only drop down when I click the link.

I uploaded my test revision to dropbox for someone to hopefully spot what's wrong in my lovely coding. You can view it here http://goo.gl/yjAm

To recreate the problem, don't click on the "about link". Just click on an image, and the about me will expand. Help! I've been stuck on this for like an hour and it's pissing me the gently caress off

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

veonenergee posted:

Ok, so I'm a pretty big novice when it comes to coding for the web, and I've only dabbled with jQuery/CSS sparingly. I'm trying to implement using jQuery on my new graphic design portfolio site, and I've been doing ok so far. Just one last thing is frustrating the hell out of me.

I've got an "About Me" section that's hidden, and when you click on the "About" link, I have it set to slide down. Now, the problem is whenever I click on a image to bring it up in Fancybox, the hidden "About Me" div automatically slides down on its own. How do I prevent that from happening? I just want it to stay hidden, and only drop down when I click the link.

I uploaded my test revision to dropbox for someone to hopefully spot what's wrong in my lovely coding. You can view it here http://goo.gl/yjAm

To recreate the problem, don't click on the "about link". Just click on an image, and the about me will expand. Help! I've been stuck on this for like an hour and it's pissing me the gently caress off

This code on your page:

code:
$('a').click(function(){
		$('#aboutme').slideDown('slow');
 
	});
Tells the aboutme to slide down when ANY 'a' element is clicked. You want to do:

code:
jQuery('#click').click(function(){
  jQuery('#aboutme').slideDown('slow');
});
You might want to change the ID to something semantic, but that's more of a nitpick.

EDIT I like your work, btw.

teagone
Jun 10, 2003

Valyrian, motherfucker! Do you speak it?!

Lumpy posted:

This code on your page:

code:
$('a').click(function(){
		$('#aboutme').slideDown('slow');
 
	});
Tells the aboutme to slide down when ANY 'a' element is clicked. You want to do:

code:
jQuery('#click').click(function(){
  jQuery('#aboutme').slideDown('slow');
});
You might want to change the ID to something semantic, but that's more of a nitpick.

EDIT I like your work, btw.

Ahh, you are awesome! Thank you, that did the trick Now, I figured I'd just change the #click ID in that code to "#close" in order to hide the aboutme div, but that doesn't seem to work. Does it require something different? (sorry super ignorant with this stuff).

Nevermind! Figured it out Thanks again so much, saved me a headache. And much appreciated on comment

teagone fucked around with this message at Sep 29, 2010 around 04:37

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Two questions:

1) Out of curiosity, does it matter whether I use $(this) or $(event.target) in situations such as these?
code:
$('.datarow input, .datarow select').live('change', function(event)
{
    var IDviaThis = $(this).closest('tr').attr('id');
    var IDviaTarg = $(event.target).closest('tr').attr('id');
}); 
2) As you can see, my bracketing style so far has been ANSI style, but earlier this page Supervillin said use One True Brace because of the whole 'add semicolon to end of lines'. I'm aware of this, but I didn't know it could conceivably affect braces. You said it was a long story, got a link to that story?

Doh004
Apr 22, 2007

Mmmmm Donuts...

I've run into an issue and was wondering if you guys could help me out. Here's the situation:

I have your standard table with its header and the rows. In each of the rows, the user can click on an expander which then does my jQuery stuff.

You make a ajax call and it returns a new table row with one column that should span all 5 of the table's columns. The new row is then inserted below the one they clicked, and I call slideToggle() on it to slide it in.

The issue is that when the new row is slid in, it's display property is set to block, when it has to be set to table-row. My code as of right now:

code:
$("#"+rusheeId+"_id_content").slideToggle();
$("#"+rusheeId+"_content_row").css("display", "table-row");
Works but it looks terrible as it pushes everything into the one cell until the slide animation is done, and then it fixes itself when the display property is set. I can't set the display property in advance because then it makes it show, but then the slide doesn't function properly.

Any ideas?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Golbez posted:

Two questions:

1) Out of curiosity, does it matter whether I use $(this) or $(event.target) in situations such as these?
code:
$('.datarow input, .datarow select').live('change', function(event)
{
    var IDviaThis = $(this).closest('tr').attr('id');
    var IDviaTarg = $(event.target).closest('tr').attr('id');
}); 
2) As you can see, my bracketing style so far has been ANSI style, but earlier this page Supervillin said use One True Brace because of the whole 'add semicolon to end of lines'. I'm aware of this, but I didn't know it could conceivably affect braces. You said it was a long story, got a link to that story?


1) Yes. If the event is bubbled, event.target and this will not be the same

2) what will this function return:
code:
function butt()
{
  return
  {
    poop: "pants",
    blurf: "bloopy"
  }
}
Answer: undefined

Braces matter.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Doh004 posted:

I've run into an issue and was wondering if you guys could help me out. Here's the situation:

I have your standard table with its header and the rows. In each of the rows, the user can click on an expander which then does my jQuery stuff.

You make a ajax call and it returns a new table row with one column that should span all 5 of the table's columns. The new row is then inserted below the one they clicked, and I call slideToggle() on it to slide it in.

The issue is that when the new row is slid in, it's display property is set to block, when it has to be set to table-row. My code as of right now:

code:
$("#"+rusheeId+"_id_content").slideToggle();
$("#"+rusheeId+"_content_row").css("display", "table-row");
Works but it looks terrible as it pushes everything into the one cell until the slide animation is done, and then it fixes itself when the display property is set. I can't set the display property in advance because then it makes it show, but then the slide doesn't function properly.

Any ideas?

User FadeIn/Out instead. Those play nice with Table Rows. Otherwise you have to wrap the rows in a DIV or some crazy thing I can't remember.

Doh004
Apr 22, 2007

Mmmmm Donuts...

*Edit* ^^^ Thanks for that tip by the way. Ended up just doing that and it works much smoother.


After a long day of coding, I thought I had everything working. Being the good webmaster that I am and all, I figured I'd test out what I had made in IE to be safe.

Turns out I'm not

I think I've found the issue and I don't know why IE would do this (doesn't happen in FF, Safari or Chrome).

code:
$("#"+rusheeId+"_collapser").unbind();
$("#"+rusheeId+"_collapser").click(function() {
     hideRushee(rusheeId,myClass);
});
I unbind the .click() event on a certain ID so that when a user clicks on it again, it calls a different function. For some reason, when running this in IE (8), the actual function is called and run when I click on my item. That shouldn't happen when I declare the new function, right? It doesn't happen in any of the other browsers. I figured this out by using IE's built in debugger, so I'm 95% sure this is what's going on.

Any help would be greatly appreciated.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Doh004 posted:

*Edit* ^^^ Thanks for that tip by the way. Ended up just doing that and it works much smoother.


After a long day of coding, I thought I had everything working. Being the good webmaster that I am and all, I figured I'd test out what I had made in IE to be safe.

Turns out I'm not

I think I've found the issue and I don't know why IE would do this (doesn't happen in FF, Safari or Chrome).

code:
$("#"+rusheeId+"_collapser").unbind();
$("#"+rusheeId+"_collapser").click(function() {
     hideRushee(rusheeId,myClass);
});
I unbind the .click() event on a certain ID so that when a user clicks on it again, it calls a different function. For some reason, when running this in IE (8), the actual function is called and run when I click on my item. That shouldn't happen when I declare the new function, right? It doesn't happen in any of the other browsers. I figured this out by using IE's built in debugger, so I'm 95% sure this is what's going on.

Any help would be greatly appreciated.

Don't double up your selector (double the amount of work = slower), and you aren't "unbinding click":

code:
jQuery('#' + rusheeId + '_collapser').unbind( 'click' ).click( function() {
  // stuff
});
I'm not quite understanding your issue... the code you posted should make it so the next time you click on that element, hideRushee(rusheeId,myClass); will be called. Is that not what's happening?

Doh004
Apr 22, 2007

Mmmmm Donuts...

Lumpy posted:

I'm not quite understanding your issue... the code you posted should make it so the next time you click on that element, hideRushee(rusheeId,myClass); will be called. Is that not what's happening?

That's correct. Only in IE, it appears that when declaring the .click(), the browser ends up running the code that I'm simply adding as the event.

I just did a step by step running of it in IE with the break points, and it does in fact go into the hideRushee function and do the code.

Doh004
Apr 22, 2007

Mmmmm Donuts...

I apologize for double posting, but I've taken a SS of the web developer tool in IE when debugging:



As you can see, I put a break point within the hideRushee function. I then looked at the Call Stack and went back to what was calling it, and as you can see when I'm defining the new .click(), it's actually running the function. Why is this happening in IE?

Keep in mind, this only happens the first time that the showRushee function is called. All subsequent callings operate correctly. :/

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30 day no risk Free Trial!


I'm using jquery-checkbox to do some fancy checkbox styling but there is a known issue that affects click and change functions.

$('input:checkbox').change() doesn't work and if you use onclick or $('input:checkbox').click(function() {}; the output is reversed.
The first click isn't recognized although the image changes. The second click is recognized as opposite and so on.

See the issues here:
http://code.google.com/p/jquery-che...ues/detail?id=4
and here:
http://code.google.com/p/jquery-che...ues/detail?id=5

The developer hasn't addressed these issues and I would really like to get this working right. I'm hoping someone here has the ability to identify the issue and help me get this working.

DarkLotus fucked around with this message at Oct 12, 2010 around 18:44

Lamb-Blaster 4000
Sep 20, 2007



I'm working on someone else's Joomla theme, the theme makes an XHR request at one point and I need to figure out the original calling function.

Using firebug I can break on XHR, but that only puts me on the general ajax request function, I need to see all the way up the call stack to the custom theme js function that started the ball rolling.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

1.4.3 is out.

* JSLint compliant (big whoop, get back to me when JSLint is jQuery compliant)
* CSS module rewrite.
* Lots of improvements to data, including having HTML 5 data show up in .data()
* Traversal is vastly improved, like .find() and .closest()
* .bind('click', false) is a simple shortcut to bind a function that returns false and stops the default action and bubbling.
* Built-in event methods like .click() accept data as the initial argument.
* event.namespace added to the event object.
* All animate methods now support easing.
* jQuery.fx.interval - "A new property that exposes the rate at which all effects fire (in milliseconds defaults to 13). Making this number smaller will make animations smoother in some browsers (such as Chrome) at the expense of CPU."
* $.type() - determines the Javascript class of an object. Which is pretty swanky. Can return boolean, number, string, function, array, date, regexp, object, undefined, null, or the object type.
* $.isWindow() does exactly that, finds out if an object is likely a window.

Sounds like there's an ugly problem with HTML 5 data, though.

Doh004
Apr 22, 2007

Mmmmm Donuts...

For the jQuery Validate plugin, I wrote a method that will only accept valid Youtube video URLs. It looks like this:

code:
jQuery(document).ready(function() {
    jQuery.validator.addMethod("youtubeVideo", function(value, element) {
	var matches = jQuery(element).val().match(/^http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=\w+)(?:\S+)?$/i);
	if (matches)
	    return true;
	else
	    return false;
     }, "Must be a valid Youtube video");
};
What do you think? I posted it on my my blog as well.

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL


@Doh004:
  • Instead of jQuery(document).ready(fn), you can just use jQuery(fn).
  • value is already the first parameter of the validation method, so you don't need to do jQuery(element).val(). In fact, you don't need element at all.
  • Rather than if (matches) {return true} else {return false}, you can just write return !! matches.
I would write the plugin like this:
code:
jQuery(function() {
  var youtubePattern = /^http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=\w+)(?:\S+)?$/i;
  
  jQuery.validator.addMethod("youtubeVideo", function(value) {
    return youtubePattern.test(value);
  }, "Must be a valid Youtube video");
});
Hope that helps

Doh004
Apr 22, 2007

Mmmmm Donuts...

Nigglypuff posted:

@Doh004:
  • Instead of jQuery(document).ready(fn), you can just use jQuery(fn).
  • value is already the first parameter of the validation method, so you don't need to do jQuery(element).val(). In fact, you don't need element at all.
  • Rather than if (matches) {return true} else {return false}, you can just write return !! matches.
I would write the plugin like this:
code:
jQuery(function() {
  var youtubePattern = /^http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=\w+)(?:\S+)?$/i;
  
  jQuery.validator.addMethod("youtubeVideo", function(value) {
    return youtubePattern.test(value);
  }, "Must be a valid Youtube video");
});
Hope that helps

That seems like a much more elegant solution. It'd probably be good if I learned more of the Javascript functions as there seems to be a lot of functionality that I'm unaware of. Thanks

Kekekela
Oct 28, 2004

by FactsAreUseless


On the validator subject, I've been meaning to ask for a slicker way to actually validate a date (since the built in "date" validator is worthless and allows poo poo like 86/87/9999) than what I cobbled together:

code:
jQuery.validator.addMethod(
        "validDate",
        function (value, element) {

            var check = false;
            var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
            if (re.test(value)) {
                var adata = value.split('/');
                var mm = parseInt(adata[0], 10);
                var gg = parseInt(adata[1], 10);
                var aaaa = parseInt(adata[2], 10);

                var xdata = new Date(aaaa, mm - 1, gg);

                if ((xdata.getFullYear() == aaaa) && (xdata.getMonth() == mm - 1) && (xdata.getDate() == gg)) {

                    switch (Number(mm)) {
                        case 1:
                        case 3:
                        case 5:
                        case 7:
                        case 8:
                        case 10:
                        case 12:
                            check = Number(gg) <= 31;
                            break;
                        case 4:
                        case 6:
                        case 9:
                        case 11:
                            check = Number(gg) <= 30;
                            break;
                        case 2:
                            if (isLeapYear(aaaa)) check = Number(gg) <= 29;
                            else check = Number(gg) <= 28;
                            break;
                    }
                }
                else
                    check = false;
            } else
                check = false;
            return this.optional(element) || check;
        },
        "Please enter a valid date."
);

function isLeapYear(y) {
    return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
}
I think I pulled the part that parses out the month/day/year from someone else's code since those don't look like my variable names and I suck with regex, but I wrote this a while back so can't really remember.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean



Remember that date validation is Locale specific, but there are a lot of good jquery date validator plugins.

Kekekela
Oct 28, 2004

by FactsAreUseless


MEAT TREAT posted:

Remember that date validation is Locale specific, but there are a lot of good jquery date validator plugins.

All of the dates have to be mm/dd/yyyy, its a preexisting site that handles prescriptions for customers in the US. It already uses jQuery validator so I wanted to just be able to add a custom validation method to that instead of using a separate plugin.

mcnealys baby
Nov 3, 2002

ohhh here we go


I am having the strangest thing happen when I break up a div, edit it, and put it back in. My code:

code:

<script type="text/javascript" >

function SplitByline(stringToSplit, charToSplit) {
    var myArray = stringToSplit.split(charToSplit);
    return myArray;
}

function init() {

		//Split the byline to get the authorText and and dateText
		$(".byline").each(function() {
			var text = $(this).text();
			authorText = SplitByline(text, " on ")[0];
			dateText = SplitByline(text, " on ")[1];
		});

		$(".byline").text(authorText);
		
		// date goes in a new div
		$('<div class="postDay" />').insertAfter(".byline");
		$('.postDay').text(dateText);

}

$( init );
</script>
The original byline div reads something like "Posted by Jack Black on Thu, Oct 14, 2010 ", and I'm breaking the div into two so I can style each part differently in CSS. The date when written into the postDay div is always written as April 30th, 2010, which is the dateText for the last entry on the page. The CMS I am using puts all author bylines, date, name, etc. into one div named "byline" so I need to break them up via CSS.

For some reason, the script reaches the end of the page, and wraps around rewriting all of the dateText tags to match that last string from the page. Then it stops running. edit: answered this myself

mcnealys baby fucked around with this message at Oct 22, 2010 around 02:19

mcnealys baby
Nov 3, 2002

ohhh here we go


Alright so I moved the part where I write the divs into inside of the each() function and it works now. Sometimes you just need to look at things again.

Adbot
ADBOT LOVES YOU

RobertKerans
Aug 25, 2006

There is a heppy lend
Fur, fur aw-a-a-ay.

I am building a Wordpress site, and I needed the photos section to work in a similar manner to Facebook's, which it now does perfectly with the ajax functionality needed added with this snippet...

code:
jQuery(document).ready(function(){
	
			jQuery('.attachmentPagination a').live('click', function(e){
				e.preventDefault();
				var link = jQuery(this).attr('href');
				jQuery('#attachmentcontent').fadeOut(500).load(link + ' #attachmentcontentInner', 
function(){ jQuery('#attachmentcontent').fadeIn(500); });
					
			});
	
		});
...only it then there is the obvious history problem. I am only learning JQuery, so am not so good at it: I am trying to use the jQuery Tools history plugin to give me what I need. I set up a test, and can get it to work with tabs or scrolling or whatever else from that UI library, but I am a retard and can't get it to work on its own with that code above that I currently have and am quite happy with. Any help would be greatly appreciated

  • Locked thread
«54 »