Setting up your buttons
First let us setup some buttons:
The page will look like:
If you try clicking on these buttons, nothing will happen because we haven’t written any code to describe the actions to take upon a button click. First, let us assign id, name, and value attributes to each button. Here is how that would look:
The output will still be the same as before. Note that each button HTML element now has an id, a name, and a value. The value corresponds to the text on the button. The id and name are descriptive and unique names to each button.
Now let us write an “onclick” handler function for each button prescribing what each function should do. Here is how that code will look. For simplicity, we write the handler for only the first button:
If we click on the first button, we get:
Wow - what happened? If you use the document.write() method on an already loaded page (as is the case here) it will delete all existing HTML and proceed to render a fresh page. This is why all the previous elements, buttons, etc. are removed. If you would like to update the previous page we must do:
Note that we have created a new element, a H2 element, and given it an id of “message”. Inside the function f() we access this element using the getElementById method and then set its innerHTML value to “Humpty”. Now when we clicked on the Humpty button, we get:
Note that the script does not load a new page but instead updates an element on the current page.
We can expand the script to add the additional functions:
Now when we click the buttons one by one, the messages are overwritten because the same element is overwritten, eg:
Simplifying our code
The above type of code can get unwieldy. Here is a simple way to standardize this with just one function for all buttons. We invoke the function with an argument that is the value of the current button. This value is then accessed inside the function for printing purposes.
The functionality of the page is the same as before. When the third button is clicked, we get:
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.