0

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  
1
  • Once you type $, it will be replaced with the word money? Also, since there is parenthesis, it makes a confusion about what output you expect. Commented Dec 5, 2016 at 0:26

1 Answer 1

1
<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

Sign up to request clarification or add additional context in comments.

1 Comment

I see what you did there. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.