Black Magic
Black Magic

Reputation: 85

echoing a jquery animation function with php

I am trying to echo this jquery function, with php. basically if the script detects a field of a form is not filled in then it will echo this and make the input text box turn red.

It works fine when it is not being echo'd.

echo('
<script type="text/javascript">
    $(document).ready(function() { 
        $(\'input\').animate({backgroundColor:\"#F00\"},200);
    });
</script>
');

any ideas?

Upvotes: 1

Views: 993

Answers (5)

Dr.Molle
Dr.Molle

Reputation: 117334

Furthermore: a hex-color-value is no numeric value you can use for animate() . By this, the error is fixed by removing the backslashes from the doublequotes, but your animation wouldn't show any effect.

Upvotes: 0

Valentin Flachsel
Valentin Flachsel

Reputation: 10825

You're over-doing it on the string escape. To keep it simple, just use single quotes around the echoed string, and use double quotes inside it. Something like:

echo('
<script type="text/javascript">
    $(document).ready(function() { 
        $("input").animate({backgroundColor: "#F00"}, 200);
    });
</script>
');

When you're echoing stuff, there are indeed some cases when you need to escape the quotes, but most of the times you can simply get away with it by using different types of quotes. For example, I'll never get it why people still do something like:

echo "<input type=\"text\" name=\"username\">";

as opposed to

echo '<input type="text" name="username">';

which makes your life a whole lot easier when you have to modify it.

Hope this helps !

Upvotes: 1

MOOD
MOOD

Reputation: 111

i didnt test it, but try that:

$nl = "\n";
echo '<script type="text/javascript">'.$nl;
echo '    $(document).ready(function() {'.$nl;
echo '        $("input").animate({backgroundColor:"#F00"},200);'.$nl;
echo '    });'.$nl;
echo '</script>'.$nl;

the $nl="\n" is only for linebreak (I prefer to use singlequotes in echos, so php didn't have to parse the content - just echo out).

Upvotes: -1

DiAngelo
DiAngelo

Reputation: 220

You shouldn't use \" there, just "

Upvotes: 0

Olaf Keijsers
Olaf Keijsers

Reputation: 566

I don't think you have to escape your quotes when the string is within single quotes. PHP won't parse the string, it will be output literally.

Upvotes: 2

Related Questions