Posts Tagged ‘javascript’

JavaScript Tip: Submit Form On Enter Key

Sunday, May 4th, 2008

A common practice with search forms is to have them submit when the enter key is pressed, instead of requiring the user to use their mouse to press the submit button (or using tab key to tab to the submit button).

Here is a simple way to do that in JavaScript:
First, define a input box:

<input name="txtsearchentries" id="txtsearchentries" type="text" size="13" value="" />

Second, create a function to be placed in the head area of the webpage:
//see if the user pressed the enter key while using a specific control

function submitSearchOnEnter(variable)
{
  var keyCode;

  //get whatever key was just pressed
  //try to account for different methods of getting
  //event keys depending on implementation
  if(window.event)
  {
      keyCode = window.event.keyCode;
  }
  else if(variable)
  {
      keyCode = variable.which;
  }

  //if the key was the enter key, perform the necessary function
  if(keyCode == 13) //13 = enter key
  {
      //here is where you process the form item or call a function to do that
      searchEntries(); //call search
  }
}

Third, you need to assign the function above to to be an event handler:

//assign an event handler to the search box so we can have it
//submit when user presses enter
document.getElementById('txtsearchentries').onkeyup = submitSearchOnEnter;

That’s it. Should be able to assign it similarly to other fields on the page too, but then you would need to think of how to create separate functions to handle each.

Objects in Javascript

Thursday, April 10th, 2008

Javascript does not use a standard class model. It uses objects that are like associative array structures of data, or so I have read. Regardless of how it works, you can make a class-ish type construct in Javascript.

I’ll try to go over the basics here to help anyone who is interested.

Objects are defined by creating a new function. Inside the function you can define variables and methods that are attached to the primary function. The primary function is really like the constructor for the object as well.

For example:

function ObjectExample(constructorParameter1, constructorParameter2)
{
    //define a variable and assign a constructor value to it
    this.variable1 = constructorParameter1;
    this.variable2 = constructorParameter2;

    //you can also define variables with var, but they act differently
    var variable3 = this; //assigns an instance pointer to a "constructor" variable

    //defines a function that is attached to the object
    //this function has one parameter
    //pretend that this.variable1 is a reference to a div element
    this.statusIndicator = function(statusText)
    {
        //make sure an element reference was returned before trying to set properties
        if(this.variable1 != null)
        {
            document.getElementById(this.variable1).innerHTML = statusText;
        }
    }

    //you can also have a function with zero parameters
    this.aBoringFunction = function()
    {
        alert('YO!');
    }

    //you can call an instance function from inside the "constructor" (aka. primary function)
   this.aBoringFunction(); //every time an instance is created we will get a pop-up
}

To use the object we just defined we would do something like this:

//create a new instance
var newObjectInstance = ObjectExample('7', divReference);

//execute a object function
newObjectInstance.statusIndicator('Hello...');

That’s about it, let me know if I missed something, or there was an error. I typed the code out rather then copying something I know works for readability reasons.

Javascript Rant

Thursday, April 10th, 2008

I’ve been working on something recently where I decided to have most of the program run in a client’s browser. It’s basically a blog system that works with that asp- xml-to-access-db class I released on here as an LGPL piece of code. The clients browser sends/requests information in XML to the server script and everything turned out peachy. I’m overall extremely happy with it.

Now that I’m done writing the script. I learned quite a bit more about Javascript that I didn’t know in the past. The initial few days of working with it were tragic. I’m not too fond of Javascript’s “object” model and lack of a standard class model. While javascript works and provides a good deal of functionality, it feels “dirty.” Maybe my fellow “old school” programmers can understand.

Besides the object model, the DOM in general is a pain to work with, and hard to find information about (that works in multiple browsers). Inconsistencies, things that logically should work don’t, and, trying ~5 different suggested methods to do something, but finding out that only 1/ 5 seems to actually work.

If you don’t agree with me, have you ever tried encapsulating XMLHttpRequest in a “class” object? There are a few gotchas that I stumbled on, which I hope to talk about in the future.

My tip of the day about Javascript: Objects are functions are objects can be variables with no data hiding what-so-ever…

Accessing page content from the front and back-end of a site

Friday, February 2nd, 2007

As I’m programming this database driven website, I’ve come into a few irritating little issues. Today I’ll talk about a few methods to access page content (images) from the back-end.

I’ve created a way to create and edit page content with a browser based WYSIWYG editor. The problem is after the first time the data is submitted to the server, all images are set with a path that now only works from the root directory of the website. So when a user tries to edit some page content with images in the WYSIWYG editor they see broken images (aka. “The dreaded Red X”).

I thought of a few ways to fix the problem. I’ll also mention which method I actually used in the end.

1. Have the PHP script handle the path conversions. This would mean two functions or so with a few replacements using regular expressions. So when the fetched data is sent to the user all of the html image tags are modified. When or if the user sends the data back they are remodified (excluding any new images the user is submitting). This is probably the safest bet.

2. Create a synaptic link if the server is on Linux/Unix. For example if the site root is www/, the site editor is in www/editor, and the content is in www/images. You would create the synaptic link in the www/editor directory linking to www/images directory. Probably the easiest solution by far, but I want my site to work on both Windows and Linux/Unix servers if possible. I’m developing the site on Windows, so I did not try this, but I’m pretty sure it would work. I also know that windows has a way to create similar links, but it seems like a pain to use so I didn’t bother.

3. Use JavaScript to handle the temporary conversion. This is the route I picked. I was just looking for something quick that worked and this was it. Well it wasn’t exactly quick because I spent a few minutes researching what function I needed to use and exactly how it works. The tutorials I saw were lacking…

Here is an example of the code that will do the initial edit, so the user can see the images in the WYSIWYG editor:

function fixImagePaths(textAreaId)
{
  var tempHtmlData = document.getElementById(textAreaId).value;
  tempHtmlData = tempHtmlData.replace(/(<img\s.*src=")(images\/[^"]*"\s.*>)/gi, '$1/../$2');
  document.getElementById(textAreaId).value = tempHtmlData;
}

The KEY problem that took me a few minutes to figure out was that the first parameter (the regular expression) in the replace function can’t have any type of quotes around it. If you’ve never heard of regular expressions, I highly suggest that you read up on them. They are extremely useful in a multitude of applications. Anyways, what that function does is take data from a wysiwyg html textarea and search through the whole thing for img tags. When it finds one that has a src directory that starts with “images/” it replaces it with “/../images”, this gets the browser to jump back a directory to find the right path to the image folder.

I have this function execute on the body onload event. I’ll also have a second similar function execute on the form onsubmit event. This solution seemed a bit easer then the php one. Well that’s it for now!




The Way Of Coding



 
Scott J. Waldron Photography
Stock Photo Website
Tech Learning Site
Follow me on Twitter

Popular Article Tags

Archives

Pages