Question

I have a link that wired up to a jQuery function. It is inside an <li> with another link. Code here:

<li id="aps_pdf1">
   <a target="_blank"" href="....">1testpdf.pdf</a>
      <span style="padding-left:40px">
           <a id="delete-aps_pdf1" class="delete_pdf" title="Delete this PDF." href="#">Delete</a>
      </span>
</li>

I'm trying to replace the first link with a file upload control when the delete-aps_pdf1 is clicked by replacing the html with jQuery. Here's what I have so far with my code:

jQuery(document).ready(function($) {
    $('.delete_pdf').each(function(i,e) { //grab the link class delete-pdf
        var id = $(this).attr('id').replace(/delete-/, '');
        var li = $(this).closest('li').attr('id');
        $(this).click(function(){
            //alert('Clicked! '+ id);//$(this).attr('id'));  //THIS WORKS WHEN CLICKED
            //alert(li);
            $(li).replaceWith('<input type="file" style="width: 700px;" name="' + id + '" id="' + id + '" />');

        });
    });

My replaceWith doesn't seem to be working at all. I'm relatively new with jquery and I've done this reading documentation so I'm sure I'm missing something somewhere.

A step in the right direction would be greatly appreciated!

Was it helpful?

Solution

You're trying to replace a string. Pass the jQuery object instead:

jQuery(document).ready(function($) {
$('.delete_pdf').each(function(i,e) { //grab the link class delete-pdf
    var id = $(this).attr('id').replace(/delete-/, '');
    var li = $(this).closest('li');
    $(this).click(function(){
        //alert('Clicked! '+ id);//$(this).attr('id'));  //THIS WORKS WHEN CLICKED
        //alert(li);
        $(li).replaceWith('<input type="file" style="width: 700px;" name="' + id + '" id="' + id + '" />');

    });
});

OTHER TIPS

You are getting the li id (.attr("id")) which means that you need to concatenate a # on the front of your other query

$('#'+li).replaceWith('<input type="file" style="width: 700px;" name="' + id + '" id="' + id + '" />');

Could you just grab the parent li with:

var li = $(this).parent('li');

You have a mistake in the following line

var li = $(this).closest('li').attr('id');

It should be

var li = $(this).closest('li');

or

var li = $(this).closest('li#' + id);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top