Docsity

JavaScript Function to Generate Permutations and Transfer Focus, Exercises of Web Programming and Technologies

Toggle sidebar
bg1
characters, there’s no error (yet). We’ll see how to check if it’s an integer in a
moment.
The next file (permutation4.html) uses the function VerifyIntInRange,
found in the external file verify.js in the same directory. You can view that
file just by typing its name into the browser navigation bar. As you can see
from the function call, this takes three inputs, a variable that is a text box (or
textarea), and a lower and upper bound. Looking at the source code, you can
see that this is first parsed as a floating point number (using the parseFloat
command, and then we check if it’s an integer (with the second part of the
ā€œifā€ conditional test) and is in the specified range. If not, an error message is
displayed and the text box is cleared.
The next file (permutation5.html) includes the Permutation function to
generate the permutation, given an integer. The idea behind this function is
that you start with the list of numbers 1,2, . . . , n (in that order) and, for a large
number of times, pick a position and swap the two numbers in adjacent posi-
tions. For example, you might start with 1,2,3,4,5 and perform the following
(pseudo)random choices that will swap elements:
1 2 3 4 5 (starting configuration)
1 3 2 4 5 swap numbers at positions 2 and 3
1 3 4 2 5 swap numbers at positions 3 and 4
3 1 4 2 5 swap positions 1 and 2
3 1 2 4 5 swap positions 3 and 4
3 1 2 5 4 swap positions 4 and 5
3 1 5 2 4 positions 3 and 4
3 1 5 4 2 positions 4 and 5
.
.
..
.
.
Hopefully, you might be convinced that doing this transposition operation
a large number of times will lead to a (nearly) random permutation. Showing
this is the case is a mathematical task, as well as figuring out what exactly is
meant by the word ā€œlargeā€. (But I won’t talk about that here.) Simply use
this function as shown, namely pass it an integer, and you will receive back a
string that contains the permutation. In this case the permutation is simply
inserted into the alert box output. Note that checking that the input value is
an integer assures that the argument passed to the Permutation function is a
valid argument (so that function need not do any checking itself).
The next page (permutation6.html) changes from the previous one in the
display of the output. How do we do this? It’s similar to retrieving the input
value. We use the getElementById function to locate the textarea element, and
then assign its value property using the string returned from Permutation.
Vo“ıla! Dynamic insertion of text into an existing element of a webpage!
Okay, so now you have a fully working page that ā€œdoes exactly what it says
on the tinā€. But I’m lazy (as those who know me well can attest to). And
the page doesn’t fully behave how I’d like it to behave. Namely, I’d like to
insert a number in the input area, press the ā€œEnterā€ key, and have it give me
a permutation back. I don’t want to have to reach for the mouse and click the
2
docsity.com
pf3
pf4

Partial preview of the text

Download JavaScript Function to Generate Permutations and Transfer Focus and more Exercises Web Programming and Technologies in PDF only on Docsity!

characters, there’s no error (yet). We’ll see how to check if it’s an integer in a moment. The next file (permutation4.html) uses the function VerifyIntInRange, found in the external file verify.js in the same directory. You can view that file just by typing its name into the browser navigation bar. As you can see from the function call, this takes three inputs, a variable that is a text box (or textarea), and a lower and upper bound. Looking at the source code, you can see that this is first parsed as a floating point number (using the parseFloat command, and then we check if it’s an integer (with the second part of the ā€œifā€ conditional test) and is in the specified range. If not, an error message is displayed and the text box is cleared. The next file (permutation5.html) includes the Permutation function to generate the permutation, given an integer. The idea behind this function is that you start with the list of numbers 1, 2 ,... , n (in that order) and, for a large number of times, pick a position and swap the two numbers in adjacent posi- tions. For example, you might start with 1, 2 , 3 , 4 , 5 and perform the following (pseudo)random choices that will swap elements:

1 2 3 4 5 (starting configuration) 1 3 2 4 5 swap numbers at positions 2 and 3 1 3 4 2 5 swap numbers at positions 3 and 4 3 1 4 2 5 swap positions 1 and 2 3 1 2 4 5 swap positions 3 and 4 3 1 2 5 4 swap positions 4 and 5 3 1 5 2 4 positions 3 and 4 3 1 5 4 2 positions 4 and 5 .. .

Hopefully, you might be convinced that doing this transposition operation a large number of times will lead to a (nearly) random permutation. Showing this is the case is a mathematical task, as well as figuring out what exactly is meant by the word ā€œlargeā€. (But I won’t talk about that here.) Simply use this function as shown, namely pass it an integer, and you will receive back a string that contains the permutation. In this case the permutation is simply inserted into the alert box output. Note that checking that the input value is an integer assures that the argument passed to the Permutation function is a valid argument (so that function need not do any checking itself). The next page (permutation6.html) changes from the previous one in the display of the output. How do we do this? It’s similar to retrieving the input value. We use the getElementById function to locate the textarea element, and then assign its value property using the string returned from Permutation. Vo“ıla! Dynamic insertion of text into an existing element of a webpage! Okay, so now you have a fully working page that ā€œdoes exactly what it says on the tinā€. But I’m lazy (as those who know me well can attest to). And the page doesn’t fully behave how I’d like it to behave. Namely, I’d like to insert a number in the input area, press the ā€œEnterā€ key, and have it give me a permutation back. I don’t want to have to reach for the mouse and click the

button if I don’t want to do so. How can I do this? Well, you can check for keyboard events, and if the user presses the ā€œEnterā€ key you can proceed as before (get the input value, check that it’s an integer, and, if so, generate a permutation, and output it to the screen). Before I do this, however, I’m going to put the code for getting the input value, generating the permutation, and inserting it into the output into a sep- arate function. Why? Because now I’m going to be using this in two different places, so there’s no need to repeat the code. After all, this one of the reasons that functional-based programming was developed. So in permutation7.html, the only thing that has changed from the previous version is that I have created a new JavaScript function called ā€œProcess()ā€ that will handle the whole proce- dure. Then I call this function when the user presses the button. As I said, one reason that I do this is so that I can call the same procedure when someone now presses the ā€œEnterā€ key. Then, now that I’ve packaged this into a function, how can I add the func- tionality that I’ve described above, namely when a user hits the ā€œEnterā€ key, the new permutation is generated? To do this, we define an event handler to look for keyboard events. Note that this event handler needs to be assigned to the text input element, as that’s what will trigger the (important and relevant) keyboard events that we want to capture. See the file permutation8.html for the implementation. The user-defined function CheckForEnter does the job. This takes two inputs, the relevant element in which the events occur, and the event itself. The ā€œthisā€ keyword refers to the ā€œinputā€ element itself in this case (the JavaScript way of performing a self-reference to an object while ā€œinsideā€ that object). The variable ā€œeventā€ is the (reserved) JavaScript object variable that is set when an event occurs (any sort of event, like moving or clicking the mouse, or hitting a key). We can capture keyboard events using any of three event handlers, namely onkeydown, onkeyup, or onkeypress. I chose to use the onkeyup event handler (partly because Internet Explorer handles the onkeypress events slightly differently from other browsers and I want this to work in all browsers, or so I hope). When an onkeyup event is triggered, a property called keyCode is set in the event that indicates which key was pressed (stored as a number in the ASCII standard). The relevant key we want, the ā€œEnterā€ key, has value 13. So what we do is relatively straightforward, that is we check the keyCode property (of the ā€œeventā€ object) to see if it’s the ā€œEnterā€ key and return true or false as appropriate. Then, if true, we start up the sequence of events as before (exactly as if the button had been clicked). See permutation8.html for this version. So I’m happier now since my laziness is (somewhat) satisfied. But what happens if I do choose to use the mouse to click the button? If I then want to insert a different value, I have to either use the mouse to select the input box or use the ā€œTabā€ key to move all the way around the webpage to get to the input box again. My laziness again rebels against this. How can I alter this behavior of the page? Here’s where I use a function to change the ā€œfocusā€. What is this? For such a page like this where there’s input boxes and buttons (and similar pages containing checkboxes, radio buttons, and the like), one element is said to

browser and it appears to work correctly. You might also notice that the colored background box appears differently in Firefox and Internet Explorer. (Chrome shows it similarly to Firefox.) I believe this might stem from how Internet Ex- plorer implemented the so-called W3C ā€œbox modelā€ in its Cascading Style Sheet implementation differently than the other browsers. I haven’t fully explored this issue, nor considered/found ways to correct that. This is as far as I’ve taken this page. You might have other ideas. If you don’t want to start with a default value in the text input box, you can simply change the value property of the element to be an empty string (or some other value if you wanted it). As you can see, you can add as much, or as little, as you want to such a page. Part of what you want to consider is what will the user(s) want, what will be useful to them, or just extraneous.

P.S. In terms of JavaScript programming, sometimes ā€œdebuggingā€ your pro- grams might be more difficult than if you’re programming in Java or C. If you use Firefox, then (depending upon the version of Firefox) there is an exten- sion that can be installed called FireBug, that can prove useful in debugging JavaScript code. There’s also a JavaScript error console that can give some error messages (or warnings). Select the ā€œError Consoleā€ under the ā€œToolsā€ menu. Internet Explorer (and possibly other browsers) have some tools for debug- ging JavaScript, but I am less familiar with them. It is worthwhile checking for such utilities and tools to help debug JavaScript code if you intend to write large and complex scripts. My general advice is to proceed somewhat slowly with your coding, and test your programs incrementally, i.e. often so that you can detect and correct errors as they occur instead of having a large mess of code that might have multiple errors that can be hard to fix.