How do I add text to an HTML input form?

I created a basic html input form but would like to add some text to user input, how would I go about doing that?

<form action="https://api.hipchat.com/v1/rooms/message" method="get" target="">
  <input type="hidden" name="room_id" value="example">
  <input type="hidden" name="from" value="example">
  <input type="hidden" name="color" value="example">
  <input type="hidden" name="notify" value="example">
  <input type="hidden" name="auth_token" value="example">

  Message: <input type="text" name="message"><br>
  <input type="submit" value="Submit">
</form>

      

I want to get information from a user and then send him to the HipChat room. It all works the way it is. But I would like to add "@Lewis", for example, before the post to get a mention of HipChat. Is it possible to do something like:

value = "@Lewis" + "Submit"

Thank!

+3


source to share


2 answers


No need to add jQuery for this request. A little JavaScript will serve you just as well, and will be much easier. But if you plan on using a lot of js, you can start jQuery validation.



<form id="myForm" action="https://api.hipchat.com/v1/rooms/message" method="get" target="">
  <input type="hidden" name="room_id" value="example">
  <input type="hidden" name="from" value="example">
  <input type="hidden" name="color" value="example">
  <input type="hidden" name="notify" value="example">
  <input type="hidden" name="auth_token" value="example">Message:
  <input type="text" name="message" id="myMessage">
  <br>
  <input type="submit" value="Submit">
</form>

<script type="text/javascript">
  window.onload = function() {
    document.getElementById("myForm").onsubmit = function() {
      var msgElement = document.getElementById("myMessage");
      msgElement.value = '@Lewis: ' + msgElement.value;
      alert(msgElement.value); //comment/remove this line
      return true;
    };
  };
</script>
      

Run codeHide result


Note that I have added an id to the form and post element.

+2


source


You can do it with JavaScript. Add a submit handler and add the text you want at the beginning of the message. Example using jQuery:



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">   </script>
<script>
  $(function() {
    $('form').submit(function() {
      var $m = $(this).find('[name=message]');
      $m.val('@Lewis ' + $m.val();
    });
  });
</script>

      

+1


source







All Articles