2011-03-18 111 views
0
<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> 

我的输入值为空。不过,我不希望它被提交为空。当表单提交时,我希望它抓取标签的值,然后提交。jquery:获取标签值onsubmit

但是我这样做有很多问题。任何想法我在这里做错了吗?

$('#test').submit(function(e) { 
    if ($(this).children('.grab-label').val() == '') { 
     $(this).children('.grab-label').val($(this).closest('label')); 
    } 
}); 

问候亚光

回答

4

首先,通过调用.children()help你只能从根节点直接儿查询。在这种情况下,它不能找到.grab-label,因为它不是一个直接的孩子。

那里使用.find()help。此外,.closest()只查找父节点。在你的上下文中,由于这个原因它找不到所需的节点。您可以使用从input节点开始的.prev()help

$('#test').submit(function(e) { 
    var $input = $(this).find('.grab-label'); 

    if (!$input.val().length) { 
     $input.val($input.prev().text()); 
    } 
}); 
3

closest给你一个祖先。但是label是输入字段的兄弟。使用.prev()children只会在DOM的下一级搜索,而不是所有的后代。使用.find()代替:

$(this).find('.grab-label').val($(this).prev('label').text()); 

(你还需要.text()

或更改您的HTML:

<div class="input-inside-label"> 
    <label for="loc">12345 
     <input class="grab-label" value="" type="text" name="loc" id="loc"> 
    </label> 
</div> 

但那么这将是更容易使用.parent()

$(this).find('.grab-label').val($(this).parent().text()); 
1

你必须得到。html( ) from <label>

$('#test').submit(function(e) { 
    if ($(this).children('.grab-label').val() == '') { 
     $(this).children('.grab-label').val($(this).closest('label').html()); 
    } 
});