Uncaught ReferenceError: findWeather is not defined - javascript

I am currently working on a simple web-app for my studies that shows the current weather per location and current weather on the location you type in.
I have in my HTML file:
<div id="data">
</div>
<input type="text" value="Which city are you in?">
<input type="button" value ="Submit" onclick="findWeather()">
and for the JavaScript file:
function findWeather() {
$.get("http://api.openweathermap.org/data/2.5/forecast?q=Eindhoven&appid=*My_APP_ID*",
function () {
document.getElementById("data").innerHTML = data.list.main.temp;
})
}
Of course I have filled in the right App ID, I'm just not sure whether to share it here or not.
The JavaScript script won't run and I have no clue why.
EDIT: I seem to getUncaught ReferenceError: findWeather is not defined
error, while I did declare findWeather..?

You haven't defined data.
Presumably it is supposed to be the first argument of the function you pass as the second argument to $.get.

After passing the URL, as a second argument of the .get() function you are passing a callback anonymous function. In this function you must declare the parameter in which the data should be stored. For example:
function findWeather(){
$.get("http://api.openweathermap.org/data/2.5/forecast?q=Eindhoven&appid=*My_APP_ID*",
function(data) {
document.getElementById("data").innerHTML = data.list.main.temp;
})
}

Related

Global variable not working as an input value

I am a JavaScript beginner, I am stuck with a problem regarding variables.
I wrote this code :
var acNo = document.getElementById("ac").value;
function doSomething(){
alert(acNo);
}
The output is: undefined
But when I did this :
var acNo = 3
The output is 3
Html code :
(This is a very big project so that's why I cant share much code, but I am sharing the HTML code related to this script)
<td>A/c</td>
<td> <input type="number" name="" id="ac"></td>
<td> <input type="number" name="" id="acHour"></td>
Can you please tell me how can I fix it while keeping the variable global only.
Try defining acNo after the document has fully loaded, or within the function.
Solution 1:
let acNo;
window.onload = () => {
acNo = document.getElementById("ac").value;
}
function doSomething() {
alert(acNo);
}
Solution 2:
funtion doSomething() {
alert(document.getElementById("ac").value)
}
A way you can go to check that is by opening the dev tools of your browser and running your document.getElementById in the console.
You will be able to see everything about the element and what properties it has. For example, you might want to check innerHTML instead of value depending on your element type.
I think the value is only set in the beginning and not when you run doSomething later. If you want to have the value globally, have a global variable and keep updating it when you call doSomething.
var acNo = document.getElementById("ac").value;
function doSomething(){
acNo = document.getElementById("ac").value;
alert(acNo);
}

getJSON is not a function when the second time I called it

This is the first time I use jquery. The situation I'm facing here is that I need to parse some JSON file whose url is given by another JSON file.
Thus, I use the code
var GlobalID = {};
function parseID() {
var data;
$.getJSON('https://taitk.org/api/algorithms', function(algorithms) {
GlobalID = algorithms;
console.log("ID got!");
parseKeyword();
});
}
function parseKeyword () {
for(var i = 0; i < GlobalID.length; i++) {
$.getJSON('https://taitk.org/api/algorithms/' + GlobalID[i].id, function(subdata) {
console.log(subdata.data)
});
}
}
, where parseID() is a function to get the ID of each url, parseKeyword() is a function print out each url's data (written in the callback function, thus avoid the asynchronous function call).
However, the error I got is keyword.js:31 Uncaught TypeError: $.getJSON is not a function while the message "ID got!" is successfully printed. Also, the code work fine when I delete the parseKeyword()function, which is confusing for me because the first getJson() call seems to work while the second doesn't.
I'd like to figure out what kind of situation I'm facing to cause such error, thank you.
And, below is how I include those function in the html file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script></script>
<script src="js/keyword.js"></script>
<script type="text/javascript">
parseID()
</script>
The real cause is that I included the slim version of jquery in the <body> part along with the version mentioned in the question description. After removing it, it seems good.

"Error: Invalid ReCAPTCHA client id" when executing an invisible captcha

I'm trying to implement Google's Invisible reCAPTCHA in a HTML form in a Wordpress website.
In the head
First, I have the script that sets up the callbacks and binds the submit event of the form to the verification:
jQuery(document).ready(function() {
var valid = false;
window.recaptchaOkay = function(token) {
valid = true;
jQuery('#cadastro').submit();
};
document.getElementById('cadastro').addEventListener('submit', function validate(event) {
if (valid) {
return true;
}
var cap = document
.getElementById('cadastro')
.querySelector('.g-recaptcha');
grecaptcha.execute(cap);
event.preventDefault();
return false;
});
});
Then, I load the reCAPTCHA script, precisely as indicated in the documentation:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
In the body
And this is the form I'm using:
<form action="https://example.com/" method="post" id="cadastro">
<div
class="g-recaptcha"
data-sitekey="6Lc0jC4UAAAAANlXbqGWNlwyW_e1kEB89zLTfMer"
data-callback="recaptchaOkay"
data-size="invisible"
id="cadastro-captcha">
</div>
<button type="submit" id="cadastro-submit">Enviar</button>
</form>
What happens
I fill the form, submit it, and the following error is thrown (in the line with grecaptcha.execute):
Error: Invalid ReCAPTCHA client id: [object HTMLDivElement]
Also tried just passing the cadastro-captcha ID directly to that function as a string (e.g. grecaptcha.execute("cadastro-captcha")), yet the same error happens (bar the id being different, obviously). Equivalently, if I pass no argument, the same error happens, except it refers to undefined.
Try this one :--
The grecaptcha.reset() method accepts an optional widget_id parameter, and defaults to the first widget created if unspecified. A widget_id is returned from the grecaptcha.render() method for each widget created. So you need to store this id, and use it to reset that specific widget:
var widgetId = grecaptcha.render(container);
grecaptcha.reset(widgetId);
If More information then Read google recaptcha docs:--
https://developers.google.com/recaptcha/docs/display#js_api

Validate dynamic input form elements using Validator Plugin Jquery

I am using this http://jqueryvalidation.org/ jquery validation plugin.
HTML dynamic form will be like this
<form name="baby_book" id="baby_book">
<input name="form_elements[16]" id="form_elements[16]">
<input name="form_elements[17]" id="form_elements[17]">
<input name="form_elements[18]" id="form_elements[18]">
<a class="myfont baby_book_save" href="javascript:void(0)" onclick="validatefilesizeform('save')" >Save</a>
</form>
My JS Code will be like this
<script type="text/javascript">
var validator="";
$(document).ready(function(){
var max_length_rules= <?php echo json_encode($valid_rules); ?>;
validator=$("#baby_book").validate();
$.each(max_length_rules,function(k,v){
$.each(v, function(key, value){
$('input[id="'+key+'"]').rules('add',"required");
});
});
});
function validatefilesizeform(type)
{
if(type == 'save')
{
document.baby_book.sec_submit.value="save";
if(validator.form())
{
document.baby_book.submit();
}
}
</script>
While applying dynamic rules like that it doesn't validate the form.
In console it displays this error
Uncaught TypeError: Cannot read property 'form' of undefined
Can anyone help me how to add dyanmic rules . Thanks.
That's because when the browser finds the validatefilesizeform('save') in the onclick attribute, it evaluates that expression, i.e runs the function. With this syntax you're asigning the result of that evaluation to the onclick event, which is not what you want.
The Cannot read property 'form' of undefined error happens because in that moment the $(document).ready() callback has not yet been executed, and, when the function tries to execute validator.form(), that variable is already undefined. It will be initialized later, inside the $(document).ready().
To get the expected behavior, and avoid the error, you must change the onclick handler to this one:
`onclick="function() { validatefilesizeform('save') }"`
In this case you're registering a function as the value for the onclick attribute. And this function will be evaluated when the control is clicked.
To make it even more clear:
// This is the value returned by the function evaluation:
validatefilesizeform('save')
// This is a function
function() { validatefilesizeform('save'); }
So the second is a function that can be evaluated. The first one evaluates the function. Handlers should always be functions, and not values.

Javascript reference error to function

I want to call a Javascript function every time a checkbox changes its value. I do the same for inputs of the select type and there it works just fine. Both inputs are in one table.
This is one element that calls the first function:
<td>
<select name="minuteEnd" id="minuteEnd" onChange="calculateWorkTime()">'.$dropDown_minuteEnd.'
</select>
</td>
And the part which calls the second function
<td>
<input type="checkbox" name="deleteShift" id="deleteShift" onChange="updateSubmitButton()" /><br />
<input type="checkbox" name="deleteShiftConfirm" id="deleteShiftConfirm" onChange="updateSubmitButton()" />.
</td>
Then I define both functions in separate script tags, but I also tried to define them in one, that did not solve the problem. Because I do not always need both of them I call a PHP-function for each to be written.
These PHP functions are
drawScriptCalculateWorkTime();
drawScriptUpdateSubmitbutton();
the actual Javascript code is this:
function drawScriptCalculateWorkTime()
{
echo'
<script>
function calculateWorkTime()
{
//I work (My name can be found)
}
</script>
';
}
function drawScriptUpdateSubmitbutton()
{
echo'
<script>
function updateSubmitButton()
{
//I do not work. I get the error: ReferenceError: updateSubmitButton is not defined
//This is my code
var delete = document.getElementById("deleteShift").checked;
var deleteConfirm = document.getElementById("deleteShiftConfirm").checked;
if(delete && deleteConfirm)
{
document.getElementById("submitButton").disabled = false;
}
}
</script>
';
}
My Browser-console always tells me
ReferenceError: updateSubmitButton is not defined,
but I checked the name about 20 times. Further, it always tells me on window load this:
SyntaxError: missing variable name
This refers to the first line of Code of the second javascript.
I already checked google and even found a quite similar question here ( Javascript Uncaught Reference error Function is not defined ) but that solution did not work for me.
If I did not provide all information needed I will provide them right away.
John
In javascript, delete is a reserved word and cannot be used for a variable name.

Categories