Javascript Replace Text After An Underscore
Solution 1:
filename = filename.replace('_true','_false');
neither jQuery nor regexp necessary
<img src="FileName_true.png"
onclick="this.src=(this.src.indexOf('_true')!=-1)?this.src.replace('true','false'):this.src.replace('false','true')" />
is what I could come up with at this late hour
To do this in php would be plain silly and would need a cookie
Solution 2:
The answer by mplungjan is great, but let me suggest some alternatives. Image swaps are best done with a sprite, so that there is never any delay switching between the images. Put both versions of the image side by side in a single file. Set that image to be the background of a div, and adjust the background position to display one or the other image.
Suppose "pic1_bw_color_sprite.png" was a 75x75 color image, with a 75x75 b/w image below it, making the final image 75px wide and 150px high. Set up your css like this:
#pic1
{
background-image: url(pic1_bw_color_sprite.png);
height: 75px;
width: 75px;
}
#pic1.bw
{
background-position: 0px -75px;
}
Then some simple jQuery to make it all work:
$("#pic1").click(function()
{
$(this).toggleClass("bw");
});
Try it here: http://jsfiddle.net/gilly3/B7esz/
As far as duplicating the code, that is one thing that jQuery is very good at avoiding. Just use a selector that includes every class that needs the behavior:
$("#pic1,#pic2,#pic3,#pic4").click(...);
// or
$(".bwSwap").click(...);
To store the current state in the form so that you can update your database, you need to get a reference to your form element, then set the value
property (or .val()
in jQuery).
$("#pic1").click(function()
{
$(this).toggleClass("bw");
$("#pic1isBW").val($(this).hasClass("bw"));
});
Post a Comment for "Javascript Replace Text After An Underscore"