Question

Im trying to write a small js script that will let a user input a string of text and then output it wrapped in some html to the page.

I know how to do this with php, but it seems a little bit of an overkill for such a simple action, plus im always keen to learn something new.

I was playing around using document.myform.submit(); but i wasnt sure how to submit the form value to a variable and then output that var to the screen using document.write();

Any ideas how i would do this ?

Ive created a jsfiddle of the problem here - http://jsfiddle.net/pudle/axcLz/

Was it helpful?

Solution

There are many ways to do it. Here is the code that shows one of them:

document.getElementById("myform").onsubmit = function (event) {
    var link = document.getElementById("mylink");
    var textField = document.getElementById("text");
    link.href = textField.value;
    textNode = document.createTextNode(textField.value);
    if (link.hasChildNodes()) {
        link.removeChild(link.lastChild);
    }
    link.appendChild(textNode);
    event.preventDefault();
};

jsfiddle: http://jsfiddle.net/TMJGH/5/

I added an id attribute to the a element to make things easier.

First line says that we want to change the function that handles "onsubmit" event in our form and then we define that function. The "event" argument is used only to call .preventDefault() in the last line which basically means that we don't want the form to be actually submitted.

We need to get access to DOM elements in the javascript code, so I used document.getElementById. Then I set the href attribute to the value of the textField. To change the actual link text I created a new text node with the value of the textField (it is possible to use textNode.innerHTML but that won't escape HTML code if someone inserts it in the text field). Then I check if our a element already has some text in it - if yes, it has to be removed. Finally I append the text element as a new child to our a element.

If you want to append more HTML nodes inside a node you can easily create them with document.createElement('element name') and append them to link. I also have to mention that jQuery makes playing with DOM a lot easier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top