Need .innerHTML functionality but with the current form field values including input, select (selected option), and textarea.
So, given:
if user enters 123, and selects option two, normal f.innerHTML returns:
I'd like f.magicInnerHTML to return:
reflecting the current form values.
回答1:
I think this is what you're looking for: JSFiddle link
In this example, the 'magic' innerHTML of the form is alerted with all changed attributes and their values. I used the jquery getAttributes plugin. Here is the code, other than the plugin code:
function magicHTMLloop($el, s, notfirst){ if (notfirst) { 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); });
This has a few possible edge cases that you might want to consider, such as quotes within the values (which will cause invalid HTML) - but I'm sure you can just escape that yourself, if necessary in your case. As you can see, the output of the magicHTML function is the updated innerHTML:
回答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']; }
回答3:
Try something like this...
$('#f').submit(function(e) { e.preventDefault(); var value = $('#text').val(); if ((value != '') && $('#select').val() == '2') { $('#text').val(value); } });
EDIT: After reading the question again I'm thinking maybe you want to add a block of html in with the value from the previous html form. If that's the case try something along these lines...
$('#f').submit(function(e) { e.preventDefault(); var value = $('#text').val(); if ((value != '') && $('#select').val() == '2') { $(this).after(insertValue(value)); } }); function insertValue(val) { return ""; }