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.
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.
For textareas use :
$("#textareaid").val() or $("#textareaid").html()
instead.
TextArea does not have an attribute called value...try using val
map[cfe.attr('name')] = cfe.val();
textarea does not have a value attribute by default. You should use cfe.val() or cfe.html() to get its content.
It's because a textarea doesn't have a value attribute.
Use .val() instead.
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