将功能应用于所选文本[关闭]

http://webwrinkle.com/

I have a basic form up on the above listed web address. I would want the option for the user to be able to apply a javascript or jquery function to selected text in the form. Is a php file, so the info would go into a database, and then output as html in a page.

I was thinking that the user could select text entered into the form, apply the function via a button, and the function tied to the button would input link tags on both ends of the selected text to make the selected text a clickable weblink on a posted php page. (the same kind of functionality in TinyMCE) Let me know if more info is needed, or I didn't explain it fully. I should be able to figure out how to build the PHP functions that need applied if I can get started in the right direction...

thanks for all your help!

Well first of all, you shouldn't have to send anything to the server until you're ready to submit the "memo" -- you can do all of the editing you described entirely with javascript.

First of all, you need to be able to retrieve the currently selected text. You can use something like this:

var memoBox = document.getElementById("memo"); //get the memo input element

var startIndex = memoBox.selectionStart, endIndex = memoBox.selectionEnd; //store the start and end of the user's selection
var selectedText = memoBox.value.substring(startIndex,endIndex); //retrieve and store the selected text

Now, let's say you want to add a link to the selected text. You could write a function like this:

function addLinkToSelected() {
    var memoBox = document.getElementById("memo");
    var startIndex = memoBox.selectionStart, endIndex = memoBox.selectionEnd;
    var selectedText = memoBox.value.substring(startIndex,endIndex);

    var linkURL = prompt("Link target: "); //ask the user for a link target
    var linkTag = '<a href="'+linkURL+'">'; //construct a link tag

    memoBox.value = memoBox.value.substring(0,startIndex) + linkTag 
                   + selectedText + "</a>" + memoBox.value.substring(endIndex+1);
}

Now, just add a button and call the function when it is clicked:

<input type="button" value="add link" onclick="addLinkToSelected()" />

I'm not exactly sure if this is what you're looking for, so feel free to add more detail. I've created a jsfiddle where you can check out a working example.

you can use link() function of javascript to convert text into a hyper text link

ex.

function addLink() {
    var memoBox = document.getElementById("memo");
    alert(memoBox.link(memoBox));
}