HTML input - getting the value via innerHTML or XMLSerializer - javascript

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:
<input id="myInput" value="my entry that I just typed in"/>
I have tried innerHTML, I have tried XMLSerializer, etc.
var htmlDiv = document.getElementById('myInput');
var str = s.serializeToString(htmlDiv);
The value is always empty.
If you are wondering why I want to do this - it is because this is my simple example of what in reality is about 60 inputs, all part of an HTML string that I want to send to XSLT translation. That part works like gangbusters, I just have to get it HTML with values intact.
Another related problem is that innerHTML has a nasty habit of getting rid of the / at the end of the input box, which throws off the XSLT translation.

Try this:
console.log(document.getElementById("myInput").outerHTML);
<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"/>

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;
}

Related

Highlight the textContent or innerText of an element containing other elements also based on user's searchedWords Using Pure Javascript

How to highlight all the words that the user is searching without affecting the text of the display and the attributes inside the elements. I have tried some approaches but there is a problem as described below. Please help. Thank you. Keep safe and healthy.
<input type='text' id='search' onkeyup="highlight(this.value)">
<p id='WE1'><b>WE</b>wE & theythem and We<span id="we2">we only.</span></p>
function highlight(searchedWords) {
var p = document.getElementById("WE1");
var words = searchedWords.trim().split(" ");
for (var i=0; i < words.length; i++) {
var word = words[i].trim();
/*
searchedWords = "We Only";
trial#1: use replaceAll
p.innerHTML = p.innerHTML.replaceAll(word, "<mark>" + word + "</mark>");
Issues:
1) replaceAll does not work in other browsers
2) It highlights also the tag attributes containing the searchedWords
3) It is case sensitive, it only highlights the exact match, though I've addressed this using this:
var str = p.innerHTML;
for (var j=0; j < words.length; j++) {
var x = words[j].trim(), string = str.toLowerCase();
while (string.lastIndexOf(x) > -1) {
str = str.substring(0, string.lastIndexOf(x)) + "<mark>"
+ str.substr(string.lastIndexOf(x), words[j].length) + "</mark>"
+ str.substring(string.lastIndexOf(x) + words[j].length, str.length);
string = string.substring(0, string.lastIndexOf(x));
}
}
p.innerHTML = str;
4) Changing .toLowerCase() also changes the display to lower case
var x = p.innerHTML.toLowerCase, word = word.toLowerCase;
p.innerHTML = x.replaceAll(word, "<mark>" + word + "</mark>");
trial#2:
p.innerHTML = p.innerHTML.replace(new RegExp(words[i], "gi"), (match) => `<mark>${match}</mark>`);
Issues:
1) OK, it is NOT case sensitive, it highlights all the searchedWords and the display is OK
2) But, it highlights also the tag attributes containing the searchedWord, anchor tags are affected
I tried also using p.childNodes, nodeValue, textContent so that the attributes
containing the searchedWord are not affected yet it only inserts the words
<mark>SearchedWord</mark> and the searchedWord is not highlighted.
*/
}
}
replaceAll is a new feature es2021. As for today it's incompatible with IE.
I found you something that might work. Please have a look and tell me if you still have problems How to replace all occurrences of a string in JavaScript on stackoverflow
I made a workaround by reading the innerHTML from right to left and disregarding the match if there is a "<" character to the left, which means that the match is inside a tag. Although the solution below seems to be manual, yet it works for me for now.
<!DOCTYPE html>
<html>
<input type="text" onkeyup="highlight(this.value)">
<p>Hi! I'm feeling well and happy, hope you too. Thank you.</p>
<p id="WE1"><b>WE</b> wE, We, we.
Only you.
<span id="wemark">mark it in your calendar.</span>
</p>
<script>
function highlight(searchedWords) {
var p = document.getElementsByTagName('p');
for (var i=0; i<p.length; i++) {
p[i].innerHTML = p[i].innerHTML.replace(new RegExp("<mark>", "gi"),(match) => ``);
p[i].innerHTML = p[i].innerHTML.replace(new RegExp("</mark>","gi"),(match) => ``);
}
var words = searchedWords.trim();
while (words.indexOf(" ") > -1) {words = words.replace(" "," ")}
if (!words) return;
words = words.split(" ");
for (var i = 0; i < p.length; i++) {
p[i].innerHTML = mark(p[i].innerHTML, words)
}
}
function mark(str, words) {
try {
for (var j=0; j < words.length; j++) {
var s = str.toLowerCase(),
x = words[j].toLowerCase().trim();
while (s.lastIndexOf(x) > -1) {
var loc = s.lastIndexOf(x), y = loc;
while (y > 0) {
y = y - 1;
if (s.substr(y,1)=="<"||s.substr(y,1)==">") break;
}
if (s.substr(y, 1) != "<") {
str = str.substring(0, loc) + "<mark>"
+ str.substr(loc, x.length) + "</mark>"
+ str.substring(loc + x.length, str.length);
}
s = s.substring(0, loc-1);
}
}
return str;
} catch(e) {alert(e.message)}
}
</script>
</html>

I am not able to write javascript array variables values into CSV file in a Given pattern

I have three javascript variables by name Area, Device and Problem. I want to store values of these variables into a CSV file one by one as given in the image attached with this and download that sheet on click of download button.Both jsp and javascript are in same file.i have tried the below so far.
Sample.jsp
<form>
<input type="BUTTON" id="DownloadBtn" value="Download">
</form>
<script type="text/javascript">
var Area=["Area1","Area2"];
var Device=[["device1","device2"],["device3","device4"]];
var Problem=[[["problem1","problem2"]],[["problem3","problem4"]],[["problem5","problem6"]],[["problem7","problem8"]]];
$("#DownloadBtn").click(function() {
var resp=confirm("Do You Want To Download?");
if(resp){
var last = '';
for (var i = 0; i < Area.length; i++) {
var first = Area[i];
for (var j = 0; j < first .length; j++) {
var second= device[j];
for(var k=0;k<second.length;k++){
var third=problem[k];
var value= third.replace(/"/g, '""');
if (value.search(/("|,|\n)/g) >= 0)
value= '"' + value+ '"';
if (k > 0)
last += ',';
last += value;
}
}
last += '\n';
}
var anchor= document.createElement('a');
anchor.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(last ));
anchor.setAttribute('download', 'sample.csv');
anchor.click();
}
});
</script>
Please suggest me any kind of changes or modification needed to get desired pattern. how this can be achieved as required in the image. Comment below for any kind of clarification on this question. Any suggestion would be welcome.

jQuery Loop through text content while keeping wrapping html tags

I have the following javascript function that aims to append a BIDI code to text that matches a specific criteria.The problem with the current function is that it works great with text only content but is problematic with content that has HTML Content. To summarize, I am splitting the text into words and checking if any of the characters in each word is matching a certain criteria to append the BIDI code to it.
The current status:
<div>This is the text that I am processing</div> //This works great
<div><span>This is the text</span><p>that I am processing</p></div> // This doesn't work well.
I want the function to work is for the text but also to keep the wrapping HTML tags in their place in order to keep etc....
function flipper(flipselector) {
var pagetitle = $(flipselector);
var text = pagetitle.text().split(' '); //I know that I am using text function here but .html didn't work either
var newtext="";
for( var i = 1, len = text.length; i < len; i=i+1 ) {
//text[i] = '<span>' + text[i] + '</span>';
newstring="";
if (matches = text[i].match(/\d/))
{
var currentstring=text[i];
for (var x = 0, charlen = currentstring.length; x < charlen; x++) {
if (matches = currentstring[x].match(/\d/)) {
varnewchar=currentstring[x];
}else {
varnewchar= "‏" + currentstring[x];
}
newstring=newstring + varnewchar;
}
} else {
newstring= text[i];
}
newtext=newtext + " " + newstring;
}
pagetitle.html(newtext);
}

Cannot manage to use innerHTML

I'm new to Stack Overflow and also in JavaScript. So, first of all, hello to everyone and thanks in advance for your help.
I'm using Incomedia Website X5 Evolution to create a website. On one of the page, I want to populate a table with data from a server. So, I've created a table and insert in each cell this HTML code:
<!--#0000,0000-->
Values are representing the row and the column. I managed to write a javascript to change the value of each cell. But when I want to replace the content of the HTML pahe using innerHTML, it does not work. Nevertheless, everything seems correct as the old and the new html content is the same. Even if I just use again the original variable, it still doesn't work.
Could you tell me where is the problem please ?
Here the javascript code:
<script>
var i;
var div = document.getElementById('imTableObject_1');
div = document.getElementsByTagName('table');
var htmlContent = div[0].innerHTML;
var newHtmlContent = div[0].innerHTML;
var test = div[0].innerHTML;
var row,col;
//I can't understand why the scrip stop running at this line. I didn't change anything...
div[0].innerHTML = newHtmlContent ;
for (i=htmlContent.length - 5; i > -1; i--) {
if(htmlContent.charAt(i)=='#') {
//alert(i);
//alert(htmlContent.substring(i+6,i+10));
row = parseInt(htmlContent.substring(i+1,i+5));
col = parseInt(htmlContent.substring(i+6,i+10));
newHtmlContent = insertText(row,col,newHtmlContent,i);
};
};
alert(div[0].innerHTML);
alert(newHtmlContent );
//This does not work
div[0].innerHTML = newHtmlContent ;
alert("Done !");
function insertText (row, col, text, index) {
var length;
var newText;
length = getTextLength (text,index + 13);
//alert(htmlContent.substring(index+13,index+13+length));
newText = text.substring(0,index+13);
newText += "Titi too !";
newText += text.substring(index+13+length,text.length);
//alert(newText);
return newText ;
}
function getTextLength (text,startIndex) {
var i = 0;
for(i = startIndex ; i < text.length ; i++) {
//alert(text.substring(i,i+7));
if(text.substring(i,i+7) == "</span>") {
return i - startIndex ;
};
};
return -1;
}
</script>
You set:
var newHtmlContent = div[0].innerHTML;
And then:
div[0].innerHTML = newHtmlContent ;
You're setting its content to what its content already was. Hence, no change occurs.
Change the 3rd row to
div = document.getElementsByTagName('td');
to look for <td> tags instead of <table> tags. <table>s can't directly store text data so I guess their innerHTML doesn't work as expected either.
I managed to get it working here: http://jsfiddle.net/mgabor/ZMaW6/1/

sending infinity number of checkbox values to text

I have a table with n number of rows with checkboxes and a what i want to do is if i select a checkbox the value should go to the text area, so i stored all elements in an array first, but it isnt happening, as you can see i added alerts as well to check it out. please help.
window.onload = function () {
var oRows = document.getElementById('rnatable').getElementsByTagName('tr');
var iRowCount = oRows.length;
alert('Your table has ' + iRowCount + ' rows.');
var i = 0;
cb = new Array(iRowCount);
while (i <= iRowCount) {
var id = 'check'+ i;
cb[i] = document.getElementById(id);
i++;
}
//alert('Your table has ' + cb[i].value + ' rows.');
for(var a=0; a < iRowCount; a++) {
var fasta = document.getElementById('fasta');
if(cb[a].checked) {
fasta.value = cb.value + ",";
};
};
}
Are you seeing an error in the console? I suspect that when while (i <= iRowCount) runs when i === iRowCount that document.getElementById(id) isn't yielding a result, and that then when you use that value, bad things happen.
Also, each lap through the fasta loop overwrites the previous value. You probably want something like fasta.value += cb.value + ","; instead.

Categories