2011-04-28 3 views
6

.inner HTML 기능이 필요하지만 input, select (선택한 옵션) 및 textarea를 포함한 현재 양식 필드 값이 필요합니다.현재 양식 값이있는 innerHTML

그래서, 주어진 : 사용자가 123을 입력하고 두 번째 옵션을 선택

<form id=f> 
    <input type=text name=x /> 
    <select name=y> 
    <option value='1'>one</option> 
    <option value='2'>two</option> 
    </select> 
</form> 

경우, 정상 f.innerHTML 반환 : 나는 f.magicInnerHTML 반환하고 싶습니다

<input type=text name=x /> 
<select name=y> 
    <option value='1'>one</option> 
    <option value='2'>two</option> 
</select> 

:

<input type=text name=x value='123' /> 
<select name=y> 
    <option value='1'>one</option> 
    <option value='2' selected>two</option> 
</select> 

현재 양식 값을 반영합니다.

+1

는 일부 HTML을 제공하십시오 수/귀하의 질문에 도움이되는 javascript? – samandmoore

답변

1

완전히 만족하지, 그러나 이것은 대부분 작동합니다

$('input:text, input:hidden, input:password').each(function() { 
    var v=this.value; 
    $(this).attr("magicmagic_value",v).removeAttr("value").val(v); 
}); 
$('input:checkbox,input:radio').each(function() { 
    var v=this.checked; 
    if(v) $(this).attr("magicmagic_checked","checked"); 
    $(this).removeAttr("checked"); 
    if(v) this.checked=true; 
}); 
$('select option').each(function() { 
    var v=this.selected; 
    if(v) $(this).attr("magicmagic_selected","selected"); 
    $(this).removeAttr("selected"); 
    if(v) this.selected=true; 
}); 
$('textarea').each(function() { 
    $(this).html(this.value); 
}); 

var magic=$('form').html().replace(/magicmagic_/g,""); 

$('[magicmagic_value]').removeAttr('magicmagic_value'); 
$('[magicmagic_checked]').attr("checked","checked"). 
    removeAttr('magicmagic_checked'); 
$('[magicmagic_selected]').attr("selected","selected"). 
    removeAttr('magicmagic_selected'); 

alert(magic); 
0

이 같은 형태의 입력 값을 얻을 수 있습니다 :

<input type="text" id="name" value="Paul" /> 

<script type="text/javascript"> 
    $("#name").val(); 
</script> 
+3

''태그? 뭐야 ...? ':)' –

1

이런 식으로 뭔가를 시도 ...

$('#f').submit(function(e) { 
    e.preventDefault(); 
    var value = $('#text').val(); 
    if ((value != '') && $('#select').val() == '2') { 
     $('#text').val(value); 
    } 
}); 

데모 : http://jsfiddle.net/wdm954/nEXzS/


편집 : 후 다시 질문을 읽고 나는 아마 이전 HTML 폼의 값으로 HTML 블록을 추가하려고한다고 생각하고있다. 나는 이것이 당신이 찾고있는 무엇을 생각 http://jsfiddle.net/wdm954/nEXzS/1/

4

:이 예에서 JSFiddle link

의 '마법 그런 경우에는 ...

$('#f').submit(function(e) { 
    e.preventDefault(); 
    var value = $('#text').val(); 
    if ((value != '') && $('#select').val() == '2') { 
     $(this).after(insertValue(value)); 
    } 
}); 

function insertValue(val) { 
    return "<input type=text name=x value='" + val + "' /><select name=y><option value='1'>one</option><option value='2' selected>two</option></select>"; 

} 

데모이 라인을 따라 뭔가를 시도 '폼의 innerHTML은 변경된 모든 속성과 값으로 경고됩니다. jquery getAttributes plugin을 사용했습니다. 여기에 플러그인 코드 이외의 코드는 다음과 같습니다

function magicHTMLloop($el, s, notfirst){ 
    if (notfirst) { 
     s += '<' + $el.get(0).tagName.toLowerCase(); 

     var attrs = $.getAttributes($el); 

     for (var i in attrs){ 
      s += ' ' + i + '="' + $el.attr(i) + '"'; 
     } 
     s += '>'; 
    } 

    $el.children().each(function(){ 
     s += magicHTMLloop($(this), '', true); 
    }); 

    if ($el.children().length && notfirst){ 
     s += '</' + $el.get(0).tagName + '>'; 
    } 
    return s; 
} 

function magicHTML($el) { 
    return magicHTMLloop($el, '', false); 
} 

// This is the example usage: 

$('input').change(function(){ 
    var v = magicHTML($('form')); 
    alert(v); 
}); 

이는 (잘못된 HTML의 원인이됩니다) 값 내에서 따옴표로 당신이 고려할 수있는 몇 가지 가능한 가장자리 경우가 있습니다 -하지만 난 필요한 경우 자신의 것으로 탈출 할 수 있는지 확인하십시오. 당신이 볼 수 있듯이, magicHTML 함수의 출력은 업데이트 innerHTML을이다 ​​: 그것

<input type="text" name="x" value="this is the changed value"> 
2
/** 
* HTML content along with the values entered by the user for form elements 
* (unlike the default browser behavior) 
* 
* @author i.carter euona.com 
* @version 1.0 2012-04-14 
* @return innerHTML (or outerHTML) 
* @param e HTMLElement 
* @param t String: "outer" OR "inner" (default) 
* 
* @effect changes defaultValue 
* @tested FF11,IE10,GC 
*/ 
function getHTML(e,t) 
{ 
    if(typeof t=='undefined') var t='inner'; 
    switch(e.nodeName.toUpperCase()) 
    { 
     case 'INPUT': 
      if(e.type=='checkbox' || e.type=='radio') 
      { 
       e.defaultChecked=e.checked; 
       break; 
      } 
     case 'TEXTAREA': 
      e.defaultValue=e.value; 
      break; 
     case 'SELECT': 
      var o=e.options,i=o.length; 
      while(--i > -1) 
       o[i].defaultSelected=o[i].selected; 
      break; 
     default: 
      var x=e.getElementsByTagName('input'),i=x.length; 
      while(--i > -1) getHTML(x[i],t); 
      x=e.getElementsByTagName('textarea');i=x.length; 
      while(--i > -1) getHTML(x[i],t); 
      x=e.getElementsByTagName('select');i=x.length; 
      while(--i > -1) getHTML(x[i],t); 
    } 
    return e[t+'HTML']; 
} 
+1

고마워. 이것은 jsPDF 및 html2pdf 라이브러리를 사용하여 채워진 양식에서 pdf 파일을 생성하는 데 필요한 것입니다. –