I’m building up a code block and have run into a problem that makes me curious why ampersands won’t encode from the WordPress text editor view. This code works as expected, giving me the alerts I’m looking for when it’s embedded directly in the page through the text editor:
// This code works as expected
<script>
jQuery(document).ready(function() {
if (jQuery('select[name=idx-q-PropertyTypes]:first').val()=='') {alert ('it exists');} else {alert ('cant find it');}
jQuery('.dsidx-resp-area-submit input').click(function(e){
alert ("you clicked it");
if (jQuery('select[name=idx-q-PropertyTypes]:first').val()=='') {
alert ('There were no search parameters.');
e.preventDefault();
}
});
});
</script>
The next thing I wanted to do is check for a concurrence of conditions. So I changed the code to this:
// This code gives errors
<script>
jQuery(document).ready(function() {
if (jQuery('select[name=idx-q-PropertyTypes]:first').val()=='') {alert ('it exists');} else {alert ('cant find it');}
jQuery('.dsidx-resp-area-submit input').click(function(e){
alert ("you clicked it");
if (
jQuery('select[name=idx-q-PropertyTypes]:first').val()=='' &&
jQuery('select[name=idx-q-Cities]:first').val()=='' &&
jQuery('input[name=idx-q-PriceMin]:first').val()=='' &&
jQuery('input[name=idx-q-PriceMax]:first').val()=='' &&
jQuery('select[name=idx-q-BedsMin]:first').val()=='' &&
jQuery('select[name=idx-q-BathsMin]:first').val()=='' &&
jQuery('input[name=idx-q-ImprovedSqFtMin]:first').val()==''
) {
alert ('There were no search parameters.');
e.preventDefault();
}
});
});
</script>
The error I got at first is that I had used an illegal character. When I looked up where in the debugger, it was the double ampersands. They showed up as &
. So, next I tried replacing all of them with &
, which didn’t work. After replacing them like that, I got a new error saying that the conditional statement was missing a closing parenthesis. To fix that, I tried add a parenthesis at the end, enclosing each condition in a set of parentheses, and writing the whole condition on one line, each in turn, none of which worked. I also plugged it into a fiddle as this question suggested but that didn’t work either. After replacing them like that, I got a new error saying that the conditional statement was missing a closing parenthesis. To fix that, I tried add a parenthesis at the end, enclosing each condition in a set of parentheses, and writing the whole condition on one line, each in turn, none of which worked.
When I link to the script as an outside file, the ampersands encode correctly and the whole script works. Does anyone know why that would be and if there’s any way around this problem if I wanted to embed the script like I originally tried?
So you need your script inside CDATA but if you do not want to, just do this if you do not want to change the code.
Alternative: