Skip to content Skip to sidebar Skip to footer

Javascript Function To Add/remove Fields

I'm not very experienced with JavaScript, but this code was similar to what I was looking for , especially where it includes the 'Remove Field' link. Here is the Javscript functio

Solution 1:

Remove those if(!document.getElementById) and if(document.createElement) conditions. Every browser supports them, and those which not are not worth to be supported (Let them throw their errors).

To add the remove-method to DOM-created elements, just use the onclick property. You can also use standard-compliant addEventListner(), but this needs some workarounds for IE. See sections Legacy Internet Explorer and attachEvent and Older way to register event listeners.

So the code would be

...
li.appendChild(document.createTextNode(" ");
var a = document.createElement("a");
a.appendChild(document.createTextNode("Remove Field"));
a.style = "cursor:pointer;color:blue;";
a.onclick = function() {
    // this.parentNode.parentNode.removeChild(this.parentNode);// nay. we have better references to those objects:
    field_area.removeChild(li);
};
li.appendChild(a);

http://jsfiddle.net/wtX7Y/2/

Solution 2:

I'm going to differ with Kappa and encourage you strongly to keep doing what you're doing. JQUery is great for what it is, but it is too often a crutch, and it's so important to know what you're doing and why you're doing it when working with javascript. Especially if you are learning to get a job in the sector, you will need straight JavaScript.

The good news, what you're trying to do is actually quite simple!

var li = document.createElement("li");
    var input = document.createElement("input");
    input.id = field+count;
    input.name = field+count;
    input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
    li.appendChild(input);
    field_area.appendChild(li);
    //create the removal link
    removalLink = document.createElement('a');
    removalLink.onclick = function(){
        this.parentNode.parentNode.removeChild(this.parentNode)
    }
    removalText = document.createTextNode('Remove Field');
    removalLink.appendChild(removalText);
    li.appendChild(removalLink);

Here's the code on JSFiddle: http://jsfiddle.net/r9bRT/

Solution 3:

I strongly suggest you to take a look to jQuery (ora similar: prototype, motools etc..)

They have full featured DOM manipulation functionalities, that makes what you ask as complex as writing 1 line of js.

Post a Comment for "Javascript Function To Add/remove Fields"