Shown below I am try to input text into a text area and output it into a new window. My problem is I can't seem to get a new line to show in my DispWin when I click enter on the keyboard.
<script>
function display() {
// open a new window with specific properties
const DispWin = window.open('', 'NewWin', 'toolbar=no,status=no,width=700,height=500');
// create an array of the form elements
const formElements = [
document.form1.activity,
document.form1.des,
document.form1.trouble,
];
// create an array of the form labels
const formLabels = [
"Activity",
"Description",
"Troubleshooting Steps",
];
// create an empty string to store the message
let message = "<ul style='list-style-type:none;font-family:sans-serif;'>";
// loop through the form elements and add them to the message string
for (let i = 0; i < formElements.length; i++) {
message += `<li style='margin-bottom:5px;'><b>${formLabels[i]}:</b> ${formElements[i].value}</li>`;
}
message += "</ul>";
// write the message to the new window
DispWin.document.write(message);
}
</script>
My expected result should be when I go to DispWin is...
Activity: *Activity Type
Description: (Inputted text)
Troubleshooting Steps:(Inputted text) (Input From keyboard for a new line)
(Inputted text on a new line)
In the html standard new lines \n are handled like any other white space. Use white-space: pre-line which adds line breaks to the new lines.
<li id="li-1" style='margin-bottom:5px; white-space: pre-line'></li>
<script>
document.getElementById('li-1').innerHTML = 'first\nsecond\nthird';
</script>
Related
I want to extract html codes from a textarea value but failed.
I want to detect and replace images with textarea value.
Below is an example of what I want to do.
TEXTAREA
<textarea class="editor"><img src="x1"><img src="x2"></textarea>
The code below is an example of what I want to do, I know it's wrong.
var editor_images = $('.editor').val().find('img');
editor_images.each(function(key, value) {
$(this).attr('src','example');
});
If you want to replace multiple attributes or tags, then your question may be too broad. However, the example below gives you an idea of how to replace an image attribute within the textarea:
function replaceValueOfTextArea(searchAttr, replaceAttr, value) {
const editor = document.querySelector('.editor');
const imgs = editor.value.match(/<img[a-zA-Z0-9="' ]+>/g);
let textAreaNewValue = '';
for (let img of imgs) {
const regMatch = new RegExp(`(?<!img)${searchAttr}`, "gi");
const match = img.match(regMatch);
if (match) {
const regAttr = new RegExp(`${searchAttr}=["|'][^"|']+["|']`, "gi");
textAreaNewValue += img.replace(regAttr, `${replaceAttr}="${value}"`);
} else {
textAreaNewValue += img;
}
}
editor.value = String(textAreaNewValue);
}
replaceValueOfTextArea('src', 'src', 'https://example.com');
<textarea class="editor"><img src="x1"><img alt="x2"></textarea>
You can use jQuery's $.parseHTML() to parse an HTML string into DOM nodes. Then you can use this method to turn them back into HTML before reinserting them in your <textarea>:
// Get contents of editor as HTML and parse into individual <img> nodes:
let nodes = $.parseHTML( $('.editor').val() )
// Map through <img> nodes and change src attribute, and return as HTML text:
let html = nodes.map(function(node){
$(node).attr('src', 'example')
return $('<div>').append($(node).clone()).html();
})
// Insert HTML text back into editor:
$('.editor').html( html.join('') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="editor"><img src="x1"><img src="x2"></textarea>
I am developing web portal for ASR (Automatic speech recognition). As you all know that ASR won't give the 100% correct result. The main reason of getting wrong result are speaking behavior of person, noise, style of speaking, voice intensity, homophones (buy, bye. cite, site) etc. I am planning to do post processing by using web portal. I defined textarea where I get the recognized text. If user found that wrong word in text area then he will double click on wrong word in textarea and after word selection in same place display similar word pronunciation option (Similar pronunciation words are stored in text file. one line contains same pronunciation words) exa. If user selected word "sad" then in option he will get "sad, mad, bad" etc. I have created text file which contains following lines
sad, mad, bad
hero, zero
site, cite
buy,bye
If user select word "site" then he will get "site, cite" in textarea and finally user will select his correct word. Indirectly I am searching word in text file and if word found in text file then copy whole line and display as option in textarea (like google display's search options after entering text)
I wrote small code but getting failed to done all functionalities. My text file is locally stored.
<textarea name="text" id="textdata" rows="7" cols="79" wrap="soft" maxlength="4000" style="overflow:auto; resize:none; font-size: 17pt; font-family:"Times New Roman"
onselect="populateList(this.value)" > </textarea>
<script>
function populateList(val)
{
// alert("Entered populateList ");
var textComponent = document.getElementById('textdata');
var selectedText;
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
alert("Selected word : "+selectedText);
dic(selectedText);
}
</script>
<script>
$.get("http://localhost/english/master.txt",function(returnedData) {
$("#element").text(returnedData);
},"text/plain");
</script>
<script>
var text = $("#element").text();
var words = text.split(" ");
var dictionary = new Array();
for(var i=0; i < words.length; i++) {
dictionary[i] = words[i];
alert("dictionary elements are :"+dictionary[i]);
}
</script>
<script>
function dic(word) {
alert("Word passed for searching :"+word);
// var dictionary = new Array("Java","Python","Swift","HTML","PHP");
// This line is unnecessary; use the dictionary var already created.
var flag = 0;
for(var i = 0; i < dictionary.length; i++) {
if(dictionary[i] == word) {
document.getElementById("result").innerHTML = "Element Found";
flag = 1;
alert("Element found ");
break;
}
if(i == dictionary.length - 1) {
document.getElementById("result").innerHTML = "Element Not Found";
alert("Element not found ");
}
}
}
</script>
I am new in website development.
I've solved your problem, but I'm not using txt file, but json (because of CORS problem in fiddle), but if you create txt file it will work same. One line for one prompt words in file.
function populateList(val)
{
let textComponent = document.getElementById('textdata');
let tooltip = document.getElementById('tooltip');
let selectedText;
let startPos = textComponent.selectionStart;
let endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
fetch('https://api.myjson.com/bins/z9wr6').then(data=>data.json()).then(data=>{
let text = data.result.split('\n').reduce((acc,e)=>{
acc.push(Array.prototype.concat.call([],e.split(' ')))
return acc
},[]);
text.forEach(e=>{
if(e.find(ele=>ele===selectedText)){
tooltip.innerHTML = e.join(', ')
}
})
})
}
And working fiddle: https://jsfiddle.net/bfx8jdgh/
I want to get the values that were entered by the user from the window prompts, and let them display in paragraph tags on by html page. I thought using document.getElementById("idName").innerHTML would work, but it doesn't show the values that were entered by the user.
Here is the code I have on my JavaScript page. I have called the methods that need to execute on the page. :
var players = [];
var numberOfMoves = 0;
var currentPlayer = 0;
getPlayerNames(); //Get player names
setPlayerInformation(); //Set the names of the players in paragraph tags with id playerOneInformation and playerTwoInformation
function getPlayerNames()
{
players[0] = window.prompt("Please Enter Player 1: ", "");
players[1] = window.prompt("Please Enter Player 2: ", "");
}
function setPlayerInformation()
{
document.getElementById("playerOneInformation").innerHTML = players[0];
document.getElementById("playerTwoInformation").innerHTML = players[1];
}
I have code like this:
function getEmails() {
var search_in = document.body.innerHTML;
string_context = search_in.toString();
emails = string_context.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
for(var i=0; i<emails.length; i++){
console.log(emails[i]);
}
}
Instead of console.log, I need a box to appear with the list of emails from this array and a checkbox next to every email (checkbox is checked by default) and a button Save.
When I click the Save button, all selected emails should be saved to a txt file.
How do I do this?
You're practically there, I suggest your create an element in the markup and then create a string you'll append to it later, for example :
var string='';
for(var i=0; i<emails.length; i++){
string += "<div><input type='checkbox'>" +emails[i]+ "</div>";
}
and when you're done with your string, you can append it to the element of choice in the markup.
I have an image and name displaying in a new div. However, I have run into a problem where the next time a person enters name and picture and presses save, their userDiv shows their name plus the previous users name. For example, there are two users: User 1 and User 2. When I select all users and loop through the results the names are logging differently. User one shows up as "User 1", but User 2 shows up as "User 1 User 2". From a quick look around I think it is because innerHTML gets all content from the parent div, but I'm not sure.
var htmlStr="";
var theID;
var theName;
var thePhoto;
var len = results.rows.length;
console.log(len);
for(var i = 0; i < len; i++){
theID = results.rows.item(i).id;
console.log(theID);
theName = results.rows.item(i).username;
htmlStr += theName;
console.log(theName);
thePhoto = results.rows.item(i).imagepath;
console.log(thePhoto);
var imageHold= new Image();
imageHold.src = thePhoto;
console.log("this is the src:"+imageHold.src);
var userDiv = document.createElement("div");//Create the div
userDiv.innerHTML=htmlStr;
userDiv.appendChild(imageHold);
document.getElementById('showUsers').appendChild(userDiv);//append it to the document
userDiv.style.display = 'block';
Remove var htmlStr=""; and declare it within the loop on each iteration. So change
htmlStr += theName;
to
var htmlStr = theName;
and this should resolve your issue