开发者

unable to set the html content in a custom jQuery function

开发者 https://www.devze.com 2022-12-13 05:00 出处:网络
I have a jQuery function called \"bindServingSizes\" which I call like this $(servingsizes).bindServingSizes(i开发者_如何学JAVAngredientid);

I have a jQuery function called "bindServingSizes" which I call like this

$(servingsizes).bindServingSizes(i开发者_如何学JAVAngredientid);

Where "servingsizes" is a valid drop down list control.

jQuery.fn.bindServingSizes = function(ingredientid) {

    $.getJSON("/serving_sizes?ingredientid=" + ingredientid, function(j) {

        var options = "<option value=''>Please select a serving size</option>";
        for (var i=0; i < j.length; i++)
          options += '<option value="' + j[i].serving_size.id + '">' + j[i].serving_size.name + '</option>';

        $(this).html(options);
    });
  };

I do get data back from the server and I am able to see what is in the "options" variable by displaying it on the page. However, I am not able to set the html contents to the element. What could I be missing?

Thanks


The problem is that $(this) in your callback function from $.getJSON is no longer the select box. Try this which creates a variable which stores the reference to the select box.

jQuery.fn.bindServingSizes = function(ingredientid) {
    var $this = $(this);

    $.getJSON("/serving_sizes?ingredientid=" + ingredientid, function(j) {

        var options = "<option value=''>Please select a serving size</option>";
        for (var i=0; i < j.length; i++)
          options += '<option value="' + j[i].serving_size.id + '">' + j[i].serving_size.name + '</option>';

        $this.html(options);
    });
  };


When you call $(this) you call $.getJSON object. Add outside it some var container = $('containerId'); and execute conainer.html(opions);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号