Skip to content Skip to sidebar Skip to footer

HTML Input - Getting The Value Via InnerHTML Or XMLSerializer

I have an input box on a html page. I know I can get just the value, but I want the entire input string, i.e. , but with the value present: Copy
<input id="myInput" value="my entry that I just typed in"/>
And if you want to add / at the end:

myVar = document.getElementById("myInput").outerHTML;
if(myVar.charAt(myVar.length - 1) !== "/"){
console.log(myVar.slice(0, myVar.length-1) + "/>");
}
<input id="myInput" value="my entry that I just typed in"/>

Solution 2:

I ended up doing the following: Serializing with XMLSerializer, which solved the / problem. And I just got the values from the DOM and inserted them myself.

function htmlCleanup(htmlDiv) {

    //serialize the html.  It will lack the latest user changes in the inputs.
    var s = new XMLSerializer();
    var str = s.serializeToString(htmlDiv);
    var lines = str.split("\n");
    //get all of the inputs in the div
    var inputs = htmlDiv.getElementsByTagName('input');

    //Here we put in the latest values
    var inputIndex = 0;
    for (var i = 0; i < lines.length; i++) {
        var line = lines[i].trim();
        if (line.indexOf('<input') >= 0) {
            var value = inputs[inputIndex].value;
            lines[i] = fixInputValue(line, value);
            inputIndex++;
        }
    }

    str = lines.join('\n');
    //Some other weird aftertaste stuff that needs fixing. <tbody> is added to tables - wrongly.
    //the div at the top is also a problem.
    //Then we turn it all into proper xhtml for the trip back to the server.
    var contents = str.replace('<div xmlns="http://www.w3.org/1999/xhtml" id="documentEditBody">', '');
    contents = contents.replace(/<tbody>/g, '');
    contents = contents.replace(/<\/tbody>/g, '');
    contents = '<?xml version="1.0" encoding="UTF-8"?><html><head></head><body><div>' + contents + '</body></html>';

    return contents;
}

function fixInputValue(input, value) {
    var valuePos = input.indexOf('value');
    var result = "";
    if (valuePos > -1) {
        for (var i = valuePos + 7; i < input.length; i++) {
            var chr = input[i];
            if (chr === '"') {
                var last = input.substring(i + 1, input.length)
                result = input.substring(0, valuePos - 1) + ' value="' + value + '" ' + last;
                break;
            }
        }
    }
    return result;
}

Post a Comment for "HTML Input - Getting The Value Via InnerHTML Or XMLSerializer"