Reputation: 1457
I have the following code:
function $(id) {
return document.getElementById(id);
}
var material = $("material");
var materialPrices = {"invalid": "from £800.00","1": "£1,200.00","2": "£800.00","3": "£800.00"};
var price = 0;
function update() {
$(".block").animate( { backgroundColor: '#B5D8EA' }, 500);
price = materialPrices[material.options[material.selectedIndex].value];
document.getElementById('pprice').innerHTML = price;
}
material.onchange = update;
basically in the line $(".block").animate( { backgroundColor: '#B5D8EA' }, 500);
returns $(".block")
is null when a value is selected from the dropdown select box. I have been told that it is to do with: function $(id)
but have no idea how I should modify my code to get it all working, please can anyone help, my js is weak!!!
Thanks
Upvotes: 0
Views: 89
Reputation: 5800
If you are using jQuery then you are overriding the jQuery $
function by declaring.
function $(id) {
return document.getElementById(id);
}
You need to rename that function to something else since the jQuery implementation is a lot more advanced than what you have for your function. You do not have support for getting elements by class name as you are trying to do with the .block
call to your $
function.
Upvotes: 1
Reputation: 41533
.. you have a conflict regarding the $
sign.
$
is a shortcut for jQuery
and you overwrite that shortcut to a different function (document.getElementById
). The bad thing is that you use jquery with the $
shortcut even after you've redefined it.
The solution is either to rename your function to something else :
function getById(id) {
return document.getElementById(id);
}
var material = getById('material');
either use the full jQuery
notation for jQuery objects :
jQuery(".block").animate( { backgroundColor: '#B5D8EA' }, 500);
My oppinion is that if you use jQuery, you can get an element by id quite easy and you don'y need to add another function that takes care of that. ex :
document.getElementById(someId) == $('#'+someId).get(0);
Upvotes: 0
Reputation: 69915
Since you have created $(id)
function $(".block")
will call that method which will look for elementById and wont find anything. So $(".block")
is null and you are calling animate method on a null object which willl throw exception.
Try this
//Remove this method
/*
function $(id) {
return document.getElementById(id);
}
*/
var material = $("#material");
var materialPrices = {"invalid": "from £800.00","1": "£1,200.00","2": "£800.00","3": "£800.00"};
var price = 0;
material.change(function() {
$(".block").animate( { backgroundColor: '#B5D8EA' }, 500);
price = materialPrices[material.options[material.selectedIndex].value];
$('#pprice').html(price);
})
;
Upvotes: 3