2011-11-22 69 views
2

我正在開發一個Web應用程序,其中使用AJAX動態生成/加載相同的HTML表單。如何以多種形式獲取同名的字段的值?

下面是示例形式(幾乎20形成在某時刻加載):

<div class="replybox" id="rbox1"> 
    <cite> 
     <form action="" method="post" id="replypostform">  
      <p> 
       <textarea id="replytxt" name="replytxt" rows="2" cols="43" class="replytextarea"></textarea> 
       <input class="button" type="submit" value="Reply"/> 
      </p>  
     </form> 
    </cite> 
</div> 

,我使用的jQuery驗證插件來驗證它們。表單驗證工作正常,但現在我只需要在提交時獲取textarea的內容,如果我只是使用.val()函數,那麼它將只返回第一個表單的textarea內容。

但我想要點擊用戶點擊的textarea的內容。

這裏是我的jQuery驗證碼:

jQuery("#replypostform").live('mouseover', function(){ 
    jQuery(this).validate({ 
     errorElement:'div', 
      rules: { 
       replytxt:{ 
        required: true 
       } 
      }, 
      messages: { 
       replytxt:{ 
        required: "<div style='color:red'>Please write a reply for posting it.</div>" 
       } 
      }, 
      submitHandler:function(mform){ 

      //here I want get the content of textarea 
     } 
    }); 
}); 

在這裏,我只是做了與鼠標懸停事件一招,以驗證具有相同名稱/ ID和相同的字段中的多個表單。

我的頁面使用AJAX加載大約20個完全相同的表單。

所以建議我如何獲得特定形式的textarea的內容。

-Thanks

+2

一個ID只能在HTML文檔中顯示一次。如果您多次使用此表格,則應使用類別進行標識而不是標識。 – Andrew

回答

0

我想這和它的作品

我知道這是不是一個正確的做法,但這一招所做的工作

這裏是我的jQuery代碼:

textBoxVal=""; 
     jQuery("#replytxt").live('keyup',function(){ 
     textBoxVal=jQuery(this).val(); 

     }); 

然後submitHandler( )

我用「textBoxVal」值。

+0

上面寫在我提供的解決方案中的代碼將會超出jQuery(「#replypostform」)。live('mouseover',函數(){ }然後在submithandler()中只取上面給出的值 – Peeyush

0
$("#replypostform").find("#replytxt").val(); 

還冒泡

jQuery("#replypostform").live('mouseover',function(e){ 
e.stopPropagation(); 

停止活動,並得到文本區域的像

$(this).find("#replytxt").text(); 
+0

我試過這個,但它給了我「未定義」的值,但是謝謝你的回覆 – Peeyush

+0

你的意思是如果你做'console.log($(「#replypostform」)。find(「#replytxt」).val())'你得到undefined在螢火蟲控制檯... – Rafay

+0

是的,我用警報框也試圖也顯示undefined – Peeyush

1

內容試試這個:

//here I want get the content of textarea 
var textareaValue = $("#replytxt", this).val(); 

this提供了觸發mouseover事件的form的上下文以查找#replytxt

+0

我試過這個,但它給了我「未定義」值 – Peeyush

+0

感謝您的答覆,但它不工作:( – Peeyush

-2

嘗試eq()特定元素相匹配:

爲:

$('textarea').eq(0).val() 

編輯:另一個例子的選擇:

第一種形式的文字區域:

$('form:eq(0) textarea').val(); 

第二種形式的第三textarea:

$('form:eq(1) textarea:eq(2)').val(); 
+1

如果用戶徘徊在第二或第三種形式... – Rafay

+0

我只是在編輯答案 – Arda

+0

你是否認真地建議OP爲他的所有表單重複這20次?如果需求改變,他需要100個表單呢?或者如果他們決定讓用戶動態地添加表單? –

相關問題