-1

I'm quite new to programming (started yesterday) and so far I've just created a very simple code. I am currently unaware on how to make it so I can click enter and it will submit the forum post so any commands on how to make that possible would be greatly appreciated :)

<!DOCTYPE html>
<html>
<head>
<title>Title Changing Simulator!</title>
<script type="text/javascript">
function substitute()  {
var myValue = document.getElementById('myTextBox').value;

if (myValue.length == 0)   {
alert('Please enter a real value in the text box!');
return;
}  
var myTitle = document.getElementById('title');
myTitle.innerHTML = myValue;

}
</script>
</head>
<body>
<h1 id="title">Title Changing Simulator!</h1>

<input type="text" id="myTextBox" />
<input type="submit" value="Click My Button" onclick="substitute()" />
</body>
</html>
j08691
  • 204,283
  • 31
  • 260
  • 272
  • Go to CodeSchool.com and take one of their free courses on web programming. Rails for Zombies is a good choice, or the one for Node. You need to have some kind of server-side logic that gets the info you're trying to post. One of those courses will help with the fundamentals. Good luck – Paul Jun 06 '16 at 02:24
  • 1
    This updates the title h1 element. What were you trying to accomplish? – Chris Ballance Jun 06 '16 at 02:24
  • with 'click enter', you mean 'type enter', right? – le_m Jun 06 '16 at 03:22

1 Answers1

0

Wrap your input and button in a <form> and listen for the form's submit event which is triggered either by clicking the submit button or pressing enter in the input field. See also How to trigger enter key press of textbox?

const form = document.getElementById('form');
const text = document.getElementById('text');
const title = document.getElementById('title');

form.addEventListener('submit', event => {
  event.preventDefault();

  if (text.value.length > 0) {
    title.textContent = text.value;
  } else {
    alert('Please enter a real value in the text box!');
  }
});
<h1 id="title">Title Changing Simulator!</h1>

<form id="form">
  <input type="text" id="text">
  <input type="submit" value="Update">
</form>
le_m
  • 19,302
  • 9
  • 64
  • 74