2011-03-18 100 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()); 
    } 
});