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 money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
noapparentfunction
Apr 27, 2006

spin that 45 funk.

Avenging Dentist posted:

Look at the number of quotation marks in this (underlined for emphasis):
pre:
<a href="#" onclick="function() {
                $(".widearea").animate({
                        marginLeft: "0px"
                }, 500">art.</a>
Also, you should be doing the same thing you did with your buttons. Just give them an ID.

Thanks for the help. Should I get rid of those quotation marks or replace them with a different character? I tried removing them and the links did not work. Also, I don't know how to assign an ID to the links like I did the buttons, so if you could help me with that I'd appreciate it.

Here's what it looks like in context. I'm really pleased with the results.

http://www.noapparentfunction.com/experimental/

Adbot
ADBOT LOVES YOU

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

noapparentfunction posted:

Thanks for the help. Should I get rid of those quotation marks or replace them with a different character? I tried removing them and the links did not work. Also, I don't know how to assign an ID to the links like I did the buttons, so if you could help me with that I'd appreciate it.

You can use single quotes if you like. Also, adding an ID to an "a" tag is exactly the same as adding one to a "button" tag: id="butts". As usual, each ID must be unique on that page.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



I can't figure out why the result would be i = 0:

code:
Array.prototype.blah = function(){i = 0;}
function wtf()
{
	ary = new Array();
	i = 10;
	ary.blah();
	alert('i = ' + i);
}
How does the blah function have access to things in the wtf function's scope? I could understand if blah was inside wtf, but not this.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Munkeymon posted:

I can't figure out why the result would be i = 0:

code:
Array.prototype.blah = function(){i = 0;}
function wtf()
{
	ary = new Array();
	i = 10;
	ary.blah();
	alert('i = ' + i);
}
How does the blah function have access to things in the wtf function's scope? I could understand if blah was inside wtf, but not this.

Because you have i set up as a global. Because you didn't use this or var in front of it.

code:
Array.prototype.blah = function(){
 this.i = 0;  // belongs to the Array instance
}
function wtf()
{
	ary = new Array();
	i = 10; // this is global because var is not in front of it.
	ary.blah();
	alert('i = ' + i);
}

Lumpy fucked around with this message at 23:08 on Jun 2, 2009

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
A variable declared without the var keyword is global.

Magicmat
Aug 14, 2000

I've got the worst fucking attorneys
Let me preface this by saying I am not a Javascript programmer in any way. It's been almost a decade since I touched it seriously, and in that time the language (and paradigm) have changed enough to make whatever I did remember almost useless.

With that said, I'm wondering if one of you guys can help me with a Greasemonkey script. The short version is that I'm trying to find a way to delete certain elements on the Facebook homepage (specifically, I want to get rid of "Highlights" items from people whom I don't care about.)

The proof-of-concept works fine either using getElementsByClassName() or jQuery. The problem comes in the fact that Facebook uses some AJAX'ified way to load pages. When you click a link it doesn't send you to a new page, it (so far as I can tell) uses some Javascript to fetch and the new page's data, erases the current page data and replaces it with the new data. Effectively, it's loading new pages without ever having to actually load a new page.

This is a problem because Greasemonkey scripts run when a page is loaded. If it never detects the page is reloaded, the script never runs. The effect is that my script works great when you first go to facebook.com, since that's a normal load, but if you click a link and then click a link back to the homepage, my script is completely oblivious because FB is 'cheating' on the load, and my script is never run, and the homepage is rendered unmolested.

Do any Facebook users now what/how I can hook whatever function it uses to load new pages to then trigger my script?

One lead I'm investigating is that FB seems to load some new iFrames on each cheater load, and those do trigger my script (though it then senses that the page being loaded, being simply a hidden data frame, isn't the homepage and then gives up.) Is there an easy way to maybe make my script, triggered inside an iFrame, 'break out' of the iFrame and then run on the containing page?

ronin109
Aug 23, 2002
Since you are creating a GM script (hence, developing this for Firefox only) you can use the DOMSubtreeModified or DOMNodeInserted events to signal the deletion script.

Magicmat
Aug 14, 2000

I've got the worst fucking attorneys

ronin109 posted:

Since you are creating a GM script (hence, developing this for Firefox only) you can use the DOMSubtreeModified or DOMNodeInserted events to signal the deletion script.
I was looking into that. Is the best method just to then trigger my item deletion function when the DOMNodeInserted event is fired? I'm afraid that may bog down the browser. Will there be any problem of an infinite loop if I'm just deleting items out of the DOM?

sonic bed head
Dec 18, 2003

this is naturual, baby!
Does anyone know of a multiple select javascript code that works with Prototype JS core? I don't want to use any other add on libraries like livepipe and I don't particularly want to roll my own.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Lumpy posted:

Because you have i set up as a global. Because you didn't use this or var in front of it.

Fucks sake. I promise I'll stay home when I'm sick next time.

FrozenShellfish
Aug 30, 2004

I'm making a nice website for a mobile library project in the Peruvian Andes, I tried to use javascript to make the forms easier to fill out and then I realised I don't have a clue what I am doing :(

This does what I want in firefox (adds/removes another row from the table) but it doesn't work at all in IE. Can someone fix it for me? Cheers.
http://new.bibliotecaurubamba.com/iesucks.htm
code:
<!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" lang="en">
 
<head> 
<script type="text/javascript"> 
// Last updated 2006-02-21
function addRowToTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);
  
  // left cell
  var cellLeft = row.insertCell(0);
  var al = document.createElement('input');
  al.type = 'text';
  al.name = 'bookid' + iteration;
  al.id = 'bookid' + iteration;
  al.class = 'field';
  al.tabindex='1';
  al.maxlength='4';
  al.size='5';
  cellLeft.appendChild(al);
  
  // right cell
  var cellRight = row.insertCell(1);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'firstname' + iteration;
  el.id = 'firstname' + iteration;
  el.class = 'field';
  el.tabindex='1';
  el.maxlength='20';
  el.size='21';
  cellRight.appendChild(el);
  
  // select cell
  var cellRightSel = row.insertCell(2);
  var ol = document.createElement('input');
  ol.type = 'text';
  ol.name = 'lastname' + iteration;
  ol.id = 'lastname' + iteration;
  ol.class = 'field';
  ol.tabindex='1';
  ol.maxlength='30';
  ol.size='31';
  cellRightSel.appendChild(ol);
}
function removeRowFromTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
function openInNewWindow(frm)
{
  // open a blank window
  var aWindow = window.open('', 'TableAddRowNewWindow',
   'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
   
  // set the target to the blank window
  frm.target = 'TableAddRowNewWindow';
  
  // submit
  frm.submit();
}
function validateRow(frm)
{
  var chkb = document.getElementById('chkValidate');
  if (chkb.checked) {
	var tbl = document.getElementById('tblSample');
	var lastRow = tbl.rows.length - 1;
	var i;
	for (i=1; i<=lastRow; i++) {
	  var aRow = document.getElementById('txtRow' + i);
	  if (aRow.value.length <= 0) {
		alert('Row ' + i + ' is empty');
		return;
	  }
	}
  }
  openInNewWindow(frm);
}
 
 
</script>  
</head>
 
<body>
  
<form action="./iesucks.htm" method="post">
 
<table border="1" id="tblSample">
  <tr>
	<th class=\"top\" scope=\"col\">BookID</th>
	<th class=\"top\" scope=\"col\">First Name</th>
	<th class=\"top\" scope=\"col\">Last Name</th>
  </tr>
  
  <tr>
	<td><input type="text" name="bookid1" id="bookid1" size="5"  maxlength="4" class="field" tabindex="1" /></td>
	<td><input type="text" name="firstname1" id="firstname1" size="21" maxlength="20" class="field" tabindex="1" /></td>
	<td><input type="text" name="lastname1" id="lastname1" size="31" maxlength="30" class="field" tabindex="1" /></td>
  </tr>  
  
</table>
<input type="hidden" name="done" value="1" />
 
<p>
<input type="button" value="One more" onclick="addRowToTable();" />
<input type="button" value="One less" onclick="removeRowFromTable();" />
<input type="submit" name="submit" id="submit_1" class="button" value="Submit" tabindex="6" />
</form>
 
</body>
</html>
edit: fixed it very soon after I posted this: it didn't like the line "al.class='field'" for some reason

FrozenShellfish fucked around with this message at 07:34 on Jun 8, 2009

Roctor
Aug 23, 2005

The doctor of rock.

FrozenShellfish posted:

I'm making a nice website for a mobile library project in the Peruvian Andes, I tried to use javascript to make the forms easier to fill out and then I realised I don't have a clue what I am doing :(

This does what I want in firefox (adds/removes another row from the table) but it doesn't work at all in IE. Can someone fix it for me? Cheers.
http://new.bibliotecaurubamba.com/iesucks.htm

It appears to work fine in ie 8.

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

FrozenShellfish posted:

I'm making a nice website for a mobile library project in the Peruvian Andes, I tried to use javascript to make the forms easier to fill out and then I realised I don't have a clue what I am doing :(

This does what I want in firefox (adds/removes another row from the table) but it doesn't work at all in IE. Can someone fix it for me? Cheers.
http://new.bibliotecaurubamba.com/iesucks.htm

edit: fixed it very soon after I posted this: it didn't like the line "al.class='field'" for some reason

It'd be worth your while to check out jquery - using it you could probably reduce this down to a few lines of code as well as making it more cross-browser compatible.

Fruit Smoothies
Mar 28, 2004

The bat with a ZING
Hey. I have an XML request which gives me a list of data. An older version of these data already exist on the webpage. Both data are variants on a simple list. What's the best way of syncing these lists? In the HTML list, each item is in its own div, and the XML nodes from the new list are being looped through.
The method I can think of at the moment, is to remove all old (HTML) items from the new (XML) list. If an item isn't found in the XML list, it's removed from the HTML. At the end, all the remaining items in the XML are added to the HTML div list.
This poses data structure problems, and I'm not familiar with how best to handle lists in javascript. Would arrays be the way forward?

Supervillin
Feb 6, 2005

Pillbug

Fruit Smoothies posted:

Hey. I have an XML request which gives me a list of data. An older version of these data already exist on the webpage. Both data are variants on a simple list. What's the best way of syncing these lists? In the HTML list, each item is in its own div, and the XML nodes from the new list are being looped through.
The method I can think of at the moment, is to remove all old (HTML) items from the new (XML) list. If an item isn't found in the XML list, it's removed from the HTML. At the end, all the remaining items in the XML are added to the HTML div list.
This poses data structure problems, and I'm not familiar with how best to handle lists in javascript. Would arrays be the way forward?

Performance-wise it seems like it would be much faster to just replace the whole list than to sync using two or possibly three loops through each set. Maybe I'm too tired or something, but wouldn't you get the same data if you destroy the HTML list and add all the XML items?

Edit: If I DID misunderstand, either Arrays or object literals should work fine. Those are pretty much the only list paradigms built into JavaScript. I know ExtJS and probably some other libraries have ways of binding data sets together, might be what you need.

Editx2: vvv Just need more semantic markup and you should be all set. Make your list a real list (ul/dl), or if that's not feasible at least surround the list with a container div that can be reset without affecting the forms and images after the list.

Supervillin fucked around with this message at 01:38 on Jun 14, 2009

Fruit Smoothies
Mar 28, 2004

The bat with a ZING

Supervillin posted:

Performance-wise it seems like it would be much faster to just replace the whole list than to sync using two or possibly three loops through each set. Maybe I'm too tired or something, but wouldn't you get the same data if you destroy the HTML list and add all the XML items?

Edit: If I DID misunderstand, either Arrays or object literals should work fine. Those are pretty much the only list paradigms built into JavaScript. I know ExtJS and probably some other libraries have ways of binding data sets together, might be what you need.

The trouble is, there are other elements tree'd under the list items. These contain forms and images which empty and flicker if the HTML is re-written. The list updates about every second.

0zzyRocks
Jul 10, 2001

Lord of the broken bong
Quick question... how do I stop the onBeforeUnload event from popping up its default question window (aside from not returning anything in the callback function)?

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL
Why are you listening for beforeunload events, if not to potentially stop the document unloading? Could you listen for unload instead?

0zzyRocks
Jul 10, 2001

Lord of the broken bong
I need to have the user decide whether they want to save data on a webapp before navigating away. I wanted to use my own confirm window so I could capture what button was clicked. Is there a way to capture the button clicked on the default beforeunload event popup?

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL
The only way to see which button the user pressed is to test whether the unload event follows the beforeunload event. Browsers deliberately restrict the author's choices in this scenario, and always display a standardized UI for the close-tab confirmation dialog, because they don't want to let malicious sites confuse users about the basic mechanics of navigating and closing/opening windows. I guess this is partly fallout from the well-established tradition of making banner ads or popups look like system dialog boxes, to fool users into clicking or obeying them.

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

0zzyRocks posted:

I need to have the user decide whether they want to save data on a webapp before navigating away. I wanted to use my own confirm window so I could capture what button was clicked. Is there a way to capture the button clicked on the default beforeunload event popup?

Gmail seems to manage this - if you try and leave it before data finishes loading it presents you with a prompt that allows you to stay with the page even though you've requested to leave it.

Good luck making sense of viewing their source though!

Save the whales
Aug 31, 2004

by T. Finn

0zzyRocks posted:

I need to have the user decide whether they want to save data on a webapp before navigating away. I wanted to use my own confirm window so I could capture what button was clicked. Is there a way to capture the button clicked on the default beforeunload event popup?

So, you don't want to prevent them from leaving, but you want to prompt them to save before leaving, right? How about this?

code:
var saved = false;

function save() {
  saved = true;
  alert('data saved!');
}

window.onbeforeunload = function() {
  if (!saved) {
    if (confirm('You have unsaved data.  Save??')) {
      save();
    }
  }
};

Jreedy88
Jun 26, 2005
thirty4
I have this in my CSS:
code:
#headers
{
	display:none;
}
And I'm trying to use this JavaScript in a function later on to dynamically display something:

code:
document.getElementById("headers").style.display = "";
It's a no go. I don't understand why it's not making it visible. I've done this tons of times before without defining the style in the stylesheet. Now that I've defined the style of none in the sheet, it won't reappear. Also, is there a better way to do this?

I just want the element to be invisible on page load and visible after a function is called.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Jreedy88 posted:

I have this in my CSS:
code:
#headers
{
	display:none;
}
And I'm trying to use this JavaScript in a function later on to dynamically display something:

code:
document.getElementById("headers").style.display = "";
It's a no go. I don't understand why it's not making it visible. I've done this tons of times before without defining the style in the stylesheet. Now that I've defined the style of none in the sheet, it won't reappear. Also, is there a better way to do this?

I just want the element to be invisible on page load and visible after a function is called.

Set the display to block.

Think "none" = invisible, "block" = visible

Jreedy88
Jun 26, 2005
thirty4

Lumpy posted:

Set the display to block.

Think "none" = invisible, "block" = visible

Yay! Worked like a charm. Thanks.

Supervillin
Feb 6, 2005

Pillbug

Jreedy88 posted:

Yay! Worked like a charm. Thanks.

FYI, when you set it to "" you're telling it to set display to whatever its default is, which according to your CSS is "none"; that's why it seemed like it didn't do anything.

Often when you come across snippets that hide/show stuff they'll use display="none" to hide it and display="" to show it, because the default could be "inline", "block", etc. depending on the element.

Jreedy88
Jun 26, 2005
thirty4

Supervillin posted:

FYI, when you set it to "" you're telling it to set display to whatever its default is, which according to your CSS is "none"; that's why it seemed like it didn't do anything.

Often when you come across snippets that hide/show stuff they'll use display="none" to hide it and display="" to show it, because the default could be "inline", "block", etc. depending on the element.

Yeah, block formatting messed my page design anyways so I ended up just doing a display="none" on the element in javascript after the page had loaded.

Jreedy88 fucked around with this message at 16:25 on Jun 26, 2009

Tivac
Feb 18, 2003

No matter how things may seem to change, never forget who you are

Jreedy88 posted:

Yeah, block formatting messed my page design anyways so I ended up just doing a display="none" on the element in javascript after the page had loaded.

The answer to your disappeared question is to use "new Date()" instead of just "Date()", fyi.

Synter
Sep 22, 2004

College Slice
I've been working on a Firefox extension, and I'm having trouble with a particular javascript function.

code:
function GetStatus(timeout) {
  var sreq = new XMLHttpRequest();
  sreq.onreadystatechange = function (aEvt) {
    if (sreq.readyState == 4) {
      if(sreq.status == 200) {
	    var img = document.write("http://url.com/Smileys/sa/" + sreq.responseText);
        document.getElementById("WOPR-ImgLeft").value = img;
		document.getElementById("WOPR-ImgRight").src = "http://url.com/Smileys/sa/goonpatriot.png";
      }
    }
  };
  sreq.open('GET', URL()+'/toolbar_status.php', true);
  sreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  sreq.send(null);
  if (timeout) {
    setTimeout ("GetStatus()", 1000*60*30);
  }
}
The function is supposed to recursively call itself every 30 minutes (it does), retrive the image name from toolbar_status.php (it does) and point two images that appear in the toolbar to it.

I have tried multiple combinations of document.getElementById(image id).value and .src with combinations of the above image options (document.write("http://url.com/Smileys/sa/" + sreq.responseText) and a direct url like "http://url.com/Smileys/sa/goonpatriot.png") and neither seem to work.

The part of overlay.xul in particular is correct as far as I can tell, but posting it just in case:
code:
<toolbaritem flex="0" height="20">
	<image id="WOPR-ImgLeft" />
</toolbaritem>
<toolbaritem flex="0" align="center">
	<label id="WOPR-GetMessage" />
</toolbaritem>
<toolbaritem flex="0" height="20">
	<image id="WOPR-ImgRight" />
</toolbaritem>
Edit:

Never mind, fixed.
Going to write "I shouldn't be using document.write to concatenate strings" 100 times on the blackboard

Synter fucked around with this message at 12:49 on Jun 27, 2009

Ether Frenzy
Dec 22, 2006




Nap Ghost
I'm having trouble amending this javascript form submission to also allow the "Enter" key to submit the form. I'm not that experienced with javascript, so my googling has not been resulting in any successes at inserting the additional elements.

my form currently checks a text area entry against a list of promotional codes before passing the user along to the next page, what I need it to do is to accept both pressing the 'go' button as well as hitting enter to submit the promotional code, so if anyone could explain to me how to do that I'd really appreciate it.

My form:
code:
<div class="action">
                <form id="codeentry" name="codeentry" action="">
                        
                <input type="text" name="refcode" id="refcode" value=""> <br><br>
               
           <p class="submit"> <input type="button" onclick="refcodecheck()" value=""></p>

</form><br>
                
            </div>
My javascript code checker:
code:
<script language="javascript" type="text/javascript">
    function refcodecheck()

    {   

        var codes = new Array("7 one nine","7-one-nine","7-one nine");

        for (var i=0;i<19;i++)

        {

            if (document.getElementById('refcode').value.toLowerCase() == codes[i])

            {   //code matched

               
                window.location = 'http://www.google.com';

                return false;

            }

        }

        //code did not match

        alert('You have entered an invalid code.  Please try again or go to [url]www.coderequest.com[/url] to register for a valid code.');
      
    }      

</script>  

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Ether Frenzy posted:

I'm having trouble amending this javascript form submission to also allow the "Enter" key to submit the form. I'm not that experienced with javascript, so my googling has not been resulting in any successes at inserting the additional elements.

my form currently checks a text area entry against a list of promotional codes before passing the user along to the next page, what I need it to do is to accept both pressing the 'go' button as well as hitting enter to submit the promotional code, so if anyone could explain to me how to do that I'd really appreciate it.


First link from a Google for "javascript bind keys" has a pretty good tutorial:

http://www.javascriptkit.com/javatutors/javascriptkey.shtml

Ether Frenzy
Dec 22, 2006




Nap Ghost
Thanks for that tutorial link - didn't actually get my problem solved but having looked over that site some more, I'm learning more about JS now than I...uh, really wanted to know.

But I did eventually get my script tweaked using googled results that plugged into my existing form validator...

Here's what did the trick:


code:
  <script language="javascript">
    
function catchEnter(e)

{

    // Catch IE’s window.event if the
    // ‘e’ variable is null.
    // FireFox and others populate the

    // e variable automagically.
   if (!e) e = window.event; 

   // Catch the keyCode into a variable. 
   // IE = keyCode, DOM = which.
   var code = (e.keyCode) ? e.keyCode : e.which;

           

    // If code = 13 (enter) or 3 (return),
    // cancel it out; else keep going and
    // process the key.
    if (code == 13 || code == 3) 
    {
        refcodecheck();
        return false;
    }
    
}


// Anonymous method to push the onkeypress
// onto the document.
// You could finegrain this by
// document.formName.onkeypress or even on a control.
window.onload = function() { document.onkeypress = catchEnter; };


</script>


    <script language="javascript" type="text/javascript">
    function refcodecheck()
    {   

        var codes = new Array("7 one nine","7-one-nine","7-one nine");

        for (var i=0;i<19;i++)

        {

            if (document.getElementById('refcode').value.toLowerCase() == codes[i])

            {   //code matched

               
                window.location = 'http://www.google.com';

                return false;

            }

        }

        //code did not match

        alert('You have entered an invalid code.  Please try again or go to [url]www.coderequest.com[/url] to register for a valid code.');

        

    }      
</script>   

:cheers:

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

Ether Frenzy posted:

Here's what did the trick:


code:
...
:cheers:

A-are you seriously doing validation on the client side? :barf:

spiritual bypass
Feb 19, 2008

Grimey Drawer

Avenging Dentist posted:

A-are you seriously doing validation on the client side? :barf:

Seems fine to me if it's there to complement existing server validation.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

Ether Frenzy posted:

I'm having trouble amending this javascript form submission to also allow the "Enter" key to submit the form. I'm not that experienced with javascript, so my googling has not been resulting in any successes at inserting the additional elements.

Shouldn't it work just to make your input button type="submit"?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

royallthefourth posted:

Seems fine to me if it's there to complement existing server validation.

Yeah, I don't think "putting the list of valid (presumably secret) codes in Javascript" counts as "complementing server validation".

ronin109
Aug 23, 2002
By default, a form will be submitted whenever a form field has focus and the user presses the enter key so there is no need to recreate that functionality. The proper way to handle client-side validation is by using the form's onsubmit event. If the form fails validation you simply return false to cancel the form's submission. Returning true (actually, by not explicitly returning false) will cause the form to submit.

The main problem with your current approach of listening for key events on the document is that pressing enter anywhere on the page (outside your form) will cause your form to be validated and submitted.

What you really should do is use a submit button and do your validation (refcodecheck) in the onsubmit.

However, all of this is moot if you actually intend to do (presumably secret) reference code checks since, as Avenging Dentist points out, that should be a server-side only check to avoid putting the "secret" answers in the source code of the page.

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

ronin109 posted:

However, all of this is moot if you actually intend to do (presumably secret) reference code checks since, as Avenging Dentist points out, that should be a server-side only check to avoid putting the "secret" answers in the source code of the page.

Secret-code validation done on the client side would make a pretty good captcha for a programming website though. :xd:

Ether Frenzy
Dec 22, 2006




Nap Ghost

Avenging Dentist posted:

A-are you seriously doing validation on the client side? :barf:

Tell me about it.

I wanted to do serverside validation with PHP but the location of the program is outside our boundaries, and the clients (and my bosses) were happy with the total lack of security. I let them know that this was not the real way to do this, but they didn't care. Which is why I ended up hacking up some JS to function here.

The promo codes are freebie giveaways anyway, that are all virtually the same, but we wanted the illusion that they're original. Fundamentally security wasn't that high a priority with the sponsors, they were more interested that the users are passed through to the part where they spend money.

Kilson posted:

Shouldn't it work just to make your input button type="submit"?

You can't do a satisfactory image replacement of the submit button (or at least not have it work in IE 6, which we stupidly continue to support - would typically be done with CSS v2) with input type="submit", it has to be input type="button" to use an image as the button.

Which generated all this additional nonsense anyway.

Adbot
ADBOT LOVES YOU

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
Full disclosure - I posted this in the Web Design & Development small questions thread, but came to the conclusion that it's really more Javascript and I will be more likely to get help with it here. Hence I'm reposting it.

My website implements a board game via PHP. A user can view a game in progress by visiting a URL that looks like mywebsite.com/board.php?GameID=1234. Although the site is essentially set up to enable a play-by-email kind of experience, it might happen that some users would like to play in real time, or close to real time. Because the page generated when visiting the URL is static, they can only see what the real current state of the game is by refreshing the page. This is inconvenient, and it means more work for my website too if people are constantly refreshing pages, so I rigged up a hack to slightly reduce the problem. To each game there corresponds a number saying how many moves have been made in the game. So it starts off at zero and is incremented whenever someone makes a move. If a user loads a page corresponding to a game in progress, then a Javascript runs such that every five seconds the page checks with the website to see if the number of moves made is bigger. If it is then it turns the page background a different colour, so as to alert the user without interrupting any activity the user is performing on the page.

My <body> tag looks like this:

<body onLoad="IntervalID = setInterval ('ajaxFunction()', 5000);" onUnload="clearInterval(IntervalID);">

For completeness, here is ajaxFunction: (This was taken from the page from a game that at the time had had 95 moves made, hence the "95")

code:
function ajaxFunction() {
    /* Attribution: This JavaScript code is based on code
       taken from w3schools.com */
    var xmlHttp;
    try { xmlHttp=new XMLHttpRequest(); }
    catch (e) {
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            return false;
        }
    }
    xmlHttp.onreadystatechange=function() {
        if ( xmlHttp.readyState == 4 ) {
            if ( xmlHttp.responseText != "95" ) {
                document.bgColor = "#BFDFFF";
                clearInterval(IntervalID);
            }
        }
    };
    xmlHttp.open("GET","newmoves.php?GameID=1234",true)
    xmlHttp.send(null);
}
My question: I noticed that occasionally when one leaves the page, the page background will change colour (despite the fact that when one comes back, no new moves have been made). I deduce that this is because the every-five-second function happens to be running at just that time. I attempted to tackle this by adding to the <body> tag (as given above) the following:

onUnload="clearInterval(IntervalID);"

This does not solve the problem. The page still changes colour sometimes when one leaves. What should I do to stop this?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply