I am trying to write a JS function that takes a block of text pasted inside textarea, removes line breaks but keeps paragraph breaks, and updates the text inside that textarea before I submit a form.
I have attempted to do it this way:
<textarea name="sum" id="sum" onpaste="frmt()"></textarea>
JS:
const tar = document.getElementById("sum");
const reg = /[\r\n](?![\r\n])/g;
const str = tar.value;
tar.innerHTML = str.replace(reg, "");
What am I missing?
CodePudding user response:
<textarea name="sum" id="sum"></textarea>
<script>
const sum = document.getElementById('sum');
sum.addEventListener('paste', () =>
setTimeout(
() => (sum.value = sum.value.replace(/[\r\n](?![\r\n])/g, '')),
0
)
);
</script>
https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event
CodePudding user response:
<textarea> is not supported .innerHTML so you need to set values through .value and you can use oninput event.
This event occurs when the value of an <input> or <textarea> element is changed.
Helpful links:
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput
https://www.w3schools.com/jsref/event_oninput.asp
function frmt(id){
const tar = document.getElementById(id);
const reg = /[\r\n](?![\r\n])/g;
const str = tar.value;
tar.value = str.replace(reg, "")
}
textarea{
width: 95%;
height: 160px;
}
<textarea name="sum" id="sum" oninput="frmt('sum')"></textarea>
