我有一個表格有幾個輸入,並在他們旁邊(左邊)有一個相應的標籤。jquery:立即獲得之前的兄弟或元素的父親
當我驗證輸入時,我想顯示一個消息,使用相應的標籤來告訴哪個輸入錯誤。
我有一個顯示爲我想要的唱片公司工作的腳本,但它打破了,如果我的輸入是不是標籤的直接兄弟,但兄弟姐妹的孩子,而不是...
這裏是爲了說明的代碼:
HTML:
<form>
<label class="autoFormLabel obligatorio">* calle : </label>
<input id="calle2" class="autoForm obligatorio" type="text" value="" name="calle2">
<br>
<label class="autoFormLabel obligatorio">* CP : </label>
<input id="CP" class="autoForm obligatorio" type="text" value="" name="CP">
<br>
<label id="label_colonia" class="autoFormLabel obligatorio">* Colonia : </label>
<span id="span_combo_colonias">
<select id="Colonia" class="obligatorio autoForm" name="Colonia">
<option selected="" value="0">-- seleccione --</option>
<option value="1">one</option>
<option value="2">two</option>
</select>
</span>
<br>
<label class="autoFormLabel obligatorio">* Delegacion : </label>
<input id="delegacion" class="autoForm obligatorio" type="text" value="" name="delegacion" >
<br>
<input type="button" id="val" value="Val" />
</form>
JS:
function validate(){
$(":input.obligatorio:enabled").each(function(i, el){ // solo considerar los enableds
if($(this).val() == "" || $(this).val() == "0" || $(this).val() == 0){
label = $(this).prev("label").html(); //A: works for all but select
//label = $(this).parent().prev("label").html(); //B: works for select, but not the others
//label = $(this).closest("label").html(); //C: why doesn't work for select?
alert("El campo:\n\n"+label+"\n\nno puede ir vacio");
$(this).focus();
return false;
}
});
}
所有的輸入都有一個對應的兄弟標籤,除了<select>
,它在<span>
之內,它本身就是其標籤的兄弟。
我選擇label = $(this).prev("label").html();
作品完美excpet的選擇所有的輸入,因爲它包含一個跨度內(我需要它這樣的,因爲這樣的選擇是動態的,並得到通過AJAX插入這樣的跨度內)
我知道我可以使它與選擇案例的另一個選擇器一起工作,如下所示:label = $(this).parent().prev("label").html();
但理想情況下,我希望只有一個選擇器可以獲取所有標籤,而不管其相應輸入的深度如何。我也試過用.closest()選擇器,但它不起作用,我不知道爲什麼,但我認爲它沒有,因爲標籤不是select的上升(它是一個它的父母的兄弟,[讓我們說一個'叔叔]])
那麼哪個選擇器可以用於所有情況下,儘管是父母,兄弟姐妹,父母兄弟或即使是盛大的盛大父母,無論...(我可以有一個輸入埋在其標籤旁邊的幾個跨度內,或其他任何東西)
換句話說,我如何遍歷DOM「上方和左邊」並獲得選擇者的第一個選擇,無論他們是父母還是他們 兄弟姐妹?
@nirmal,小提琴已經存在。 –
@Nimal問題完整清晰 – mplungjan
https://gist.github.com/ryankirkman/6630488 – mplungjan