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.
Related
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);
}
I can't find out what is the problem with this JSFiddle.
HTML:
<input type="button" value="test" onclick="test()">
JavaScript:
function test(){alert("test");}
And when I click on button - nothing happened. The console says "test not defined"
I've read the JSFiddle documentation - there it says that JS code is added to <head> and HTML code is added to <body> (so this JS code is earlier than html and should work).
If you do not specify the wrap setting it defaults to "onLoad". This results with all JavaScript being wrapped in a function run after result has been loaded. All variables are local to this function thus unavailable in the global scope.
Change the wrapping setting to "no wrap" and it'll work:
http://jsfiddle.net/zalun/Yazpj/1/
I switched the framework to "No Library" as you don't use any.
The function is being defined inside a load handler and thus is in a different scope. As #ellisbben notes in the comments, you can fix this by explicitly defining it on the window object. Better, yet, change it to apply the handler to the object unobtrusively: http://jsfiddle.net/pUeue/
$('input[type=button]').click( function() {
alert("test");
});
Note applying the handler this way, instead of inline, keeps your HTML clean. I'm using jQuery, but you could do it with or without a framework or using a different framework, if you like.
There is another way, declare your function into a variable like this :
test = function() {
alert("test");
}
jsFiddle
Details
EDIT (based on the comments of #nnnnnn)
#nnnnnn :
why saying test = (without var) would fix it ?
When you define a function like this :
var test = function(){};
The function is defined locally, but when you define your function without var :
test = function(){};
test is defined on the window object which is at the top level scope.
why does this work?
Like #zalun say :
If you do not specify the wrap setting it defaults to "onLoad". This results with all JavaScript being wrapped in a function run after result has been loaded. All variables are local to this function thus unavailable in the global scope.
But if you use this syntax :
test = function(){};
You have an access to the function test because it's defined globally
References :
https://stackoverflow.com/a/338053/3083093
https://stackoverflow.com/a/5830423/3083093
Change wrap setting in the Frameworks & Extensions panel, to "No wrap-in <body>"
There is no problem with your code.Just choose the extension onLoad() from right side.
<script>
function test(){
alert("test");
}
</script>
<input type="button" value="test" onclick="test()">
Select OnDomready
HTML:
<input id="dButton" type="button" value="test"/>
JavaScript:
addEventListener('load', init, false);
function init()
{
oInput = document.getElementById('dButton');
oInput.onclick = test;
}
function test(){
alert("test");
}
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.
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;
})
}
I have html like
<div id="MAC_Allocation_Heading">
<span style="position:relative;left:2%;">
MAC Allocation
</span>
<span style="position:relative;left:9%;">
<label>Quantity</label>
<input type="text" style="width:40%" name="txtMACNeededAllocations"/>
</span>
</div>
Now in my .js file I have a global array as
var user_entry = [$("#MAC_Allocation_Heading input[type=text]:first")]
and inside FormValidate() I have the following code
function FormValidate() {
console.log(user_entry[0].val());
}
I run the application and entered value in text box. But I am getting console output as 'undefined'.
If I put the array "user_entry" inside the function then am able to get the textbox value.
What is the reason?
I Would love to keep this array globally as it will be used by other functions also
Try this:
var user_entry = [];
function FormValidate()
{
alert(user_entry[0].val());
}
$(document).ready(function()
{
user_entry = [$("#MAC_Allocation_Heading input[type=text]:first")]
})
By this you can achieve "I Would love to keep this array globally as it will be used by other functions also".
I got the issue as per comments above
I initialized the array inside $( document ).ready(function() { ... });
and this solved my issue
The problem is I included the .js file before tag so that before DOM is loaded completely I try to get a reference to the object which is obviously empty