-1

Here is my code. I am using role="textbox" and getting value from it. But, when I enter more than one line of text in the textbox, it gives me the value in multiple lines. How do I get this value in a single line?

function getText() {
  let text = document.querySelector('[role=textbox]').innerText;
  alert(text);
}
.textbox{
border: 1px solid;
}
<div>
    <div id="txtboxLabel">Enter your five-digit zipcode</div>
    <button onclick=getText()>
    Get TextBox Data
    </button>
    <div class="textbox" role="textbox" contenteditable="true" aria-labelledby="txtboxLabel"></div>
</div>
amar
  • 443
  • 4
  • 15

3 Answers3

1

You can replace all the new line characters \n by using Strings replaceAll()

text = text.replaceAll('\n', "");

function getText() {
  let text = document.querySelector('[role=textbox]').innerText;
  text = text.replaceAll('\n', "");
  alert(text);
}
.textbox{
border: 1px solid;
}
<div>
    <div id="txtboxLabel">Enter your five-digit zipcode</div>
    <button onclick=getText()>
    Get TextBox Data
    </button>
    <div class="textbox" role="textbox" contenteditable="true" aria-labelledby="txtboxLabel"></div>
</div>
Aalexander
  • 4,987
  • 3
  • 11
  • 34
1

You can replace all \n (new line character that causes the multi line) with space character from the text content using String.prototype.replaceAll():

function getText() {
  let text = document.querySelector('[role=textbox]').innerText.replaceAll('\n',' ');
  alert(text);
}
.textbox{
  border: 1px solid;
}
<div>
    <div id="txtboxLabel">Enter your five-digit zipcode</div>
    <button onclick=getText()>
    Get TextBox Data
    </button>
    <div class="textbox" role="textbox" contenteditable="true" aria-labelledby="txtboxLabel"></div>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

Complicated to understand but this can do the trick by replacing all return at the line by space.

function getText() {
  let text = document.querySelector('[role=textbox]').innerText;
  text = text.split("\n").join(" ");
  alert(text);
}

If you want only the first line:

function getText() {
  let text = document.querySelector('[role=textbox]').innerText;
  text = text.split("\n")[0];
  alert(text);
}
Thibaud
  • 1,059
  • 4
  • 14
  • 27