Javascript Function Reference Error, Function undefined - javascript

I have the following HTML:
<input type='checkbox' onchange='checkvalue(this)' def='checked' value='checked' />
and the following javascript:
$(document).ready(function(){
function checkvalue(){
if($(this).attr("value") != "checked"){
($(this).attr("value") = "checked");
}
else{
($(this).attr("value") = "unchecked");
}
}
});
Basically whenever a checkbox is checked or unchecked I want to call this javascript function which will see whether or not the default value of the checkbox is checked or unchecked, and then change the value accordingly - if a checkbox had default value of checked and is clicked, the value should change to unchecked and vice versa. However, I get the following error when I click on my checkbox:
Uncaught ReferenceError: checkvalue is not defined (index):38
onchange
Here is the link to my jsfiddle: http://jsfiddle.net/LRneA/

checkvalue is not in the global scope. It is local to the ready handler, which is an anonymous function.
I suggest not using onclick="...". If you're already using jQuery, bind the event using jQuery also:
$("#myCheckBox").on("click", checkvalue); //you will need to give your checkbox
//an id
You can do this inside the onReady handler.
Another thing I noticed:
if($(this).attr("value") != "checked")
Isn't going to work. The value of the checkbox has nothing to do with it being checked or not. Use the :checked pseudoselector instead along with .is:
if($(this).is(":checked"))

The function/identifier checkvalue is local to the "on ready" function.
To use checkvalue from an inline event attribute, you must make it accessible from the relevant (global) scope. For instance,
$(document).ready(function(){
function checkvalue(){
// ..
}
window.checkvalue = checkvalue;
});
However, simply eliminating the use of inline events is often preferred. If the element ID is not known, or the event must be applied to many elements, then Event Delegation (i.e. .on) can be used.
jQuery(function($){
function checkvalue() {
// ..
}
// ideally you'd pick a more refined ancestor than "document"
$(document).on("click", "checkbox", checkvalue);
});
And, if you do continue with inline events, and you do fix the first mentioned issue, then you'll also have to use apply to correctly setup the context or this will evaluate to the window object in the handler, which will be no fun and lead to other errors.
onclick="checkvalue.apply(this)"

Related

Change checkbox value doesnt fire the change event in Jquery

I have a checkbox and I marked it as checked, however it doesnt fire the on change function. The note doesn't appear.
My code:
$('#checkbox1').prop("checked", true);
$('#checkbox1').change(function(){
if ($(this).is(':checked'))
$('#s-note').show();
else
$('#s-note').hide();
});
Do you expect the onchange to fire without user interaction?
Your issue is you set the checked state before you set the handler so if this would have trigged change, you would have not caught it. Your real issue here is setting the property with JavaScript does not fire the change event. So you need to trigger the change event manually.
$('#checkbox1')
.prop("checked", true) // set it to checked
.on("change", function() { // bind change event
$('#s-note').toggle($(this).is(':checked')); // toggle visibility
}).trigger("change"); //trigger that you need the change to run
If you are setting the note to be hidden by default and doing it with an id based selector, like this:
#s-note { display:none; }
Then your code won't be able to show it because it also uses an id based selector and that won't be more specific than the selector already in effect.
Instead, you'll have to default the note to hidden using a selector that is less specific than the id selector you will use to show/hide it later. That would be a class.
Also, it's critical that you set up the event handler before you trigger the event, so that when the event happens, there is already an event handler registered.
Now, for your needs, you don't really need the change event, click will do just fine. And, lastly, to ensure that you properly trigger the event, use JQuery's .trigger() method to set things in motion.
// Make sure you set up the callback first
$('#checkbox1').on("click", function(){
if ($(this).is(":checked"))
$('#s-note').show();
else
$('#s-note').hide();
});
// Then just trigger the event
$('#checkbox1').trigger("click");
.hide { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox1">Test
<div id="s-note" class="hide">Special</div>
I hope this code snippet will help you
Approach 1
$('#idcheckbox').on('change', function() {
if($(this).is(':checked')) {
alert('checked');
} else {
alert('default ');
}
});
Approach 2
$('input[type=checkbox]').on('change', function() {
if($(this).is(':checked')) {
alert('checked');
} else {
alert('default ');
}
});
I ran your code in .net mvc and it runs fine.
This is the checkbox same id it hide or shows div element.
<input type="checkbox" id="checkbox1" value=" " />
<div id="s-note" style="display: none">
<label>Showing</label>
</div>
What are you trying to display?

checkbox onclick function not called in IE

I have the following checkbox in HTML:
function updateSettings(id, bit) {
alert('0');
}
<input type="checkbox" onclick="alert('1');updateSettings(0, 1);alert('2');" />
In IE11 on click I get alerts 1, 2 but not 0: the function is not executed at all.
In Chrome everything works fine.
The function updateSettings is defined in IE on the document object. See this documentaion.
When you put a call inline, as in this case in an onclick, it will look first in the element itself if the function is defined. Then it will search the DOM tree up to document to see if the function is defined (some elements are searched and some not, unfortunately I didn't know the rule governing this until #user4749485 wrote his comment below), and after, as a last resort in window. As it find it, it runs it.
As you defined your own updateSettings probably on the global object (window), it's not fired in IE, because the function defined on the document object is found first.
End of mystery bug :-)
UPDATE :
#user4749485 pointed to the link explaining this at the w3 site, the information is in item 1.10 - Lexical Environment Scope. To sum it up :
<element onclick="functionFoo();">bar</element>
implies following procedure :
Does element.functionFoo exist ? YES ==> use this function.
ELSE
Does element belong(1) to a form and form.functionFoo exist ? YES ==> use this function.
ELSE
Does document.functionFoo exist ? YES ==> use this function.
ELSE
Does window.functionFoo exist ? YES ==> use this function.
ELSE
crash.
(1) = an element belongs to a form != an element is inside a form element. Roughly it must be a form element, like in the question an input element.
Found the issue, but it's strage. If you change the function name to lower case, then it works.
function updatesettings(id, bit) {
alert('0');
}
<input type="checkbox" onclick="alert('1');updatesettings(0, 1);alert('2');" />
DEMO: http://codepen.io/anon/pen/YXLgxJ
UPDATE: As Zimmi has explained updateSettings is an inbuilt method document.updateSettings() in IE and this will be triggered on onclick event instead of our method window.updateSettings()
I'd suggest not to use an inline onclick event and instead use jquery to define an event for the checkbox:
function updateSettings(id, bit) {
alert('0');
}
jQuery(document).ready(function(){
jQuery("#cbMyCheckbox").click(function(){
alert('1');
updateSettings(0, 1);
alert('2');
});
});
and then in your html:
<input type="checkbox" id="cbMyCheckbox" />

Checkbox and click event handling

I'm trying to set a textbox to 'readonly', add a class, and put a text into the textbox at that moment when I check the checkbox. Moreover, I'm also trying to remove 'readonly' attribute from the textbox, add a class, and delete text in the textbox.
I have
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
This code doesn't work for me.
Thanks,
Phillip
Thanks everyone for answers.
According to your comments and answers, I've changed my code but it's still not working.
$('#CheckBoxSectionCode').click(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').prop('readonly', true);
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text('disabled');
}
else {
$('#TextBoxSectionCode').prop('readonly', false);
$('#TextBoxSectionCode').removeClass('disabled').addClass('enabled');
$('#TextBoxSectionCode').text('');
}
});
I'm using chrome browser to run this code, and using developer tools in chrome and put a break point at the code above to see what's happening in the jquery. However, when I click the check box to check/uncheck, nothing happens there.
document.getElementById('TextBoxSectionName').val this is wrong. You really should cache your jQuery object so it's not navigating the DOM over and over. Then you mix in native JS and .val is not a DOM property or method, nor is it a jQuery property, it should be .value for a DOM object or .val() for a jQuery object.
Obligatory explanation by #Archy Wilhes:
"Just to clarify; when #SterlingArcher says caching the jQuery object,
she/he means doing something like var obj = $('#TextBoxSectionCode')
then calling the functions using the variable like this:
obj.attr(...); obj.addClass(...). Every time you do a $(something) you
are calling a function in jQuery that looks for the DOM."
since everytime you are adding the class the element is going to end up having both the two classes. Consider removing the other class before adding one. For example,
$(selector).removeClass('disabled').addClass('enabled')
Try with change event instead of click:
$('#CheckBoxSectionCode').change(function () {
if ($(this).is(':checked')) {
$('#TextBoxSectionCode').attr('readonly', 'readonly');
$('#TextBoxSectionCode').addClass('disabled');
$('#TextBoxSectionCode').text(document.getElementById('TextBoxSectionName').val);
}
else {
$('#TextBoxSectionCode').attr('readonly', false);
$('#TextBoxSectionCode').addClass('abled');
$('#TextBoxSectionCode').text('');
}
});
You could do the following way.
//Cache reference to DOM as DOM scan is expensive!
var textBox = $('#TextBoxSectionCode');
$('#CheckBoxSectionCode').click(function () {
//Use prop as opposed to attr
textBox.prop("readOnly", false).removeClass('disabled').addClass('abled').text("");
if ($(this).is(':checked')) {
textBox.prop("readOnly", true).removeClass('abled').addClass('disabled').text($("#TextBoxSectionName").val());
}
});

How to associate onClick with a dynamically generated div with dojo?

I am using dojo 1.9.2, and is trying to attach an onClick function on a piece of HTML code that I created on the fly, like this:
clickableDiv = "<div data-dojo-attach-point=\"testBtn\">Click Me!</div>";
self.racks.innerHTML = clickableDiv;
and then I want to give it an onClick function after, so right below the code I putted:
connect(this.testBtn, "onclick", alert("You Clicked It!"));
For some reason not only this wont work, when I refresh the page the alert "You Clicked It!" would pop up without me clicking anything...
I Have to use this dojo version, it's part of the requirement...
Any idea or suggestion on how I can go about doing this?
Well, dojo is part of javascript, so you can probably use some javascript function, for example:
clickableDiv = "<div id=\"testBtn\">Click Me!</div>";
self.racks.innerHTML = clickableDiv;
document.getElementById('testBtn').onclick=function(){alert("You Clicked It!");};
The code mentioned in the question is correct, except for one mistake. The "onclick" event needs a handler function, not the code directly. So, enclose that alert statement by a function.
connect(this.testBtn, "onclick", function(){alert("You Clicked It!")});
Or a separate function elsewhere can be linked here a handle by passing the function or just name of the function.
function abcd() {
alert('You clicked It');
}
connect(this.testBtn, "onclick", "abcd");//same as connect(this.testBtn, "onclick", abcd);
When providing an event handler (or a callback in general), you have to provide the function as reference. When you use:
connect(this.testBtn, "onclick", alert("You Clicked It!"));
You're actually saying that you want to connect the onClick event handler to the return value of that alert(). What you actually want is like the other answers already explained by wrapping it inside a function that is passed through by reference:
connect(this.testBtn, "onclick", function() {
alert("You Clicked It!")
});
However, since you're using data-dojo-attach-point which is generally used in widgets, you could also define your event handler in a similar way, for example:
clickableDiv = "<div data-dojo-attach-point=\"testBtn\" data-dojo-attach-event=\"onClick: myClickHandler\">Click Me!</div>";
Then you can just write a function called myClickHandler in your widget that shows the alert, for example:
myClickHandler: function() {
alert("You Clicked It!");
}
He's using dojo 1.9.2. connect is deprecated and he should be using on:
on(this.testBtn, "click", function(){
alert("You Clicked It!")
});
Your data-dojo-attach-point won't get picked up in dynamically placed HTML. You would put that in a custom widget template to provide the actual reference to your node/widget. If you did have that element in a template to begin with, you could simply use the attribute on your element:
data-dojo-attach-event="onClick: someFunction"

Find observable from input-field

When an input gets focus, I want to pop up a warning if the input is invalid.
The message is in the observable.
So given this code, how do I find the observable bound to it.
$(document).on("focus", "input.invalid", function(){
console.log("ahaaaa!");
//your code here
//dig out observable from this and find the message
//create element with class invalid-message and place it next to this
}).on("blur", function(){
$(".invalid-message").remove();
});
I'm using knockout validation and I only want to show the error message when the field has focus. Other suggestions are welcome.
EDIT:
When I'm using dataFor:
$(document).on("focus", "input.invalid", function(){
console.log(this);
console.log(ko.dataFor(this));
...
I get this in the console:
The underlined observable is the one I'm after.
EDIT2:
I'm working around it like this:
$(document).on("focus", "input.invalid", function(){
var fieldName = $(this).attr("name");
var errorMessage = ko.dataFor(this)[fieldName].error;
...
You can use:
ko.dataFor(this)
which will give you the observable of the current element.
For more details, look here:
Using unobtrusive event handlers
Why not simply use Knockout's event binding to set up handlers for focus and blur? Your handlers will be called with the value of the input as their first parameter; no need to play around with jQuery.

Categories