innerHTML with current form values

前端 未结 5 1744
太阳男子
太阳男子 2020-12-17 01:48

Need .innerHTML functionality but with the current form field values including input, select (selected option), and textarea.

So, given:

5条回答
  •  被撕碎了的回忆
    2020-12-17 02:33

    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.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 += '';
        }
        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:

    
    

提交回复
热议问题