我在html页面上有一个输入框。我知道我只能得到这个值,但我想要整个输入字符串,即但是存在值:
<input id="myInput" value="my entry that I just typed in"/>
我尝试过innerHTML,我尝试过XMLSerializer等等。
var htmlDiv = document.getElementById('myInput'); var str = s.serializeToString(htmlDiv);
值始终为空。
如果您想知道我为什么要这样做 - 这是因为这是我实际上大约60个输入的简单示例,我想要发送到XSLT转换的HTML字符串的所有部分。那部分就像流行音乐一样,我只需要将HTML保持不变。
另一个相关的问题是innerHTML有一个讨厌习惯,即摆脱输入框末尾的/,这会抛弃XSLT翻译。
答案 0 :(得分:0)
试试这个:
console.log(document.getElementById("myInput").outerHTML);
<input id="myInput" value="my entry that I just typed in"/>
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"/>
答案 1 :(得分:0)
我最终执行了以下操作:使用XMLSerializer进行序列化,解决了/问题。我只是从DOM获取值并自己插入它们。
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;
}