2011-02-18 44 views
0

我使用下面的示例映射了輸入的名稱屬性。我必須在map()中添加一個條件語句來確定checkbox是否被選中並返回true或false。但現在我沒有得到選擇選項名稱attr。我覺得它需要更多的代碼編寫。什麼是有效的方式來獲取所有的名稱屬性,並注意檢查複選框。檢查在http://jsfiddle.net/gVHaQ/3/JQuery map()表單輸入

<form> 
    <input type="text" name="name" value="John"/> 
    <input type="text" name="password" value="password"/> 
    <input type="text" name="url" value="http://domain.org/"/> 
    <select> 
     <option name="one">1</option> 
     <option name="two">2</option> 
     <option name="three">3</option> 
    </select> 
    <input type="checkbox"/>    
</form> 
<p></p> 

$("p").append($(":input").map(function() { 
    if ($(this).attr('type') == 'checkbox') { 
     return $(this).attr('checked'); 
    } 
    else { 
     return $(this).attr('name'); 
    } 
}).get().join(", ")); 

的例子這是正在返回
名,密碼,URL,真正

回答

1

也許這就是你想要什麼?

$("p").append($(":input").map(function() { 
    if($(this).is('select')) { 
     return $(this).children('option').map(function() { 
      return $(this).attr('name'); 
     }).get().join(", "); 
    } else if($(this).attr('type')=='checkbox') { 
     return $(this).attr('checked'); 
    } else { 
     return $(this).attr('name'); 
    } 
}).get().join(", ")); 

http://jsfiddle.net/gVHaQ/4/

如果沒有,你應該提供預期的輸出是什麼

編輯:接受的版本

$("p").append($(":input").map(function() { 
    if($(this).is('select')) { 
     return $(this).val(); 
    } else if($(this).attr('type')=='checkbox') { 
     return $(this).attr('checked'); 
    } else { 
     return $(this).attr('name'); 
    } 
}).get().join(", ")); 
+0

呃..我不知道爲什麼你需要map()如果你只需要選擇一個:http://jsfiddle.net/gVHaQ/7/ – 2011-02-18 04:24:47

+0

我會接受你的修改版本。 +1的努力。 – Hussein 2011-02-18 05:20:46

1

如果你仍然可以儘量避免使用地圖兩次想要使用map():http://jsfiddle.net/PmDr9/。但如果你想跳過map(),我想你可能嘗試的一種方法是$('form')。serialize()。在獲得序列化的字符串後,可以使用正則表達式替換不需要的數據。但請注意,您需要爲和提供一個名稱。這裏有一個例子:http://jsfiddle.net/JKuZE/1/。 (注意:我的正則表達式並不是很好,所以也許你可以玩它並得到你想要的結果)。

我不知道第二個實現是你在找什麼,但這是一個建議。