2011-06-27 8 views
0

我有一個表單在我的頁面上重複了很多次(它在論壇上)。 我已經建立了某種jQuery的功能基本上做到以下幾點:當我的頁面上有很多表單時,在給定表單上的jquery函數

當選擇與價值「定製」 Select選項,

  • 隱藏選擇
  • 顯示一個div textarea的內並將其聚焦

當輸入是模糊和空

  • 隱藏輸入
  • 通過顯示「復位」的選擇,並選擇它的默認(空值)選項

問題是,我做了它一個形式我的網頁上。它的工作原理。 但是當我在一個多形式的測試頁面上嘗試它時,我的功能 - 隱藏每個表格的選擇 - 在裏面顯示一個帶有textarea的div並將其聚焦於每個表單。

這當然不是我想要做的。

問題:如何使這些函數形式特定?

這是我的代碼如下。

JQUERY

$("div[name=customInput]").hide(); 
$("select[name=motifs]").show(); 

$("select[name=motifs]").change(function() 
{ 
    if($("select[name=motifs]").val() == "custom") 
    { 
     $("select[name=motifs]").hide(); 
     $("div[name=customInput]").show(); 
     $("textarea[name=customMotif]").focus(); 
    } 
}); 
$("textarea[name=customInput]").blur (function() 
{ 
    if(!$(this).val()) 
    { 
     $("div[name=customMotif]").hide(); 
     $("select[name=motifs]").show(); 
     $("select[name=motifs] option[name=motif]").attr("selected", "selected"); 
    } 
}); 

$('textarea[name=customMotif]').keyup(function() { 
      var len = this.value.length; 
      if (len >= 150) { 
       this.value = this.value.substring(0, 150); 
      } 
      $('span[name=charLeft]').text(150 - len); 
}); 

HTML

<form action="note.php" method="post" name="notation" id="notation"> 
<select name="motifs"> 
     <option value="" name="void">Motif</option> 
     <option value="custom" name="custom">Custom</option> 
     <option value="1">1</option> 
     <option value="2">2</option> 
     <option value="3">3</option> 
    </select> 
    <div name="customInput"> 
     <textarea cols="30" name="customMotif"/> 
     </textarea> 
     <span name="charLeft">150</span> Characters left </div> 
</form> 

感謝您的幫助;我是初學者,仍然在學習如何做正確的事情。任何幫助表示讚賞。

+0

您需要爲每個表單分別設置不同的ID或名稱(例如,如果這是一個包含帖子的表單,則可以將帖子ID附加到表單的ID中)。然後在你的JS中,你可以將你的邏輯應用到$(#requirediv) –

+0

謝謝;以及如何將我的邏輯動態應用於正確的ID?是不是有這個。語法或我不知道可以做到的事情? – Baptiste

回答

0

像這樣的東西應該工作:

$("select[name=motifs]").change(function() 
{ 
    if($(this).val() == "custom") 
    { 
     var $parentForm=$(this).closest("form"); 

     $parentForm.find("select[name=motifs]").hide(); 
     $parentForm.find("div[name=customInput]").show(); 
     $parentForm.find("textarea[name=customMotif]").focus(); 
    } 
}); 

closest會得到滿足的選擇最近的祖先。在這種情況下,選擇包含在其中的表單。然後使用find將僅在父窗體中找到選擇器。

作爲一個附註,ID應該始終是唯一的。

+0

它做得很好,謝謝:) – Baptiste

相關問題