开发者

Different behavior with .val() and .attr("value") using ajax return data on a clone()'d but uninserted element

开发者 https://www.devze.com 2023-03-25 12:08 出处:网络
As the title says, I\'m trying to set the value of a .clone()\'d form field using the results of a $.getJSON() request.All of the return values have the same key as the name attribute of the form fiel

As the title says, I'm trying to set the value of a .clone()'d form field using the results of a $.getJSON() request. All of the return values have the same key as the name attribute of the form field they belong to.

Naturally, I tried to use .val("foo") to deal with cross-browser/field type discrepancies but it wouldn't work. Oddly, .attr("value","foo") does.

Any ideas? Is this expected behavior, or an undocumented quirk? Here is the relevant code snippet:

function showSites(){
$.getJSON("process.php?action=showSites", function(data) {
    var items = [];
    $.each(data.sites, functi开发者_如何学编程on(key, val) {  
        var $form = $("#addSiteForm").clone(); 
        var buttons = '<button id="getCert" class="button" href="getCert.php?id=' + val.id + '">Get Cert</button>'
            + '<button id="updateSite" class="button" href="process.php?action=updateSite&id=' + val.id + '">Update Site</button>'                                                                              
            + '<button id="deleteSite" class="button" href="process.php?action=deleteSite&id=' + val.id + '">Delete Site</button>';

        // set siteId
        $form.find("input[name=siteId]").attr("value",val.id);

        // change values
        $.each(val, function(i,v){
            $form.find("[name="+i+"]").val(v);
        });

        items.push('<h3><a href="#">' + val.name + '</a></h3>');
        items.push("<div class='site'>");
        items.push("<form class='siteForm' id='"+val.id+"'>");
        items.push($form.html());
        items.push("</form>");
        items.push(buttons);
        items.push("</div>");   
    });
    var foo = items.join('');
    $("#sites").prepend(foo).accordion("destroy").accordion();                  
});
});


You can use .val() property in input tags( text box, textarea,..) only.

attr("attrname","value") this is used to set value to any tags. You can set some dummy attr in div tag and retrieve value attr("attrname");

0

精彩评论

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