Gandalf
Gandalf

Reputation: 13683

Getting value of dynamically added form field returns wrong value

I have this html code

<input type="button" id="add_destination" value="add new" />

<div id="desti_div">

</div>

and this jQuery

 var count = 0;

 $( "#add_destination" ).on( "click", function(e) {
        e.preventDefault();
         count = Math.floor(Math.random() * 78955) + 147;
    $("#desti_div").append("<div class='tmar'><div class='form-group col-md-6 getspace'><label><i class='gicon fas fa-circle'></i> New Destination</label><input class='form-control input-lg form-field' type='text' id='added_dest"+count+"' name='added_dest' placeholder='New Destinaton' ><a href='' class='gored'><span class='form-control-feedback'></span>Delete</a></div><br/></div>");

    });

        $(document).on('click', '.gored', function(e){ 
        e.preventDefault();
        field_val = $('#added_dest'+count).val();
            alert(field_val);
        $(this).parent().parent().remove();

    }); 

that I am using to get the value of a dynamically added field. I have a button that removes the form field but before I do, I want to fetch the value of the input field being removed.

This is the fiddle http://jsfiddle.net/5w2cm081/8/

When I click delete, my code gets the wrong value of form field. How can I get the value of the value I want to delete?

Upvotes: 0

Views: 92

Answers (2)

David Bray
David Bray

Reputation: 586

$(document).on('click', '.gored', function(e){ 
    e.preventDefault();
    field_val = $(this).siblings('[name="added_dest"]').val();
    alert(field_val);
    $(this).parent().parent().remove();

}); 

Upvotes: 1

Yasin Tazeoglu
Yasin Tazeoglu

Reputation: 1004

You need to use count on delete button because it should know which delete


You should edit <a href='' class='gored' count='"+count+"'><span class='form-control-feedback'></span>Delete</a> in append html

and

field_val = $('#added_dest'+$(this).attr('count')).val();

complete code

var count = 0;
function appendHtml(count){
 return "<div class='tmar'><div class='form-group col-md-6 getspace'><label><i class='gicon fas fa-circle'></i> New Destination</label><input class='form-control input-lg form-field' type='text' id='added_dest"+count+"' name='added_dest' placeholder='New Destinaton' ><a href='' class='gored' count='"+count+"'><span class='form-control-feedback'></span>Delete</a></div><br/></div>"
}

$( "#add_destination" ).on( "click", function(e) {
    e.preventDefault();
     count = Math.floor(Math.random() * 78955) + 147;
$("#desti_div").append(appendHtml(count));

});
    $(document).on('click', '.gored', function(e){ 
    e.preventDefault();
    field_val = $('#added_dest'+$(this).attr('count')).val();
    alert(field_val)
    $(this).parent().parent().remove();

}); 

Upvotes: 1

Related Questions