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
https://forums.phpfreaks.com/topic/70635-code-explanationhelp-editing-a-textfield/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.