Viktor
Viktor

Reputation: 722

How to change dynamically text with Jquery

How to change text dynamically. SO when i doubleclick on text it appear in input and i can just clear text and write another.

Here is my starting code Jsfiddle

<div id="main_text">
    <h1>Change Text</h1>
</div>



$('.main_text').dblclick(function(){
    var val = $("#main_text").value();  

});

Upvotes: 0

Views: 66

Answers (2)

Starfish
Starfish

Reputation: 3574

This should do the trick:

Edit: I added a keylistener. If you press enter, it will apply the changes.

$('#main_text').dblclick(function() {
  var currentText = $(this).children('h1').text();
  $(this).children('h1').replaceWith('<input class="change" type="text" value="' + currentText + '"/>');
  $('.change').keyup(function(e) {
    if (e.keyCode == 13) {
      var currentText = $('.change').val();
      $(this).replaceWith('<h1>' + currentText + '</h1>');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main_text">
  <h1>Change Text</h1>
</div>

Upvotes: 1

Ashish Kumar
Ashish Kumar

Reputation: 3039

Something like this may help you:

$('#main_text').dblclick(function(){
    var $elm = $(this);
    
	$elm.find("h1").replaceWith($("<input />", {
    	val: $elm.text(),
        change: function(){
            var text = $(this).val();
            
        	$elm.html($("<h1 />", {
            	text: text
            }));
        }
    }));
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main_text">
    <h1>Change Text</h1>
</div>

Working example: http://jsfiddle.net/006853mL/1/

Upvotes: 2

Related Questions