Undefined function error for javascript function - javascript

Here is my code, I don't understand what's wrong.
<script type="text/jquery">
function gettotalAdult()
{
//Assume form with id="fsd-bucket-calc"
var theForm = document.forms["fsd-bucket-calc"];
//Get a reference to the # of Adults & Children
var quantity = theForm.elements["totalAdult"];
var caloriesAdult = theForm.elements["caloriesAdult"];
var adultcalTotal=0;
//If the totalAdult is not blank
if(totalAdult.value!="")
{
adultcalTotal = parseInt(totalAdult.value)*parseInt(caloriesAdult.value);
}
return adultcalTotal;
}
function gettotalChild()
{
//Assume form with id="fsd-bucket-calc"
var theForm = document.forms["fsd-bucket-calc"];
//Get a reference to the # of Children
var totalChild = theForm.elements["totalChild"];
var caloriesChild = theForm.elements["caloriesChild"];
var childcalTotal=0;
//If the totalChild is not blank
if(totalChild.value!="")
{
childcalTotal = parseInt(totalChild.value)*parseInt(caloriesChild.value);
}
return childcalTotal;
}
function gettotalCalories()
{
//Here we get the total calories by calling our function
//Each function returns a number so by calling them we add the values they return together
var totalCalories = gettotalAdult() + gettotalChild();
//display the result
document.getElementById('total-req-cal').innerHTML = "The total required calories are "+totalCalories;
}
</script>
This is my HTML:
<input type="text" name="totalAdult" id="totalAdult" onkeyup="gettotalCalories()" />
This is my error:
gettotalCalories is not defined
If it helps, the script is in the head of a WordPress page. Does anyone see what I'm doing wrong?

You have <script type="text/jquery"> you may need <script type="text/javascript"> instead.

Related

Passing appended text box values back to Google App Script Side

I have figured out how to append text boxes and set class as autocomplete therefore setting default values as the dynamic list generated in an avaliableTag function on the google app script side. I need to get each appended text box value back to the google app script side so the end user can submit the data and a new row of data will be appended to the google sheet. Here is my html code
<label for="units" style="font-size:125%;"><b>Number of items on Ticket</b></label>
<input type="text" name="units" id="units">
<!-- specified units by user-->
<button id = 'numitems' onclick = "getUnits()">Add items </button>
<!-- button that runs function to append appropriate # of boxes -->
</div>
<button id = 'submit' type = 'submit'name = "action">Submit </button>
Here is my google script code (left out doGet and HTML Service) these functions are what the user will submit to google sheet and the function that generates autocomplete options. Still need to get userInfo.MEDS
function userClicked(userInfo){
var ss = SpreadsheetApp.openByUrl('someURL');
var ws= ss.getSheetByName('Sheet1')
var user = Session.getActiveUser();
var timestamp = Utilities.formatDate(new Date(), 'CST', 'MM/dd/yyyy HH:mm:ss')
Logger.log(userInfo)
ws.appendRow([user,userInfo.id,userInfo.ticket,userInfo.items,userInfo.MEDS,timestamp]);
}
function getAvailableTags() {
var ss = SpreadsheetApp.openById("someId");
var s = ss.getSheetByName("someSheet");
var data= s.getRange("A2:A").getValues();
var headers = 1;
var tagColumn = 0;
var availableTags = [];
for (var row=headers; row < data.length; row++) {
availableTags.push(data[row][tagColumn]);
}
return( availableTags );
}
and finally here is the js/jquery side
var x=1
function appendRow()
{
var d = document.getElementById('left-col');
d.innerHTML += "<input type='text'class = 'autocomplete' id='tst"+ x++ +"'><br >";
}
function getUnits() {
var units = $("#units").val();
x=1
for (var count = 1; count < units; count++) {
$("<input type='text'class = 'autocomplete' id='tst"+ x++ +"'><br >").appendTo("#left-col");
}
var mednum = 0
$("#left-col").append("<input type='text'class = 'autocomplete' id='tst"+ x++ +"'>")
;
}
$(function() {
google.script.run.withSuccessHandler(buildTagList)
.getAvailableTags();
});
function buildTagList(availableTags) {
$( ".autocomplete" ).autocomplete({
source: availableTags
});
}
$('#submit').on('click', function (){
$('.autocomplete').each(function() {
var med = $(this).val();
console.log(med);
});
});
window.onload=function(){
document.getElementById('submit').addEventListener('click',buttonClick);
function buttonClick() {
var userInfo = {};
userInfo.Id = document.getElementById('ptid').value
userInfo.ticket = document.getElementById('ticket').value
userInfo.items = document.getElementById('items').value
}}
I need something that will take value of each appended box and let me store it in the userInfo object so it can be passed back to the gs side
You can use google.script.run to run a function in code.gs side and send the form object [1]. Also, you should prevent the default behavior for when the form is submitted:
function buttonClick() {
var userInfo = {};
userInfo.Id = document.getElementById('ptid').value
userInfo.ticket = document.getElementById('ticket').value
userInfo.items = document.getElementById('items').value
google.script.run.userClicked(userInfo)
}
$("#formID").submit(function(e){
e.preventDefault();
});
[1] https://developers.google.com/apps-script/guides/html/communication#forms

i don't know what i did wrong, it doesn't work, i'm trying to make a task list

<!DOCTYPE html> <!--Declare the document type and version of HTML-->
<html>
<head><!--Information related to the decument-->
<title>Task List</title>
<link rel="stylesheet" href="mydesign.css">
</head>
<body><!--Information related to display the decument-->
[<img src="cm1XiuT.png" alt="CounterStrike" style="width:100%;height:250pt;">][1]
<input type="text" placeholder="Add Tasks Here..." id="taskValue">
<button id="addBtn" onclick="addTask()">add</button>
<!--horizontal Rule-->
<hr>
<section id="content">
</section>
<script>
/creates an Array variable tasks checks if there are any stored
tasks in the browser Conditional statement - Checks IF there is
data stored then imports the data to the array IF not - exitx the
function with an empty array IF THERE IS - exits the function with
the poplulated array/
this is a code
function creatArray()
{
var taskArray = [];
var tasks = localStorage.getItem("itemList");
if(tasks != null)
{
/*code runs if the condition is met*/
taskArray = JSON.parse(tasks);
}
return taskArray;
}
/*Addsa task to the list Creates an array Creates a variable to
store the information in the input fieldset clears the information
in the input field Pushes the task into our Array Stores the
updated Tasklist in the browser Calls the displayTask Function
*/
function addTask()
{
var taskList = creatArray();
var task = document.getElementById("taskValue").value;
document.getElementById("taskValue").value = "";
taskList.push(task);
localStorage.setItem("itemList",JSON.stringify(taskList));
displayTask();
}
/*Removes a task from the list creats a variable to store the
correct button information. this - as in "this"button that has been
clicked creats an array removes the task from our array and
defines how many items we need to remove calls the displayTask
function */
function removeTask()
{
//remove the tasks from the array
var rID = this.getAttribute("id");
var taskList = createArray();
taskList.splice(rID, 1);
localStorage.setItem("itemList",JSON,stringify(taskList));
displayTask();
}
/*displays Tasks in the list Creates the array of tasks creates
the variable to store the list items LOOP statement - adds HTML to
each list item in the array {repeats until the end of the }
replaces the content in the section tag with id="content"
creates a button array LOOP STATMENT - adds an EvenListenerr to
each button in the List */
function displayTask()
{
var taskList = createArray();
var showTasks = "<ul>";
for(var i=0; i < taskLIst.length; i++)
{
showTasks += "<li>"+taskList[i]="<button class='rmvBtn'id='"+i+"'>remove</button></li>"
}
showTasks += "</ul>";
document.getElementById("content"),innerHTML =showTasks;
var btnArray = document.getElementById("rmvBtn");
for(i =0; i < btnArray.length; 1++)
{
btnArray[i].addEventListener('click',removeTask);
}
}
displayTask()
</script><!--includes an external javascript file-->
</body>
</html>
Look, only javascript and html
HTML
<div id="tasks"></div>
<div>
<input type="text" id="newTaskInput">
<button onclick="add()">Add</button>
</div>
JavaScript
var tasks = []
function init() {
tasks = load()
renderTasks()
}
init()
function renderTasks() {
var container = document.getElementById('tasks')
var frag = document.createDocumentFragment()
tasks.forEach(function(item, i) {
var div = document.createElement('div')
var text = document.createTextNode(item.name)
div.appendChild(text)
var closeBtn = document.createElement('button')
var btnText = document.createTextNode('x')
closeBtn.appendChild(btnText)
closeBtn.onclick = function() {
remove(i)
}
div.appendChild(closeBtn)
frag.appendChild(div)
})
container.innerHTML = ""
container.appendChild(frag)
}
function add() {
var input = document.getElementById('newTaskInput')
tasks.push({ name: input.value })
renderTasks()
save(tasks)
}
function remove(index) {
tasks.splice(index, 1)
renderTasks()
save(tasks)
}
function save(data) {
localStorage.setItem('tasks', JSON.stringify(data))
}
function load() {
var raw = localStorage.getItem('tasks')
if ( raw ) {
return JSON.parse(raw)
}
return []
}
DEMO

How to pass value between functions?

i'm creating a very simple Santa's game for my friends. So the logic is again very simple. Given a list of names, user need to insert his/her name and whenever the button is clicked, a random name will pick up from the list and display as result.
I have two small problems:
I can find and display the random name form the list but I cannot pass in the luckyName function and display it if is not the same of the user's name.
In case the name of the current user is the same of the picked up name, I 'm not sure how to or what's the best way to pick up another name. So far I just call again the pickRandomName function.
Html:
<h3>Santa ask: Who are you kid?</h3>
<section>
<input type="text" placeholder="YOUR name bitte, not time for joke.." id='santaName'/>
<div id="go">Go</div>
</section>
js:
var nameList = [
'gio',
'anna',
'chiara',
'ella',
'sarah',
'sara'
];
$(document).ready(function(){
pickRandomName();
luckyName();
});
var luckyName = function(randomName){
var section = $('section');
$('section').on('click', '#go', function(){
var currentSanta = $('#santaName').val();
console.log(currentSanta);
if( currentSanta != randomName){
console.log(randomName);
$('section').append(randomName);
} else {
//pick up another random name
pickRandomName(randomName);
console.log(randomName);
}
});
};
var pickRandomName = function(randomName){
var randomName = nameList[Math.floor(Math.random() * nameList.length)];
console.log(randomName);
};
and here the fiddle:
http://jsfiddle.net/anaketa/r9morh87/1/
Here is the working fiddle for your code.
$(document).ready(function(){
window.randomName =pickRandomName(nameList);/*we have created an global variable which will store randomName*/
luckyName(nameList);
});
function luckyName(nameList){
var section = $('section');
$('section').on('click', '#go', function(){
var currentSanta = $('#santaName').val();
console.log(currentSanta);
if( currentSanta != window.randomName){
console.log(window.randomName);
$('section').append(window.randomName);
}
else {
//pick up another random name
window.randomName = pickRandomName(nameList);/*It will change the global var window.randomName value*/
console.log(x);
}
});
}
function pickRandomName(randomName){
var randomName1 = nameList[Math.floor(Math.random() * nameList.length)];
console.log(randomName1);
return randomName1;
};
I am passing the value between functions by using window.randomName (Learn more about different kinds of variable here).
By defining window.randomName we have attached a property to window, like "window.location", which can accessed by all the functions whenever and wherever they want without the need to passing the argument to function again and again and also the function can change it's value so whenever we need to pass a variable to different function this is one way to do it.
Try this,
var nameList = [
'gio',
'anna',
'chiara',
'ella',
'sarah',
'sara'
];
$(document).ready(function() {
var randomName = nameList[Math.floor(Math.random() * nameList.length)];
//console.log( nameList[Math.floor(Math.random() * nameList.length)]);
$('#go').on('click', function() {
luckyName(randomName);
});
});
var luckyName = function(randomName) {
var section = $('section');
$('section').on('click', '#go', function() {
var currentSanta = $('#santaName').val();
console.log(currentSanta);
if (currentSanta != randomName) {
console.log(randomName);
$('section').append(randomName);
} else {
//pick up another random name
pickRandomName(randomName);
console.log(randomName);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>Santa ask: Who are you kid?</h3>
<section>
<input type="text" placeholder="YOUR name" id='santaName' />
<div id="go">Go</div>
</section>

How do i solve these issues?

I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)

javascript split

<script language="javascript">
function frompost()
{
var string=$('#indexsearch').val();
var url=string.split('=');
if(url==""){
var url=string.split('video/');
}
var finalurl='http://watchvideos.tv/watch/'+url[1];
window.location = finalurl;
//$('#srchFrm').attr('action',finalurl);
//document.srchFrm.submit();
}
</script>
I have a problem with this script - it's Ok as long as indexsearch field contains = and fails when it's supposed to work as well - with video/ in the field
Try it like this:
function frompost()
{
var str = $('#indexsearch').val(),
url = str.split(/=|video\//),
finalurl = 'http://watchvideos.tv/watch/'+url[1];
window.location = finalurl;
}

Categories