weixin_33701251 2015-08-26 10:27 采纳率: 0%
浏览 1873

$(选择器).val()不起作用

I have an option list in my view that gets its options set via ajax in $(document).ready() After this ajax call, I want to set the value of this field to a using .val()

My ajax call is made via the following function:

 function getOrganisations(date, id, blank) {
    $.get(myBaseUrl + "/placements/getTempsOrgsForTimesheets/" + blank + "?date=" + date + "&id=" + id,
        function (data, status) {
            $(".organisation").html(data);
        });
}

This function works fine and populates the list correctly

If, after this I try to set the value of this list, it doesn't work using

$("#org_" + rel).val($("#org_" + rel).attr("aVal"));

If I type this into the console in my browser it works fine and updates the field.

Any Ideas?

<div class="input select"><select name="timeData[organisation_id][thu]" class="organisation table-data table-row-3" aval="38" rel="3" id="org_3"><option value="0"> </option><option value="38">DFS Cork</option></select></div>

I've added

 console.log(document.getElementById("org_" + rel));

just before I try and set the value and got the following

<select name="timeData[organisation_id][thu]" class="organisation table-data table-row-3" aval="38" rel="3" id="org_3"><option value="0"> </option><option value="38">DFS Cork</option></select>
  • 写回答

1条回答 默认 最新

  • weixin_33726318 2015-08-26 10:29
    关注

    I imagine this is an asynchronous issue.

    It works in your browser console because by then the AJAX call would have completed.

    Ensure you're adding the line in the call back function.

    function (data, status) {
       $('#place_' + rel).html(data);
       $("#org_" + rel).val($("#org_" + rel).attr("aVal"));   
    });
    

    If you don't want to add the logic directly into your getOrganisations function you could include a callback parameter instead:

     function getOrganisations(date, id, blank, callback) {
        $.get(myBaseUrl + "/placements/getTempsOrgsForTimesheets/" + blank + "?date=" + date + "&id=" + id,
            function (data, status) {
                $(".organisation").html(data);
                if (typeof callback === 'function'){
                   callback();
                }
            });
    }
    

    Then use it like:

    getOrganisations('date_value', 'id_value', 'blank_value', function(){
       $("#org_" + rel).val($("#org_" + rel).attr("aVal"));  
    }); 
    
    评论

报告相同问题?