user5303690
user5303690

Reputation:

New paragraph each time I press keyboard enter button inside my inputbox (in which there is text)

Each time when I press enter (on my keyboard) inside input box and there is text inside input box, I want the new paragraph to appear which will contain the text from the input box.

This is my attempt, what is wrong with my code ? It does not work:

https://jsfiddle.net/dxuax025/

HTML:

<input type="text" id="text">
<div id="list"></div>

jQuery:

$(document).ready(function() {

                var r = $('<p>' + a.val() + '<p>');

        $('#text').keypress(function(e) {
            if(e.which == 13 & a.val() !== "") {
                var a = $('#text');
                var html = r(a.val());
                $('#list').append(html);
                $(a).val("");}
                return false;
            });
        }); 

Upvotes: 1

Views: 959

Answers (1)

Kalpesh Singh
Kalpesh Singh

Reputation: 1717

Logic is:

  1. Detect ENTER key
  2. if the user pressed ENTER key then take value from input
  3. At last, append p tag to div.

$(document).ready(function() {

	  $('#text').keypress(function(e) {
	    var key = e.which;
	    if (key == 13) // the enter key code
	    {
	      var inputText = $("#text").val();
	      $("#list").append("<p>" + inputText + "</p>");
          $("#text").val("");
	    }
	  });
	});
#list p {
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 2px 2px rgba(0, 0, 0, .15);
  color: #473e39;
  font-size: 16px;
  margin: 0 auto 5px;
  padding: 20px;
  max-width: 520px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text" placeholder="Input something and enter">
<div id="list"></div>

Upvotes: 1

Related Questions