Call a JavaScript function from a Wordpress page? - javascript

I've added the following function to my wordpress theme javascript file wp-content/themes/xxx/js/script.js
function calculateBmi() {
var weight = document.bmiForm.weight.value
var height = document.bmiForm.height.value
if (weight > 0 && height > 0) {
var finalBmi = weight/(height/100*height/100)
document.bmiForm.bmi.value = finalBmi
if (finalBmi < 18.5) {
document.bmiForm.meaning.value = "That you are too thin."
}
if (finalBmi > 18.5 && finalBmi < 25) {
document.bmiForm.meaning.value = "That you are healthy."
}
if (finalBmi > 25) {
document.bmiForm.meaning.value = "That you have overweight."
}
}
else{
alert("Please Fill in everything correctly")
}
}
I have added the following code on a wordpress page (in admin) with a form that calls the function when you press the button
<form name="bmiForm">
Your Weight(kg): <input type="text" name="weight" size="10"><br />
Your Height(cm): <input type="text" name="height" size="10"><br />
<input type="button" value="Calculate BMI" onClick="calculateBmi()"><br />
Your BMI: <input type="text" name="bmi" size="10"><br />
This Means: <input type="text" name="meaning" size="25"><br />
<input type="reset" value="Reset" />
</form>
Nothing happens when I click the button and chrome console gives the following message.
Uncaught ReferenceError: calculateBmi is not defined ?page_id=1368:126
onclick
What is it that is wrong?

It's just a matter of enqueuing properly. First, a test page with the HTML provided. Note the use of the global $b5f_hook to catch our page afterwards.
add_action( 'admin_menu', 'add_auxiliary_menu' );
function add_auxiliary_menu()
{
global $b5f_hook;
$b5f_hook = add_menu_page(
'Test',
'<span style="color:#e57300;">Test</span>',
'edit_pages',
'b5f_page_id',
'b5f_page_callback',
'', // icon default for empty
1 // create before Dashboard menu item
);
}
function b5f_page_callback()
{
?>
<form name="bmiForm">
Your Weight(kg): <input type="text" name="weight" size="10"><br />
Your Height(cm): <input type="text" name="height" size="10"><br />
<input type="button" value="Calculate BMI" onClick="calculateBmi()"><br />
Your BMI: <input type="text" name="bmi" size="10"><br />
This Means: <input type="text" name="meaning" size="25"><br />
<input type="reset" value="Reset" />
</form>
<?php
}
Enqueuing the script, not sure why jQuery is being included as dependency, but it doesn't matter:
add_action( 'admin_enqueue_scripts', 'b5f_enqueue' );
function b5f_enqueue( $hook )
{
global $b5f_hook;
if( $hook !== $b5f_hook ) # Not our page, bail out
return;
$jscriptURL = get_stylesheet_directory_uri() . '/js/script.js';
wp_enqueue_script( 'custom_script', $jscriptURL, array('jquery'), '1.0', true );
}
And the script file contains the JS code provided:
function calculateBmi() { /* rest of the code */ }

your function is not defined because it contains syntax errors.
Add ";" after each line and check for other errors e.g. using jslint tool

Related

How to make sure if everything is valid before submitting?

I have a HTML5 form and I'm using javascript to validate the form.
I have several 'if's checking the form and if it valid they change a variable ('pass') to true or false. They also display an error message. The problem is that even if just one thing is valid it changes the variable is true and I need it to only make pass true if everything else is valid.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<div>
<form name="register" action="register.php" method="POST" >
<label>First Name:</label>
<input type="text" id="firstName" name="firstName"><br />
<label id="warning_first"></label>
<br />
<label>Surname:</label>
<input type="text" id="lastName" name="lastName"><br />
<label id="warning_second"></label>
<br />
<label>Gender:</label>
<input type="radio" name="gender" value="Male" id="male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Other">Other
<input type="radio" name="gender" value="Prefer not to say"> Prefer not to say <br />
<label id="warning_third"></label>
<br />
<label>Email:</label>
<input type="email" id="email" name="email"> <br />
<label id="warning_fourth"></label>
<br />
<label>Confirm Email:</label>
<input type="email" id="confirmEmail" name="confirmEmail">
<br />
<label>Mobile:</label>
<input type="tel" id="mobileNumber" name="mobileNumber">
<br />
<label>Telephone:</label>
<input type="tel" id="telephoneNumber" name="telephoneNumber">
<br />
<input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();">
<input type="button" name="submit" value="Register" onclick="submitCheck();">
</form>
<script src="script.js"></script>
</div>
</body>
</html>
My JavaScript:
function submitCheck() {
var pass = false;
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var genderTest = document.getElementsByName("gender");
var genderIf = false;
for (var a = 0; a < genderTest.length; a += 1) {
if (genderTest[a].checked) {
genderIf = true;
}
}
var emailCheck = document.getElementById("email").value;
if (firstName.length > 0) {
document.getElementById("warning_first").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_first").innerHTML = "This is required!";
pass = false;
}
if (lastName.length > 0) {
document.getElementById("warning_second").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_second").innerHTML = "This is required!";
pass = false;
}
if (genderIf) {
document.getElementById("warning_third").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_third").innerHTML = "This is required!"
pass = false;
}
if (emailCheck.length > 0) {
document.getElementById("warning_fourth").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_fourth").innerHTML = "Your email is too short!";
pass = false;
}
if (pass) {
console.log("OK");
} else {
console.log("NO");
}
}
As you can see, if the email is true, the console will log "OK" (which I am using to see if everything is valid"). How can I solve this so that it doesn't 'pass' to true if just the email is valid?
I am using a normal button instead of a submit button because of issues with the #onsubmit.
At the moment, you default pass to false and change it to true if any element passes the test.
Reverse your logic.
Set the default value of pass to true. Change it to false if any element fails its test.
Its simple, at the start of your code change your pass variable to have a value of 1 like so:
var pass = 1;
Now change the line of code in your IF statements where you have your pass variable. For a true condition set to this:
pass *= 1;
And for a false condition to this
pass *= 0;
This ensures that unless all IF conditions are satisfied your pass variable will not return a true state.

CodeIgniter - Cannot validate form in view to javascript file

I have file .js in this link: C:\xampp\htdocs\ab-group\assets\js\default.js
I've made a form and I wanna validate it. I also already linked the js file in HTML head but it doesn't work.
I use a same way in calling css file and it succeeded, but why I can't call js file?
here my view code:
<head>
<title>Welcome to AB Group</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link href="<?php echo base_url('assets/css/default.css')?>"
rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="<?php echo base_url(). "assets/js/default.js" ?>"></script>
</head>
<body>
<div class="form-style-3">
<form id="form_sendEmail" name="form_sendEmail" method="post" onsubmit="validate();">
<fieldset><legend>Personal</legend>
<label for="field1"><span>Name <span class="required">*</span></span><input type="text" class="input-field" name="name" id="name" value="" /></label>
<label for="field2"><span>Email <span class="required">*</span></span><input type="email" class="input-field" name="email" id="email" value="" /></label>
<label for="field3"><span>Phone <span class="required">*</span></span><input type="text" class="input-field" name="phone" id="phone" value="" /></label>
<label for="field4"><span>Subject</span><select name="field4" class="select-field">
<option value="Information">Information</option>
<option value="Complain">Complain</option>
<option value="Other">Other</option>
</select></label>
<label for="field5"><span>Shipment Code <span class="optional"></span></span><input type="text" class="input-field" name="field5" value="" /></label>
</fieldset>
<fieldset><legend>Message</legend>
<label for="field6"><span>Message <span class="required">*</span></span><textarea name="message" id="message" class="textarea-field"></textarea></label>
<label><span> </span><input type="submit" onclick="validate()" id="sendEmail" value="Send Email" /></label>
<span class="required">* Indicates Required Field</span>
</fieldset>
</form>
</div>
</body>
and here my js file:
$(document).submit(function () {
function validate()
{
var emailID = document.form_sendEmail.Email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if( document.form_sendEmail.Name.value == "" )
{
alert( "Please provide your name!" );
document.form_sendEmail.Name.focus() ;
return false;
}
if( document.form_sendEmail.Email.value == "" )
{
alert( "Please provide your Email!" );
document.form_sendEmail.Email.focus() ;
return false;
}else if(atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.form_sendEmail.EMail.focus() ;
return false;
}
if( document.form_sendEmail.Phone.value == "" )
{
alert( "Please provide your phone number!" );
document.form_sendEmail.Phone.focus() ;
return false;
}
if( document.form_sendEmail.Message.value == "" )
{
alert( "Please write your message!" );
document.form_sendEmail.Message.focus() ;
return false;
}else{
return( true );
}
}
});
I hope js file could validate the form is empty or not and validate email as well. Please help to find a mistake in my code. Thank you very much.
Problem might be at linking js file. So try this.
<script src="<?php echo base_url(); ?> assets/js/default.js"></script>
I change $(document).submit(function ()... to become $(document).ready(function()... and then (somehow) it works.

How to display a JavaScript result as a paragraph?

I have been working with a javascript that will calculate BMI of a person. But with the BMI result, I want to display specific comments of specific result group. How can I do that?
Here is the script:
<script>
<!--
function calculateBmi()
{
var weight = document.bmiForm.weight.value
var height = document.bmiForm.height.value
if(weight > 0 && height > 0)
{
var stadnardwight1 = 19*height/100*height/100
document.bmiForm.weight1.value = stadnardwight1
var stadnardwight2 = 25*height/100*height/100
document.bmiForm.weight2.value = stadnardwight2
var finalBmi = weight/(height/100*height/100)
document.bmiForm.bmi.value = finalBmi
if(finalBmi < 19)
{
document.bmiForm.meaning.value = "That you are too thin."
}
if(finalBmi > 19 && finalBmi < 25)
{
document.bmiForm.meaning.value = "That you are healthy."
}
if(finalBmi > 25)
{
document.bmiForm.meaning.value = "That you have overweight."
}
}
else
{
alert("Please Fill in everything correctly")
}
}
//-->
</script>
<form name="bmiForm">
Your Weight(kg): <input type="text" name="weight" size="10"><br />
Your Height(cm): <input type="text" name="height" size="10"><br />
<input type="button" value="Calculate BMI" onClick="calculateBmi()"><br />
Your BMI: <input type="text" name="bmi" size="10"><br />
This Means: <input type="text" name="meaning" size="25"><br />
Your weight should be between: <input type="text" name="weight1" size="10"> to <input type="text" name="weight2" size="10"> kg<br />
<input type="reset" value="Reset" />
</form>
Here, meaning value is displayed by a text input from. But how can I display it as a paragraph, not as a text input?
Thanks in advance for helping.
Note: The meaning will change according to the 3 different categories of results.
It would be very helpful if you please give an example of line of code for the solution.
Instead of using an 'input' tag for meaning, use a 'span' tag, and set the innerHtml of that span to the content you want.

Text Input To Sentence Case

I have a form whose is saved to the database and generates a PDF.
I want to have the input text transformed to sentence case. Tried style="text-transform:capitalize" but it still save the input as it was typed into the database. How can I do this, perhaps with JavaScript?
<form class="form-style-9" name="litterregistration" id="LitterReg" method="post">
<li>
<input type="text" name="AKennel" required class="field-style field-split align-left" placeholder="Kennel Name" style="text-transform:capitalize" />
<input type="text" name="BDamMother" required class="field-style field-split align-right" placeholder="Dame (Mother)" style="text-transform:capitalize"/>
</li>
<input type="submit" value="Save as PDF" onClick="Onsubmit1();" />
<input type="button" onclick="ClearFormFields()" value="Clear All Fields">
</form
<script>
function Onsubmit1()
{
document.litterregistration.action = "tcpdf/examples/form-litter-regis.php"
return true;
}
</script>
Please, note this is a NOT scalabe solution, and will only work with this specif code
Hi, a few notes first:
- you call a ClearFormFields() function but it isn't build anywhere;
- the name onSubmit1() for the function is not really good.
- You've missed a /> in the form tag.
With this is mind, this should do the (THIS) trick:
Javascript:
<script type="text/javascript">
function mySubmitAction(myAction) {
with (document.getElementById("LitterReg")) {
AKennel.value = AKennel.value.toUpperCase();
BDamMother.value = BDamMother.value.toUpperCase();
}
document.litterregistration.action = myAction;
return true;
}
</script>
HTML
<form class="form-style-9" name="litterregistration" id="LitterReg" method="post">
<li>
<input type="text" name="AKennel" required class="field-style field-split align-left" placeholder="Kennel Name" style="text-transform:capitalize" />
<input type="text" name="BDamMother" required class="field-style field-split align-right" placeholder="Dame (Mother)" style="text-transform:capitalize"/>
</li>
<input type="submit" value="Save as PDF" onclick="mySubmitAction('tcpdf/examples/form-litter-regis.php');" />
<input type="button" onclick="ClearFormFields()" value="Clear all fields" />
</form>
var $input1 = $( '#input-1' );
$.toSentenceCase = function ( value ) {
var val = value.split( ' ' );
for ( var i = 0, l = val.length; i < l; i++ ) {
val[i] = val[i].charAt(0).toUpperCase() + val[i].substr(1);
}
return val.join( ' ' );
}
$input1.on( 'blur', function ( e ) {
var $this = $( this );
$this.val( $.toSentenceCase( $this.val() ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input-1">
</form>

Reference Textarea W/ Input

I am looking to build a simple webpage that can check to see if a string contains certain information. I'm taking a summer course in Java and wanted to give Javascript a try. Maybe a bad idea?
I want the user to enter information - name, phone number, and a couple other options in a form. Then I want the user to enter more information in the text area. The text area will reference the input data and if there is a match it will alert the user.
I have limited javascript experience, but I've been able to manipulate user input with javascript in the past.
Not sure what my problem here is. Any tips (especially regarding style and logic) are greatly appreciated! PS - I'm using Bootstrap if that matters...
Thanks in advance :)
HTML
<div class="container">
<div class="col-md-6">
<form>
<input type="text" id="Name" placeholder="Name" style="width:100%"><br /><br />
<input type="text" id="Number" placeholder="Number" style="width:100%"><br /><br />
<input type="text" id="Next" placeholder="Something Else" style="width:100%"><br /><br />
<input type="text" id="WhatEver" placeholder="Something Else" style="width:100%"><br /><br />
</form>
</div>
<div class="col-md-6">
<textarea id="LongText" placeholder="Enter Info" style="width:100%; height:250px">
</textarea> <br />
<input type="submit" class="btn btn-danger" id="tSubmit" value="Submit" onclick="GetInput();Check();">
</div>
<div class="col-md-12">
<h1>Output</h1>
<div id="tOutPut" style="color:red;"></div>
</div>
</div>
JS
GetInput()
{
var tNameValue = document.getElementById("Name").value;
var tValue = document.getElementById("Number").value;
var tArray = document.getElementById('LongText').value.split('\n');
}
Check( tArray, tNameValue, tValue )
{
for(var i = 0; i < tArray.length; i++ )
{
if( i === tNameVaue )
{
document.getElementById( 'tOutPut' ).innerText = "Name Match" <br />;
}
if( i === tValue )
{
document.getElementById( 'tOutPut' ).innerText = "Match" <br />;
}
}
}
*
Your javascript has many things wrong. Here is the HTML and the Javascript. The logic must be improved but the code is working.
<div class="container">
<div class="col-md-6">
<form>
<input type="text" id="Name" placeholder="Name" style="width:100%"><br /><br />
<input type="text" id="Number" placeholder="Number" style="width:100%"><br /><br />
<input type="text" id="Next" placeholder="Something Else" style="width:100%"><br /><br />
<input type="text" id="WhatEver" placeholder="Something Else" style="width:100%"><br /><br />
</form>
</div>
<div class="col-md-6">
<textarea id="LongText" placeholder="Enter Info" style="width:100%; height:250px">
</textarea> <br />
<input type="submit" class="btn btn-danger" id="tSubmit" value="Submit" onclick="ExecuteAll();">
</div>
<div class="col-md-12">
<h1>Output</h1>
<div id="tOutPut" style="color:red;"></div>
</div>
</div>
And here is the Javascript:
var tNameValue;
var tValue;
var tArray;
function ExecuteAll()
{
GetInput();
Check();
}
function GetInput()
{
tNameValue = document.getElementById("Name").value;
tValue = document.getElementById("Number").value;
tArray = document.getElementById('LongText').value.split('\n');
}
function Check()
{
if (tArray != null) {
for(var i = 0; i < tArray.length; i++ )
{
if( i == tNameValue )
{
document.getElementById( 'tOutPut' ).innerText = "Name Match <br />";
}
if( i == tValue )
{
document.getElementById( 'tOutPut' ).innerText = "Match <br />";
}
}
}
}
I will tell you what I did to fix the bugs:
Added function keyword to the javascript functions.
Put the variables as global so they can be used for the whole code.
Verified whether tArray is not null.
Fixed variable names.
Here is the Fiddle code: http://jsfiddle.net/3U6mE/6/
I hope it helps you get started.

Categories