jQuery .attr('value') returns undefined for text area

醉酒当歌 提交于 2019-12-01 08:06:01

问题


I have a page which dynamically brings in a form via ajax and displays it in a modal div (one that sits above an overlay div that covers the entire page). This is to let them save certain data before a window closes. Everything works great except one thing.

$('#save_close_form').find('*[name]').each(function(index, form_element) {
    var cfe = (form_element.jquery == undefined ? $(form_element) : form_element);
    console.log(cfe.attr('name') + " => " + cfe.attr('value'));
    if (cfe.attr('name').match(/data\[/)) {
        if (cfe.attr('type') == 'checkbox') {
            if (cfe.attr('checked')) {
                map[cfe.attr('name')] = 'on';
            }
            else {
                map[cfe.attr('name')] = '';
            }
        }
        else if (cfe.attr('type') == 'radio') {
            // only get checked radio buttons
            if (cfe.attr('checked')) {
                map[cfe.attr('name')] = cfe.attr('value');
            }
        }
        else {
            map[cfe.attr('name')] = cfe.attr('value');
        }
    }
});

The part in the else {} clause at the end triggers for TextArea and input type="text" elements, but for some reason it always sees cfe.attr('value'); as undefined for the TextArea. I'm using FF6.0 with jQuery 1.6 for this.


回答1:


Try .val() instead of .attr('value').

<textarea> doesn't have a value attribute (the text is between the tags, not in value="") however I believe .val() will retrieve it.




回答2:


For textareas use :

 $("#textareaid").val() or $("#textareaid").html()

instead.

jQuery get textarea text

Set value of textarea in jQuery




回答3:


TextArea does not have an attribute called value...try using val

map[cfe.attr('name')] = cfe.val();



回答4:


textarea does not have a value attribute by default. You should use cfe.val() or cfe.html() to get its content.




回答5:


It's because a textarea doesn't have a value attribute.

Use .val() instead.




回答6:


Ok, so the reason is that jQuery 1.6 makes a distinction between the attribute at creation and your current property value. You've created the textarea without a value attribute more than likely; thus, the initial value is undefined. When you want to pull the defined value, you need to either use .prop('value'), or call the more helpful .val() method.



来源:https://stackoverflow.com/questions/7180659/jquery-attrvalue-returns-undefined-for-text-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!