Javascript - highlight text in textbox?

Discussion in 'JavaScript' started by tobydawson13, Jul 8, 2010.

  1. #1
    <a href="javascript:;" onclick="document.forms[0].detail.value=document.forms[0].detail.value+'[b ][ /b]'">
    Bold
    </a>
    
    <form id="form1" name="form1" method="post">
    <textarea name="detail" cols="50" rows="5" id="detail"></textarea>
    </form>
    Code (markup):
    Hey, could somebody help me out? I have the code above which when the link "Bold" is clicked the javascript inserts "[b ][ /b]" into the textbox. How could I edit the current code so that when the text in the textbox is highlighted/selected the [b ][ /b] goes around the selected text? ([b ]Text here[ /b])

    Thanks for you help :)
     
    tobydawson13, Jul 8, 2010 IP
  2. Kaimi

    Kaimi Peon

    Messages:
    60
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Maybe like this:
    
    <script>
    function insert()
    {
    	var textarea = document.getElementById('detail');
    
    	if(textarea.selectionStart != textarea.selectionEnd)
    	{
    		var tmp = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);
    	
    		textarea.value = textarea.value.substring(0, textarea.selectionStart) + '[b ]' + tmp + '[ /b]' + textarea.value.substring(textarea.selectionEnd);
    	}
    }
    </script>
    <a href="javascript:;" onclick="insert();">
    Bold
    </a>
    
    <form id="form1" name="form1" method="post">
    <textarea name="detail" cols="50" rows="5" id="detail"></textarea>
    </form>
    
    Code (markup):
     
    Kaimi, Jul 8, 2010 IP
  3. anands

    anands Well-Known Member

    Messages:
    436
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    120
    #3
    I tried several methods but in vain.

    Anyone?
     
    anands, Jul 8, 2010 IP
  4. tobydawson13

    tobydawson13 Active Member

    Messages:
    645
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #4
    Thanks Kaimi, it works quite well :)
    But it doesn't work when nothing is selected. I would like [b ][ /b] to be entered into the textbox even when nothing is selected.
    Anyone have any ideas?
    Surely there's a simple way of doing this?
     
    tobydawson13, Jul 8, 2010 IP
  5. Kaimi

    Kaimi Peon

    Messages:
    60
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Just remove
    if(textarea.selectionStart != textarea.selectionEnd)
     
    Kaimi, Jul 8, 2010 IP
    tobydawson13 likes this.
  6. tobydawson13

    tobydawson13 Active Member

    Messages:
    645
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #6
    Thanks :D that works perfectly. Rep added
     
    tobydawson13, Jul 8, 2010 IP