Steve Kim
Steve Kim

Reputation: 5591

Inserting div in the input JS

I have following js:

jsfiddle

<script>
function hadd(event,which){ 
        var val = event.charCode;               
        if(val == 36){ //$ sign     
           var rh  = $(which);                           
           var cont = '<span class="dollar">Money</span>';                  
           rh.append(cont); //????      
        }           
    };  
</script>

<div class="example" contenteditable="true" tabindex="-1" onkeypress="hadd(event,this);">
   Please insert (here) now  
</div>

When "$" is typed, it appends new span at the end of "Please insert (here) now".

Please insert ($) now money.

How do I append the span right after where the $ was typed while removing the $ sign? (see below)

Please insert (money) now  

Upvotes: 0

Views: 47

Answers (1)

CodeBoy
CodeBoy

Reputation: 3300

<script>
  $(function() {
      $('.example').keyup(function(event) {
          if (event.which == 52) {  // "$"
              var rh = $(event.target);
              var newContent = rh.html().replace('$', 'Money');
              rh.html( newContent );
          }
      });
  });
</script>
<h5>Type "$" into the "here" section</h5>
<div class="example" contenteditable="true" tabindex="-1">
  Please insert (here) now  
</div>

See this JSfiddle. I made it a little more jQuery-ish by replacing the onkeypress attribute with a jQuery event handler for class example. I switched to keyup because until the key goes up the $ does not appear in the contents of the <div> (such as for keypress). When I did that, the code for $ changes from 36 to 52.

Edit: fixed link to jsfiddle

Upvotes: 1

Related Questions