Jump to content

Code explanation/help. Editing a textfield...


ShootingBlanks

Recommended Posts

Hello.  I am new to JS.  I was looking for a piece of code that would allow me to make buttons for "bold" "italic" and "underline" in a form that, when clicked, would wrap the proper tags around the selected text in a textarea HTML field. (much like you see when you are posting replies on any message board)...

 

I found the following code that supposedly should work:

function insert(id,tag,val)
{
var obj = document.getElementById(id);
var start = "[" + tag + "]";
var end = "[/";
var range;
        if(ie)
{
	range= document.selection.createRange();
	if(!val)
		val="";
	if(range.text)
		val = range.text;
	range.text = start + val + end;
	range.moveStart("character",-(end.length+val.length));
	range.moveEnd("character",-(end.length));
	range.select();
}
else
{
	var s = obj.selectionStart;
	var e = obj.selectionEnd;
	var x;
	x = obj.value.substring(s,e);
	x = start + x + end;
	obj.value = obj.value.substring(0,s) + x + obj.value.substring(s+x.length,obj.value.length);
	obj.selectionStart = s+start.length;
	obj.selectionEnd = s+x.length-end.length;
}
obj.focus();
}

 

I don't understand the vast majority of that code (again - I'm very new to JS), but I took it, pasted it into a new page, and saved it as "textEditor.js".

 

In that same directory is a PHP page with the following code underneath the "title" tags:

<script src="textEditor.js"></script>

 

The code for the textarea that I'd like to have editable by the JS code is coded like this:

<textarea name="doc_content" id="information" cols="50" rows="5"></textarea>

 

Just above that textarea, I have (based on the JS code) inserted this:

<input type="button" value="bold" name="bold" onClick="javascript:insert('information','b','value');"

 

I'm sure that was the wrong thing to do (that last part), but I don't know what I'm doing because I'm so new to all this...

 

Will that original block of code work for what I want to do?  If it will, then based on my example above, how could I make it work?  Thanks!!!

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.