Cataras Cataras - 6 months ago 27
jQuery Question

Can't pass right ID to .replaceWith()

I know the answer is probably gonna be something very simple but i'm losing my mind over not getting this to work:

<button id="buttonid<?php echo $i?>" onclick="addShift(this.id)">+</button>
<script>
function addShift(id){
alert(id);
$('#id').replaceWith( "<h2>TEST</h2>" );
}
</script>


alert shows the right ID. But i can't get the .replaceWith function to work.

$("button").replaceWith( "<h2>TEST</h2>" );


This is working by the way. What am i substantially missing here about submitting html ID's to javascript? Thanks!

Answer

I could be misunderstanding the problem, but I think it's because you are using the string '#id' instead of the value for id.

Try this:

<button id="buttonid<?php echo $i?>" onclick="addShift(this.id)">+</button>
<script>
    function addShift(id){
        alert(id);
        $('#'+id).replaceWith( "<h2>TEST</h2>" );        
    }
</script>

You might be thinking that Javascript works like PHP in terms of supporting string interpolation. That means, the thing that let's you do something like $variable = 'me'; echo "$variable is cool"; in PHP, and have it print out me is cool. But Javascript doesn't do that. You need to use string concatenation instead, i.e. alert(variable + ' is cool').