Element not defined jQuery $ (element) .remove ()

I have this javascript that adds a form field along with a link to remove that field:

var fieldCount = 0;
function addField() {
    var name = 'file' + fieldCount;
    var row = 'row' + fieldCount;
    var str = '<p id="' + row + '"><label for="' + name + '">File to upload: <input type="file" name="' + name + '" id="' + name + '" />(100MB max size) <a onclick="removeRow(' + row + '); return false;">[-]</a></label></p>';
    fieldCount++;
    $("#fields").append(str);
};
function removeRow(id) {
    $(id).remove();
};

      

Here's the markup:

<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Upload")%>" method="post" enctype="multipart/form-data">
    <fieldset id="uploadFields">
        <legend>Upload a file</legend>
        <div id="fields"></div>
        <input id="ajaxUploadButton" type="submit" value="Submit" />            
    </fieldset>
    <a onclick="addField(); return false;" id="add">Add</a>
    <div id="resultBox">
        <p id="status" style="margin:10px;"></p>
    </div>
</form>

      

The addField additions work as expected, but when I click on the remove link, firebug tells me that "line #" is undefined, where # is any number of added fields.

Any help would be appreciated!

+2


source to share


3 answers


You need to pass a valid selector expression for the ID selector ( #

ID

) either in the call removeRow

(also note the quotes associated with the ID selector):

'<a onclick="removeRow(\'#' + row + '\'); return false;">'

      



Or in the function itself removeRow

:

function removeRow(id) {
    $("#" + id).remove();
};

      

+4


source


You need to have quotes around it as it is a string. You will also need "#" to make it a selector:

var str = '... <a onclick="removeRow(\'#' + row + '\'); return false;">...';

      



Better way would be to assign onclick as a function (not sure about the jQuery way to do this, but in plain Javascript):

var a = document.createElement('a');
a.onclick = (function(row)
{
    return function()
    {
        removeRow(row);
        return false;
    };
})();

      

+2


source


You are passing the string value "row12", but the selector must be:

$('#'+row').remove()

      

# indicates that you are looking for an ID. I agree with what I think one of the other answers will say, you should just use the natural onclick events "this" keyword:

<p onclick="remove(this)">something</p>

function remove(what) {
 $(what).remove()
}

      

Or maybe just forget everything together and switch to behavior for lines like this:

$('.removableRow').live('click', function() {$(this).remove()});

      

Then you simply indicate that the string is removable and should never bother with event binding at all:

<p><a class="removableRow" href="#">Remove</a></p>

      

+2


source







All Articles