1

I have some simple code for one of my first jquery scripts, I'm trying to call it's function but it keeps saying the function doesn't exist! I have check the spelling and I'm sure I had this working before but I have no idea what's changed.

This is my code: http://jsfiddle.net/spadez/6LLpC/

This is how I'm calling my function:

jQuery(function($){
applyField();
});

Can anyone show me where I went wrong please?

Jimmy
  • 12,087
  • 28
  • 102
  • 192

3 Answers3

5

applyField isn't defined because jsFiddle wraps your code in an onload event handler. So the function is only visible in this event handler.

Choose "no wrap - in <head>" in the left menu :

enter image description here

Alternatively, you could also call your function from this event handler, this would be more coherent.

Note that calling the function isn't enough. If you want your event binding to be effective, change

$(this).on('change', '#apply',function() {

to

$(document.body).on('change', '#apply',function() {

Demonstration

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

After fixing the onload issue, your second problem is this is not a parent of the <select> element, in your function. In order to use that style of .on you need to pass in a parent of the element you're targeting (which can be document).

Change from:

$(this).on('change', '#apply',function() {

To:

$(document).on('change', '#apply',function() {

Also, to prevent hiding all inputs, I suggest using a class instead of selecting $('input'). See fiddle.

Updated fiddle

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • Am I literally going insane?! Why do these examples all stop other inputs from displaying - see here: http://jsfiddle.net/spadez/6LLpC/9/ – Jimmy Jun 24 '13 at 13:01
  • 1
    @Jimmy see my updated fiddle for a fix. It's because you hide all inputs, instead you can use a class to differentiate them. – MrCode Jun 24 '13 at 13:13
1

Approach - 1 => Click here for Demo

JQuery

$(document).ready(function(){
applyField();
});

// Apply Fields
function applyField() {
    $(this).on('change', '#apply',function() {
        var selected = $(this).find(':selected').val(),
            elem = $("#"+selected);
        $("input").addClass('hidden');
        elem.removeClass('hidden');
        $(".donthide").show();
    });
    $("#apply").trigger('change');
};

Approach - 2=> Click here for Demo

JQuery

on needed to execute the function after the DOM is ready.. Check demo.

$(document).ready(function () {
    $(this).on('change', '#apply',function() {
        var selected = $(this).find(':selected').val(),
            elem = $("#"+selected);
        $("input").addClass('hidden');
        elem.removeClass('hidden');
        $(".donthide").show();
    });
    $("#apply").trigger('change');
});
Imad Alazani
  • 6,688
  • 7
  • 36
  • 58