having trouble calling a Jquery function from within PHP. I'm getting a syntax error when I'm using the below code:
if(!empty($_POST['selectAGE'])){
$username = $_POST['selectAGE'];
}
if(empty($_POST['selectAGE'])){
echo '<script type="text/javascript">'
, '$("#selectAGE").prepend("<option value=''></option>").val('');'
, '</script>';
}
Am I not escaping properly or something?
further to this, I'm then checking this select box by using
if ( form.selectAGE.selectedIndex == 0 ) { alert ( "Enter the correct Age." ); return false; }
however, once the form has been submitted, it eliminates the prepended 'empty' value and now the one you've selected is selectedindex 0. so the above check returns that you haven't entered it. How can I amend the line above to take this into account?
-
2Just a clarification: you are not "calling a jQuery function from within PHP". That would be impossible. What you're doing is echoing javascript/jquery code from PHP. That code will be run on the client (browser), whereas PHP runs on the server.bfavaretto– bfavaretto2012年06月11日 17:46:09 +00:00Commented Jun 11, 2012 at 17:46
3 Answers 3
Escape the characters here:
'$("#selectAGE").prepend("<option value=\'\'></option>").val(\'\');'
3 Comments
If the escaping is giving you trouble I would just write the JS, instead of echoing it out.
if(empty($_POST['selectAGE'])): ?>
<script type="text/javascript">
$('#selectAGE').prepend('<option value=""></option>').val('');
</script>
<?php endif;
I prefer using the endif instead of matching brackets between JS and PHP.
Comments
You need to escape the single quotes. Try this:
<?
if(!empty($_POST['selectAGE'])){
$username = $_POST['selectAGE'];
}
if(empty($_POST['selectAGE'])){
echo '<script type="text/javascript">',
echo '$("#selectAGE").prepend("<option value=\'\'></option>").val(\'\');'
, '</script>';
}
?>