JavaScript 'function undefined' error working with jsfiddle - javascript

I'm trying just to understand an error completely because sometimes I can get around it and other times I can't. I've tried just writing a function:
function toggleButton() {
}
But I get the same error. This is the .js sample.
var checkBox = document.getElementById("chkMyBox");
checkBox.onclick = function toggleButton(e, obj1)
{
var btnElement = document.getElementById("btnMyButton");
if(btnElement != null) {
alert("Element not null");
if(e.target.checked && obj1 != null) {
alert("Checking check " + obj1.checked);
if(obj1.checked == true && btnElement.getAttribute('disabled') == false){
btnElement.getAttribute('disabled') = false;
} else {
btnElement.getAttribute('disabled') = true;
}
}
}
}
Here's the html:
<form id="frmCheckBox">
<input type="checkbox" id="chkMyBox" />
<button id="btnMyButton" disabled>I'm a Button</button>
</form>
http://jsfiddle.net/Arandolph0/h8Re6/3/

Change this line which uses name:
<input type="checkbox" name="chkMyBox" />
into using id instead:
<input type="checkbox" id="chkMyBox" />
Alternatively you could use:
var elements = document.getElementsByName('chkMyBox');
var element = elements[0]; //first element with that name in the array
or
var element = document.getElementsByName('chkMyBox')[0];
Update (as OP changed the code from the original question):
function toggleButton(e, obj1)
This won't work as there is only a single argument given to the callback function (e).
Use e.target to get the element.

You're trying to get an element by its name. You'd have to do:
var checkBox = document.getElementsByName('chkMyBox')[0];
Or, if you prefer by id. Just add id="chkMyBox" to your checkbox input.

You have several problems here.
1) You try to get the button by using getElementById but your element has no id. The easiest fix is to fix your markup.
<input type="checkbox" name="chkMyBox" id="chkMyBox" />
2) Your event handler takes two parameters. When attaching the handler via the DOM, only the event gets passed to your handler. Therefore obj1 will always be undefined. You need to get the checkbox element from the e parameter.
checkBox.onclick = function(e) {
var obj1 = e.target;
// rest of handler
}
3) You shouldn't use getAttribute to check for the element being disabled/enabled. It will give you the text value of the attribute which is an empty string. Instead, use the boolean property that the DOM gives you:
// toggle the disabled attribute
obj1.disabled = !obj1.disabled;

Related

bind javascript function to input control on window load

I amm develloping an web form with multiple text box with same css class.
and i want to bind a specific method to all these textboxes who use that class.
belows are my codes
window.onload = function ()
{
var tObj = document.getElementsByClassName('exa');
for (var i = 0; i < tObj.length; i++) {
tObj[i].onblur(convertAmount(event,this));
}
}
the another function 'convertAmount()' is below
function convertAmount(evt, obj) {
if (obj.value != "") {
var num = parseFloat(obj.value);
num = Math.round((num + 0.00001) * 100) / 100;
obj.value = num.toFixed(2);
}
else {
obj.value = "0.00";
}
}
html codes
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
when browser load first time only '0.00' values are coming on those text boxes. but when i type some values on those text boxes and press tab its not working! please help what is wrong here
As commented before, you should assign a eventHandler and not pass it as callback.
So you code would be:
tObj[i].onblur = convertAmount.bind(this, event, this);
Also, event is default argument for any eventListener and current object/element is automatically binded to it, so above code can be simplified to
tObj[i].onblur = convertAmount;
This will bind the context and you will get all properties in this.
Sample Fiddle
Note: you should use addEventListener instead. onBlur = will replace all previous events. addEventListener will add another one.
Sample Fiddle
I hope this link helpful to you.
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
$(document).ready(function(){
$('.exa').each(function(index,value){
$(this).attr('onblur',convertAmount(event,$(this)))
})
})
function convertAmount(evt, obj) {
if (obj != "") {
$(obj).val('0.00')
}
else {
$(obj).val('0.00')
}
}

Detecting an html attribute's value with a userscript?

I am trying to make myself a personal user script, but I need to detect an html attribute's value. For example:
<div id="a">Stuff</div>
<div id="b" value="false"></div>
How could I create an if statement in the script, that triggers if the "value" attribute of element b turns to true?
element = document.getElementById("b");
if(element != null) {
if (element.value == "true") {
// do something
}
}
Check out this link... it says that you can import JQuery into your userscript.
youtube video
You can then get the value of any attrubute using jquery API for attr
Jquery Api attr
which can be done like
var bAttrValue = $("#b").attr("value");
You then coulld write a function which takes in an Id and an attribute like
function GetAttributeValue(elemId, attribute)
{
//Todo: write checks to ensure the elemId exists and that it as the attribute;
var elemAttrValue = $("#"+elemId).attr(attribute);
return elemAttrValue;
}
You could then consume it like
var DivbValue = GetAttributeValue("b", "value")
if(DivbValue) //true
{
//do something
}
else //false
{
//do something
}
alternatively write this in JavaScript
function GetAttributeValue(elemId, attribute)
{
//Todo: write checks to ensure the elemId exists and that it as the attribute;
element = document.getElementById(elemId);
return element[attribute];
}

Uncaught ReferenceError: parentsCheck is not defined

I am very new to JS, but am trying to create a checkbox that when checked will reveal a div with an id of "second_row", and when unchecked will hide it (unchecked by default). Am I missing some code? Is my syntax incorrect? I could really use some help. Thanks for givin a newbie a hand!
Html:
<input type="checkbox" name="under_18" id="under_18" class="check" value="under_18" form="contest_form" onclick="parentsCheck()" />
JavaScript:
<script>
function parentsCheck()
{
var check1 = document.getElementById('under_18'),
if (check1.checked === true) {
document.getElementById('second_row').style.display = 'block';
}
else if (check1.checked === false) {
document.getElementById('second_row').style.display = 'none';
}
}
</script>
P.S. Dont know if it matters, but the checkbox is in a table cell.
Your , at the end of the var statement should be a ;.
It's causing a SyntaxError, causing the JavaScript block to be effectively ignored, so parentsCheck() is never defined.
var check1 = document.getElementById('under_18');
http://jsfiddle.net/tYv28/
As an aside, check1.checked will always return a boolean, so you don't need to do the === true and === false comparison; the following will work just fine:
function parentsCheck()
{
var check1 = document.getElementById('under_18');
if (check1.checked) {
document.getElementById('second_row').style.display = 'block';
} else {
document.getElementById('second_row').style.display = 'none';
}
}
When using event handler attributes, JavaScript only recognizes functions in the global scope. Try defining the event handler in your JavaScript, which also has the benefit of being unobtrusive:
var el = document.getElementById('under_18');
el.onclick = parentsCheck; // <---- This
jsFiddle
Also, you need to change the , into a ;.

Execute custom function onChange

Pure JavaScript.
I have a checkbox in HTML page. I want to execute
App.setCheckedProperty(name, val);
Where name is name attribute of the checkbox and val true/false means checked.
How to implement it? I can't find any materials aboit it on the Net.
UPD:
<input type="checkbox" name="smth" onChange="<WHAT TO DO HERE?>" checked />
Final execution must be equal:
App.setCheckedProperty("smth", false);
UPD2:
Are there any contructions like this.name or this.checked in JavaScript?
you shouldnt do it "inline" inside your html. its just bad practice. i think what you want to do is to loop over a couple of checkboxes?
see this code:
// declare all vars that you need and find all input-elements
var i, input, inputs = document.getElementsByTagName('input');
// loop over all input-elements
for(i = 0; i <= inputs.length; i++) {
input = inputs[i];
// if the current element is a checkbox
if(input.type === 'checkbox') {
//append a click-handler to that checkbox
input.onclick = function () {
// if the checkbox is clicked, you can find the name and the checked-property
App.setCheckedProperty(this.name, this.checked);
};
}
}
and a working example here (i just alert instead of App.setCheckedProperty): http://jsfiddle.net/5wExJ/

Detect programmatical changes on a html select box

Is there a way to make a HTML select element call a function each time its selection has been changed programmatically?
Both IE and FF won't fire 'onchange' when the current selection in a select box is modified with javascript. Beside, the js function wich changes the selection is part of framework so I can't change it to trigger an onchange() at then end for example.
Here's an example:
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
</script>
</body>
Is there any way to make test() call myfunction() without changing test() (or adding an event on the button)?
Thanks.
If you can extend/modify the framework to give a hook/callback when they change the select options, it would be better (one way could be to use the dynamic capabilities of js to duck type it in?).
Failing that, there is an inefficient solution - polling. You could set up a setTimeout/setInteval call that polls the desired select option dom element, and fire off your own callback when it detects that something has changed.
as for the answer to your question
Is there any way to make test() call
myfunction() without changing test()
(or adding an event on the button)?
yes, by using jquery AOP http://plugins.jquery.com/project/AOP , it gives an easy-ish solution.
<body>
<p>
<select id="sel1" onchange="myfunction();"><option value="v1">n1</option></select>
<input type="button" onclick="test();" value="Add an option and select it." />
</p>
<script type="text/javascript">
var inc = 1;
var sel = document.getElementById('sel1');
function test() {
inc++;
var o = new Option('n'+inc, inc);
sel.options[sel.options.length] = o;
o.selected = true;
sel.selectedIndex = sel.options.length - 1;
}
function myfunction() {
document.title += '[CHANGED]';
}
//change to aop.after if you want to call afterwards
jQuery.aop.before( {target: window, method: 'test'},
function() {
myfunctino();
}
);
</script>
</body>
Define your own change function that calls the framework function and then calls a
callback function.
e.g.:
function change(callback)
{
frameworkchange();
callback();
}
The answer is .... no.
The DOM only fires the onchange event as a result of user action not code. It does not provide any additional events to hook in this regard.
You will need to customise the framework or drop your requirement.
ahem...
you can access the event 'onpropertychange' it contains a property within the event arguments to identify which property was changed.
It detects both 'selectedIndex' and 'value' changes - simply case test 'propertyName' I'm currently working with the ASP.NET js framework here is some straight copy-paste code for that:
1) define handler:
this._selectionChangedHandler = null;
2) assign handler
this._selectionChangedHandler = Function.createDelegate(this, this._onSelectionChanged);
3) attach handler to event
$addHandler(element, "propertychange", this._selectionChangedHandler);
4) create function
_onSelectionChanged: function(ev) {
if (ev.rawEvent.propertyName == "selectedIndex")
alert('selection changed');
},
With JQuery, you could do something like
$(document).ready(function(){
$('#select-id').change(function(e){
e.preventDefault();
//get the value of the option selected using 'this'
var option_val = $(this).val();
if(option_val == "v1"){
//run your function here
}
return true;
});
});
This would detect the change programmatically and let you respond to each item changed

Categories