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.
[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.