jquery: get label value onsubmit
<form id="test" onsubmit="return checkParams();" method="post" action="">
<div class="input-inside-label">
<label for="loc">12345</label>
<input class="grab-label" value="" type="text" name="loc" id="loc">
</div>
</form>
my input value is empty. However I don't want it to be submitted empty. When the form is submitted I want it to g开发者_如何学Gorab the value of the label and then submit it.
However I have quite a few problems doing that. Any idea what I'm doing wrong here?
$('#test').submit(function(e) {
if ( $(this).children('.grab-label').val() == '' ) {
$(this).children('.grab-label').val($(this).closest('label'));
}
});
regards matt
First, by invoking .children()
help you'll only query for direct children from the root node. In this case, it can't find .grab-label
since it's not a direct child.
Use .find()
help there. Furthermore, .closest()
only looksup parent-nodes. In your context it can't find the desired node for that reason. You could use .prev()
help starting from the input
node.
$('#test').submit(function(e) {
var $input = $(this).find('.grab-label');
if ( !$input.val().length ) {
$input.val($input.prev().text());
}
});
closest
gives you an ancestor. But label
is a sibling of the input field. Use .prev()
. children
will only search in the next level of the DOM, not all descendants. Use .find()
instead:
$(this).find('.grab-label').val($(this).prev('label').text());
(you also need .text()
)
Or change your HTML to:
<div class="input-inside-label">
<label for="loc">12345
<input class="grab-label" value="" type="text" name="loc" id="loc">
</label>
</div>
But then it would be easier to use .parent()
:
$(this).find('.grab-label').val($(this).parent().text());
you have to get the .html() from that <label>
$('#test').submit(function(e) {
if ( $(this).children('.grab-label').val() == '' ) {
$(this).children('.grab-label').val($(this).closest('label').html());
}
});
精彩评论