Manipulating HTML elements with Javascript

In this tutorial, Javascript is used to update the contents of elements on a page according to user inputs. A HTML page contains buttons for three random Korean characters, a copyright symbol and a square root sybmol and a text area for textual input. When a button is pressed, the character’s unicode is passed to the script, which converts it and appends it to the text area. The script also updates displays the contents of the text area on the same page.

The sources for this tutorial are available here. The HTML page is set up with the following code:

<html>
    <head>
        <title>Unicode</title>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <script type="text/javascript" src="unicode.js"></script>
    </head>

    <body>
        <div name="mirror"></div><br />
        <button onclick="appendCharacter(44035)">&#44034;</button>
        <button onclick="appendCharacter(55202)">&#55202;</button>
        <button onclick="appendCharacter(44041)">&#44041;</button>
        <button onclick="appendCharacter(169)">&#169;</button>
        <button onclick="appendCharacter(8730)">&#8730;</button>
        <br />
        <textarea rows="5" cols="25" type="text" name="input" onkeyup="keyboardUsed()" ></textarea><br />
    </body>
</html>

A number of HTML elements allow Javascript to be executed when certain events occur. In the above code, the onclick attribute is specified for the buttons so that the appendCharacter subroutine (defined in the javascript file unicode.jsis executed when they are clicked. The numeric argument is the character’s unicode. Later, the text box is configured to execute the keyboardUsed subroutine by specifying the onkeyup attribute. In case you are wondering, there are other events that may be specified. If you also want to know which other events may be specified, check out the HTML reference at w3schools.com. With this information, you should be able to change the buttons to suit your needs.

The Javascript is defined in an external file called unicode.js. The appendCharacter subroutine needs to obtain the contents currently in text area and append the character. Since these are not standard English characters, the buttons are set to provide the unicode of the characters. If you are not familar with unicode, I recommend having a look at this page. To get back the charater represented by a particular unicode, I use the String object’s fromCharCode function.

function appendCharacter(code) 
{   
    var inputField = document.getElementsByName('input')[0];
    var newValue = inputField.value + String.fromCharCode(code);
    inputField.value = newValue;
    updateMirror(newValue);
}

The updateMirror subroutine will convert the contents of the resulting contents into encoded string for display on an HTML page.

The definition for keyboardUsed which is called when the user directly changes the contents of the text area, is more simple:

function keyboardUsed() 
{
    var inputField = document.getElementsByName('input')[0];
    updateMirror(inputField.value);
}

As mentioned earlier, updateMirror is called on to update mirror division at the top of the page. Since I want the page to handle the non-English characters from the buttons or that may be entered directly by the user, I encode the contents into the numeric character reference for HTML before displaying it at the top of the page.

function updateMirror(content) 
{
    var contentDiv = document.getElementsByName('mirror')[0];
    contentDiv.innerHTML = stringToUnicode(content);
}

Lastly, the function stringToUnicode converts an entire string into unicode and makes it suitable for display on an HTML page. A String object has the charCodeAt function that provides the numeric reference of the string. In HTML a unicode character is represented in the form &#x;, where x is the character’s numeric reference. The charCodeAt needs to know the location of the character in the string, so we will need to loop over the entire string.

function stringToUnicode(subject)
{
    var converted = "";
    var position = 0;
    
    for (position = 0; position < subject.length; position++)
    {
        converted = converted.concat("&#", subject.charCodeAt(position), ";");
    }
    return converted;
}
Advertisements

14 Responses to Manipulating HTML elements with Javascript

  1. kahgoh says:

    In reply to the following comment:

    sumeet inani
    So I added the buttons for all unicode characters I also added

    button { 
       font-size: 18pt;
    }

    in head section to get big buttons.
    I wanted to ask
    (1)How can we Provide for backspace
    (2)the button we press not only updates text field (desirable) but also writes the character at beginning of page.
    i am using firefox 3.5.2 in windows vista.

    On the backspace
    I’m not really sure what you mean. I am using a text area, so the backspace is handled by the text area. In other words, the user selects the section to delete in the text area and presses the delete key. Or did you mean something else?

    On the button
    On the second point, if you downloaded and tried the examples from the tutorial, you should notice the page already has this behaviour. Clicking

  2. sumeet inani says:

    As html page is click interface.
    One way to delete previously typed character is press backspace or delete in text box
    while other i think is if we can add script to delete last entered unicode character and associate it with button.
    The other thing is whatever I click gets printed in text box as well as at beginning of page .
    I had added in style tag in head section to get big buttons but style opening and closing tag disappeared in post.

    • kahgoh says:

      Hi,

      Adding a delete button is simply a matter of adding a button and adding another Javascript function to remove the last character from the text box. I’d imagine that the delete function will look similar appendCharacter, except it would not need a parameter and that it would be removing the last character instead. If you look at my listing for the function, that means line 4 should be changed to remove the last character, or at least extract the every up until the last character. A string object in Javascript has the substr and substring functions. The length of the string is stored in the string’s length property. With this information, you should be able to figure out how to modify a copy of appendCharacter to remove the last character.

      As for the printing at the beginning of the page, as I’ve already mentioned the updateMirror updates a division named mirror on the HTML page. I guess you tried to add the CSS style sheet information that you mentioned in your original post, implying you’ve tried making changes to the source HTML file and now it doesn’t print it out the contents at the top of the page? I’ve tried retesting the code in this tutorial and it was working for me. I was also able to add the CSS style code to my HTML and still managed to get it working. Without looking at your changes, I can only guess there is a HTML error in your changes. Since you are using Firefox, I suggest opening Tools -> Error Console and testing your page again. The console may reveal a hint as to what is causing the problem.

  3. sumeet inani says:

    I copied the first 18 lines & saved them as kah.html
    Then created unicode.js with 7+5+5+11 lines.

    what I want is that text should be in textarea but not at beginning of page.I think you are updating element named mirror so initially it is empty but as we click it appears in text area as well as mirror.How can I get letters just in text area or in div tag only one of them?
    Do you mean to delete a unicode chracter we can just lower subject.length by 1 so that last character is not included ?

    • kahgoh says:

      How can I get letters just in text area or in div tag only one of them?

      You can remove the repetition at the top by removing the <div> tag. As I have said before updateMirror updates the contents of the division, so you will have remove calls to the subroutine in the Javascript too. If you wanted to, you could remove the text box instead, but this would require a few extra changes. Removing the text box also means users would not be able to simply type in, so I would remove the repetition at the top instead.

      Do you mean to delete a unicode chracter we can just lower subject.length by 1 so that last character is not included?

      Yep, that is the first method I though of.

  4. sumeet inani says:

    i learnt that document.getElementsByName(name) gives a list of elements with ‘name’ .I think [0] means first from that array(if there are multiple with same name).

    I did a few things
    removed the textarea element from html & changed occurence of ‘input’ in unicode.js to ‘mirror.’
    Also removed function keyboardused from .js
    Now whichever key I press it gets appended at top
    but one little thing
    first keypress results in undefined then keypress is okay.
    I tried to implement backspace button by decreasing subject.length by 1 but no effect.

    • kahgoh says:

      Hi,

      i learnt that document.getElementsByName(name) gives a list of elements with ‘name’ .I think [0] means first from that array(if there are multiple with same name).

      Yep, that is right.

      first keypress results in undefined then keypress is okay.
      I tried to implement backspace button by decreasing subject.length by 1 but no effect.

      Are you sure you want to remove the text area? I would have selected to remove the repetition along the top instead, as I think most people are used to being able to type in the characters instead of having to click on a “virtual keyboard”. Anyway, if you do have good reason to remove the text area instead, I said before a few more additional changes are actually required.

      From the sounds of things, I think you got the first one – replacing the string input to mirror to get the contents in the division at the top. The second required change is to update the line below it. Since you are now getting the value from a division instead of a text input, you need to change inputField.value to inputField.innerHTML on line 4 of the originally listing.

      Lastly, you need to change it so that the character being appended is encoded properly on the same line. In other words, on line 4, you’ll need to replace String.fromCharCode(code) with something like "&#" + subject.charCodeAt(position) + ";". This will encode and append the character as it is being entered, so you will also need to remove the call to encode the contents in updateMirror. In other words, in updateMirror, at line 4 of the original listing change stringToUnicode(content) to just content.

  5. sumeet inani says:

    You are right nobody would like his buttons to move down when a line has been clicked.

    I simply made unicode.js as

    function appendCharacter(code)
    {
        var inputField = document.getElementsByName('input')[0];
        var newValue = inputField.value + String.fromCharCode(code);
         inputField.value = newValue;
    }
    

    It works great.Thanks to you.

    I tried to implement backspace using function

    function deletechar(code)
    {	
        var inputField = document.getElementsByName('input')[0];
        inputField.value.length--;
    }
    

    here I don’t know definition of declaration for null input function so 0 is passed on button click which is not used.
    This function did not yield fruit(backspace effect in this case)
    I am sorry for bothering you so much.

    • kahgoh says:

      Hi,

      Notice that your delete function does not use the code argument. This means that you can just remove the argument from the function. So change the first line from deletechar(code) to deletechar(). In your HTML code, remove any arguments that you pass to it.

      Secondly, on line 4, I don’t think you can simply decrement the length of the string in Javascript. Instead, replace the contents stored in the field with the entire string, minus the last character. I was actually thinking of using either the substr or the substring functions, something like this:

      inputField.value = inputField.value.substr(0, inputField.value.length - 1);
      

      Beware though, that the user might click on your delete button at anytime, even when there is no input, so you should check that the length is greater than 0 when you do this operation.

  6. sumeet inani says:

    Also I had initially thought of adding frame & updating it every second.That would have been lot of trouble for disk I realized.Thanks for guiding in right direction.

    Now just one thing remains that is a button which when clicked deletes last entered character.

  7. sumeet inani says:

    Will it be

    if ( inputField.value.length &gt; 0)
        inputField.value = inputField.value.substr(0, inputField.value.length - 1);
    

    Also is there some rule in javascript about leaving space before & after assignment operator.
    I know c language.How is it different from java ?

    • kahgoh says:

      Yep it should be something like that. I have noticed that you referred to Java, but Java and Javascript are two different things. There are also many differences between C, Java and Javascript that it would be a really long post if I listed them all. There is also already plenty of information about each of them on the internet. I think the Wikipedia entries on C, Java and JavaScript are good starting points if you really want to know about them and you are bound to even more information through Google.

  8. sumeet inani says:

    I will read tutorial on http://www.w3schools.com about javascript to get better understanding so that i can upgrade my html page to insert & delete characters from any position in textbox.
    Thank You for your assistance.
    In india we say धन्यवाद

  9. Pingback: Fix Unicode.js Errors - Windows XP, Vista, 7 & 8

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: