1

I use ajaxsubmit to upload file to linux server .File name+file size + cancel button will appear in my website after upload file successfully.Here is my html code:

<style type="text/css">
.files{height:10px; font-size:10px;line-height:22px; margin:10px 0}
</style>
<div class="files"></div>

My ajaxsumit code is:

$("#myupload").ajaxSubmit({
        dataType:  'json',
       ......
success: function(data) {
files.html(files.html()+"<br />"+"<b id='dataname'>"+data.name+"("+data.size+"k)</b> <span class='delimg' rel='"+data.pic+"' id='cancelbtn'>cancel</span>");
 },
 ......

When cancel button is clicked,File name+file size + cancel button will disappear .Here is my js code:

$(document).on('click',".delimg",function(){
    var filename = $('#dataname').val()+"cancel";
            files.html(files.html().replace(new RegExp(filename,"g"),""));
});

Unfortunately,it worked fail.Here is example which i want to realize.Before click cancel, my files div content is :

1.jpg(10.36k) cancel
2.jpg(10.36k) cancel
3.jpg(10.36k) cancel

After i click the second cancle,my files div content is:

1.jpg(10.36k) cancel
3.jpg(10.36k) cancel

Who can help me?

stack
  • 821
  • 1
  • 15
  • 28

1 Answers1

0

The problem is id='dataname.

You can't use multiples times the same id.
Use a class instead. More reading about it here.

So...
<b class='dataname'>
instead of
<b id='dataname'>

and remove the useless id='cancelbtn'.

Then your click event handler should be:

$(document).on('click',".delimg",function(){
    $(this).prev('.dataname').remove(); // removes the filename
    $(this).remove(); // Removes the "cancel"
});

There is no need for a regular expression here.
You have classes to target the elements to remove.

Regex are used to target character patterns in a string.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64