Home > Net >  JavaScript/html show alert which includes label input
JavaScript/html show alert which includes label input

Time:11-09

I'm using HTML5 and JavaScript

I want to be able to input any word into a label and when you click on the button it gives an alert which includes the given text.

I cannot get it to work with the text I put into the label the alert shows no text. I've only found how to do it with predefined labels.

Here's my current html code

function getinput() {
  var input = document.getElementById("form-scream").innerText;
  alert(input);
};
<div>
  <p>Word
    <label id="form-scream"></label>

    <input type="text" name="screaming" id="form-scream">

    <button onclick="getinput()"> Click to scream</button>
  </p>
  <script src="assets/js/scream.js"></script>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

input element does not have innerText property, use value instead. Also, you have use for attribute in a label to associate an element (the element's id as the value of for):

function getinput()
{
  var inputVal = document.getElementById("form-scream").value;
  alert(inputVal);
};
<div>
    <p>Word
    <label for="form-scream"></label>

    <input type="text" name="screaming" id="form-scream">

    <button onclick="getinput()"> Click to scream</button>
    </p>
    <script src="assets/js/scream.js"></script>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related