Is there a way to get text from a html textbox using js?

Viewed 64

Now, I know this has been posted before. Read it before reporting. I want to try and make a script that gets text from a textbox, and the textbox has code that the user writes. Right now I have a script that can open it in a new window, but

  const el = document.getElementById('externalLink');

  // Create a content for a new page with a script in it
  const newPageContent = `
<DOCTYPE html>
<head>
<title>some code</title>
</head>
<body contenteditable>
<h1>Some editable text</h1>
</body>
  `;

  // Listen on "click" event
  el.addEventListener('click', (e) => {
    e.preventDefault();

    // Create a new window on click
    const w = window.open('', '_blank');

    // Write your content to it
    w.document.write(newPageContent);
  });
<!-- Your link !-->
<a id="externalLink" href="#/">Click to run the code</a>
<br>
<input type="text" name="Codebox" value="Code here...">

But the script "var Codebox = document.getElementsByName('txtJob')[0].value" just gets run as a html script, thus makeing it literally say "var Codebox = document.getElementsByName('txtJob')[0].value" on the result page. If there is a way to bypass this, or if i'm just doing it incorrectly, could someone please help me? That would be great! :)

1 Answers

You can set id to input tag and get the value of it using document.getElementById('...').value as follows.

const el = document.getElementById('externalLink');

// Create a content for a new page with a script in it
const newPageContent = `
  <DOCTYPE html>
  <head>
    <title>some code</title>
  </head>
  <body contenteditable>
    <h1>Some editable text</h1>
  </body>
`;

// Listen on "click" event
el.addEventListener('click', (e) => {
  e.preventDefault();
  
  const codeValue = document.getElementById("codeBox").value;
  console.log('Code Value', codeValue);

  // Create a new window on click
  const w = window.open('', '_blank');

  // Write your content to it
  w.document.write(newPageContent);
});
<!-- Your link !-->
<a id="externalLink" href="#/">Click to run the code</a>
<br>
<input type="text" name="Codebox" id="codeBox" value="Code here...">

Related