views:

36

answers:

1

I'm trying to remove a dynamic form field by click a button. It will also subtract whatever values it had from the total amount from my calculation. This is the code:

function removeFormField(id) {
    var id = $(id).attr("name");
    $('#target1').text($("#total" + id).map(function() {
        var currentValue = parseFloat(document.getElementById("currentTotal").value);
        var newValue = parseFloat($("#total" + id).text());
        var newTotal = currentValue - newValue;
        document.getElementById("currentTotal").value = newTotal;
        return newTotal;
        }).get().join());
    $(id).remove();
}

Okay, it will do the subtraction portion of the code with no problem, this issue is with the last line to remove the field. If I comment out the rest of the code it will work, but not with the rest of the code. I know this is something simple, yet I can't seem to wrap my mind around it. Can someone please help?

+2  A: 

You're setting id to equal the name of the form element with:

var id = $(id).attr("name");

Then trying to get it with: $(id) at the end. Try changing the last line to actually use the ID of the element you are trying to delete - remember the '#' before it. Without seeing what is passed into the removeFormField() as the id parameter I can't be sure what you need to change.

The important bit to remember is form name attributes are not the same as element IDs.

Geoff Adams
I knew it would be something as simple as this. Thanks for your help, it worked.
rshivers
It's a common mistake if you're getting to grips with jQuery, remember it uses CSS3 expressions in the selector engine.
Geoff Adams