December 30, 2011

Writing Javascript into a WordPress Page or Post

Recently I was interested in writing some Javascript into a WordPress Page, and came across several differing ways to do this. The one that seemed the easiest to understand was one that was analogous to writing Javascript in a regular static page, and used shortcode to insert the Javascript. So here is an example of how to write Javascript into a WordPress Page ( or post ) using the shortcode method. The following form was inserted in HTML mode, and the shortcode is inserted after it. In this case the javascript is event driven, and loops through the form collecting all the data from all the radio buttons, and setting the results in the bottom of the form. I am using ShortCode Manager plugin.
Remember to insert the shortcode after the form, so that all the DOM elements have been identified by the time the JavasScript is ready to load.
The form has each radio element the group  with a call to the JavaScript with <input onclick="loopForm( )" to run the script.


Level of Difficulty (0 being easy,4 being very hard)01234
Tying a Knot
Programming in JS
Memorizing TS Eliot Ash Wednesday

[sb name="js"]


The form is identified with form id="quizform" and contains only radio buttons, and the JavaScript short code contains the code:

var radioResults = 0;
var totalscore = document.getElementById("totalscore");

function loopForm() {
var form = document.getElementById("quizform");
radioResults = 0;
for (var i = 0; i < form.elements.length; i++ ) {

if (form.elements[i].type == 'radio') {
if (form.elements[i].checked == true) {
//alert ("form.elements[i]: [" + i + "] was " + form.elements[i].value );
radioResults += parseInt( form.elements[i].value ) ;
}
}
}

totalscore.value = radioResults;

}

When using shortcode make sure that you have inserted the opening and closing script tags in the shortcode itself, which is not shown here.

Latest posts by Edward Rosenthal (see all)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

HSS - specializing  in Law, Art, Author, Professional and Non Profit Websites - We'd love to help you -  Building websites since 2001
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram