Search code examples
javascriptjquerycode-organization

Is it impossible to separate javascript from HTML?


To be specific, I'm talking about avoiding this type of code:

<input type='text' id='title_33' class='title'
  onfocus='updateCharsLeft(33);' 
  onkeypress='updateCharsLeft(33);' />

Here I would like to put the onfocus and onkeypress event handles separately, i.e in a .js file. Like this:

$(document).ready(function()
  {
    $(".title").focus(updateCharsLeft);
    $(".title").keypress(updateCharsLeft);
);

However here the problem is that the ID of the textbox needs to be passed onto the function updateCharsLeft(). It would suck to have to extract out the id from the ID of the textbox in that function, so it would actually be cleaner to just put in the event handlers within the HTML code.

Thoughts?


Solution

  • I've had to do something similar before and also wasn't happy with parsing the value out the ID attribute. The best thing I can suggest is that you use another attribute for the value you need, like the rel attribute:

    <input type='text' id='title_33' class='title' rel='33' />
    

    Or depending on how religious you are about validation, just use a custom attribute:

    <input type='text' id='title_33' class='title' myval='33' />