How to get "this" form content by name?
In the following example I get title
from this
form using html id=title
.
How do I do the same, but instead of using ID then using name?
$(document).ready(function(){
$('form').live('submit', function(){
开发者_运维问答var aform = $('form[name="create_form"]');
// get the entire form
var form = $(this);
// get form title field by ID
var title = this.elements.title.value;
// get selected radio button using name instead if ID
var type = $(this).find('input:radio[name="ctype"]:checked').val() || '';
alert(title);
In the case of the radio button, is it gotten by name, but I can't figure out how to translate that syntax to a normal form field of
<input name="title" id="55544_title" type="text" />
in this line
// get form title field by ID
var title = this.elements.title.value
you are not getting it with the id, you are getting it with the name attribute, so in some way you are already doing it correctly
Why can't you just do:
var title = $('input[name=title]',form).val();
instead of:
var title = this.elements.title.value
$(this).find(":input[name='title']");
should work
> // get form title field by ID
> var title = this.elements.title.value;
Within the listener, this
is the form (since the listener is attached to the form). If there is more than one element with a name of 'title' then:
this.elements.title
will be a collection. It is that object that you are trying to access the value property of. If you want a reference to the radio button within the collection that is checked, then:
$(this).find('input:radio[name="ctype"]:checked')
will return a jQuery object with your input as its only element, so:
var checkedButton = $(this).find('input:radio[name="ctype"]:checked')[0];
should do the trick (if one is selected). Or you can iterate over the elements returned by this.elements.title
to find the selected one:
var checkedButton, buttons = this.elements.title;
if (buttons.tagName) {
checkedButton = buttons;
} else {
for (var i=0, iLen=buttons.length; i<iLen; i++) {
if (buttons[i].checked) {
checkedButton = buttons[i];
}
}
}
精彩评论