2013-05-29 78 views
6

是否有可能通過.html()函數獲取具有更新值屬性的表單的html?如何通過jQuery獲取表單html(),包括更新後的值屬性?

(簡化)HTML:

<form> 
    <input type="radio" name="some_radio" value="1" checked="checked"> 
    <input type="radio" name="some_radio" value="2"><br><br> 
    <input type="text" name="some_input" value="Default Value"> 
</form><br> 
<a href="#">Click me</a> 

jQuery的:

$(document).ready(function() 
{ 
    $('a').on('click', function() { 
     alert($('form').html()); 
    }); 
}); 

這裏是什麼,我試圖做一個例子: http://jsfiddle.net/brLgC/2/

改變的值之後輸入並按下「點擊我」它仍然返回默認值的HTML。

我怎樣才能簡單地通過jQuery獲取更新的HTML?

+0

我不這麼認爲,因爲這些值從來沒有用JS來設置,它們只是被返回,因爲它們被硬編碼爲。你總是可以使用'.serialize()' – tymeJV

+0

,因爲你提醒實際的HTML ...你輸入的內容不會被添加到構建頁面的HTML中。可能需要通過每個項目做一個循環,獲得html和價值,並將其結合起來 – PlantTheIdea

回答

6

如果你真的必須有HTML,實際上你需要更新的「價值」手動屬性: http://jsfiddle.net/brLgC/4/

$(document).ready(function() 
{ 
    $('a').on('click', function() { 
     $("input,select,textarea").each(function() { 
      if($(this).is("[type='checkbox']") || $(this).is("[type='checkbox']")) { 
      $(this).attr("checked", $(this).attr("checked")); 
      } 
      else { 
       $(this).attr("value", $(this).val()); 
      } 
     }); 
     alert($('form').html()); 
    }); 
}); 
+0

我想這是唯一的解決方案然後...但是我想這對單選按鈕和複選框有點棘手...... – santacruz

+0

更新的解決方案收音機和複選框。相同的原則,除了使用checked屬性而不是值。當然,這很麻煩,但通常調用.html()。 – CodingIntrigue

+0

我也只是更新了小提琴,使其工作... http://jsfiddle.net/brLgC/5/ – santacruz

5

RGraham的回答不是爲我工作,所以我把它修改爲:

$("input, select, textarea").each(function() { 
    var $this = $(this); 

    if ($this.is("[type='radio']") || $this.is("[type='checkbox']")) { 
     if ($this.prop("checked")) { 
      $this.attr("checked", "checked"); 
     } 
    } else { 
     if ($this.is("select")) { 
      $this.find(":selected").attr("selected", "selected"); 
     } else { 
      $this.attr("value", $this.val()); 
     } 
    } 
}); 
+0

優秀 - 這可以適當地處理非文本字段 – Tahbaza

0

拉克蘭的作品「幾乎」完美無缺。問題是當表單被保存然後恢復然後再次保存收音機和複選框不取消選中,而是繼續複合。下面簡單的修復。

$("input, select, textarea").each(function() { 
    var $this = $(this); 

    if ($this.is("[type='radio']") || $this.is("[type='checkbox']")) { 
     if ($this.prop("checked")) { 
      $this.attr("checked", "checked"); 
     } else { 
      $this.removeAttr("checked"); 
     } 
    } else { 
     if ($this.is("select")) { 
      $this.find(":selected").attr("selected", "selected"); 
     } else { 
      $this.attr("value", $this.val()); 
     } 
    } 
});