How to make a text box a div that contains the text of this text box. Is it possible?

I want to create this on my website. The user enters some text into the text field, and after he presses the enter key, the text field will change to a div, and the div will contain text from the text field, and it will be in the same place where the text field was, and the text field will be hidden. Is it possible?

Here is what I have now: HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.3/js.cookie.js"></script>
<input id="name" type="text" class="name" placeholder="What your name?"/>

Javascript (inside HTML file)

<script>
            $(document).ready(function(){
                var name = Cookies.get('_username');
                if (name) {
                    $('#name').val(name);
                }
                $('#name').keydown(function(){
                    var inputName = $('#name').val();
                    Cookies.set('_username', inputName);
                })
            });
        </script>

CSS

@import url('https://fonts.googleapis.com/css?family=Roboto+Condensed:700');
.name{
    font-family: 'Roboto Condensed', sans-serif;
    font-size: 3.5vw;
    border: 0;
    outline:0;
    background: transparent;
    border-bottom: 2px solid white;
    width: 30%;
    color:#000000;
    position:fixed;
    top:60%;
    left:50%;
    margin-left:10px;
}
+4
source share
4 answers

event.which, , enter. , $('#name').hide(), textbox.

event.which ,

$(document).ready(function(){
     $('#name').keydown(function(e){
         if(e.which==13){
            $('#name').hide();
            $('#text').html($('#name').val());
         }                       
      });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" type="text" class="name" placeholder="What your name?"/>
<div id="text">

</div>
Hide result
+2

jquery . div, css, display: none;, js enter. div textbox div textbox .

$('#textbox').keydown(function(event){
    //Check if enter was pressed
    if(event.which == 13){
        event.preventDefault();
        //Get value from textbox and set to div
        $('#div').text($('#textbox').val());
        //Show div and hide textbox
        $('#div').show();
        $('#textbox').hide();
    }
})
+2

, , jQuery;

$('#name').keydown(function(e){
   if(e.which == 13) {
      $(".myDiv").text($(".myDiv input").val());
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myDiv">
	<input id="name" type="text" class="name" placeholder="What your name?"/>
</div>
Hide result

, cookie, , .

+1

, replaceWith

var inputName = $('#name').val();
if(e.keyCode == 13){
    $(this).replaceWith($("<div>").html(inputName));
}

+1

Source: https://habr.com/ru/post/1666421/


All Articles