Question

I am using this code to be able to change text overlay on an image by typing into a box.

<input type="text" id="inp"><br>
<img id="image" src="image.php?name=swag">
<script type="text/javascript">
window.onload = function()
{
    document.getElementById( 'inp' ).onkeyup = keyUp;
}

function keyUp()
{
    var img = document.getElementById( 'image' );
    img.src = img.src.replace( /name=[^&]+/ , 'name='+ this.value );
}
</script>

it works for changing the ?name= of the image.php, however whenever i clear the box it stops functioning until i refresh the page. this makes it nonfunctional because the point is to clear the text box and rewrite something.

I need to fix it so it works even when the box is cleared, but i cannot figure out how.

No correct solution

OTHER TIPS

The regex is the problem here. Replace the + with a * for a quick fix. But you should probably just do img.src = 'image.php?name=' + this.value;

The plus looks for at least 1 character. So when you blank it out, img.src ends in name= and no longer has [^&]+ to replace

You can try this, it works

img.src = img.src.replace( /name[^&]+/ , 'name='+ this.value );

search text starts with name and replace with name= , so when you clear the textbox regular exp will find the matching text and replace with new value

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top