remyremy remyremy - 7 months ago 57
Javascript Question

multiple javascript function in $(document).ready not working

I'm using several functions in the

$(document).ready(function(){
part of the page.

The old functions (highlighted below) worked fine until I added the new one (added at the top). Since then they do not work anymore.
After some testing I realized that if I switched position between the old and the new functions, only the one placed at the top will work.

I'm using the new function on a different page than the old ones but both are included in my javascript file and in the footer.

home.js :

$(document).ready(function(){

// NEW FUNCTION (up/down arrows)
var nextListitem;
var noOfListItems = $("#select > option").length-1;
var curListItem = $("#select")[0].selectedIndex;
$("#upArrow").on("click", function(){
// Decrement the selection by one, unless that will be less than zero, then go to the last option
nextListitem = (curListItem-1 < 0) ? noOfListItems : curListItem-1;
curListItem = nextListitem;
$("#select")[0].selectedIndex = nextListitem;
});


// OLD FUNCTIONS (count characters left in textarea)
window.com_domain = window.com_domain || {};
$(':text,#resort_description').click(function(){
current_input_val = $(this).val();
$(this).select();
}).focusout(function(){
if ($(this).val() == '') {
$(this).val(current_input_val);
}
});
// more old functions


});



TypeError: $(...)[0] is undefined

var curListItem = $("#select")[0].selectedIndex;


Is displayed if I load the page using the "old functions".

This is how my footer looks like (Jquery is called before) :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script src="js/bootstrap-hover-dropdown.min.js'>"></script>
<script src="js/home.js" type="text/javascript"></script>

Answer

If there's no element with id="select" on the page, $("#select") will be an empty collection, so $("#select")[0] will be undefined. You can't access undefined.selectedIndex, so you get an error at that line and nothing after it runs. It has nothing to do with having multiple functions in the ready block.

You should check whether the element exists first.

if ($("#select").length > 0) {
    var nextListitem;
    var noOfListItems = $("#select > option").length-1;
    var curListItem = $("#select")[0].selectedIndex;
    $("#upArrow").on("click", function(){
         // Decrement the selection by one, unless that will be less than zero, then go to the last option
        nextListitem = (curListItem-1 < 0) ? noOfListItems : curListItem-1;
        curListItem = nextListitem;
        $("#select")[0].selectedIndex = nextListitem;
    });
}
Comments