I have some php conditional logic...basically I want to use jQuery to show or hide certain div's when I submit a form:
<?php
if (isset($_POST['submit']) {
/*
If the user submits the form and
use jQuery to hide an existing div tag
<script type="text/javascript">
$('#mydiv').hide();
</script>
*/
}
?>
Is there a sort-of non-messy way to go about mixing php and jQuery like this? I just want my j开发者_C百科Query to be in one block and my php to be in a separate block (i.e. not interspersed)
You can catch the "onClick" event with ajax and then do what you want with your div like :
in your HTML page :
<button type="button" onclick= "yourFunction()">Click Me!</button
and then in a separate javascript file:
yourfunction() {
$("div").hide();
}
EDIT : You don't need PHP if you only want to hide a div when the form is submitted
Well if you are simply trying to hide something after the form has been processed successfully then putting your JavaScript code inside that if block is as good place as any other. You would just need to take care that the DOM tree is actually ready before you try to hide an element.
if (isset($_POST['submit']) {
echo <<<JS
<script type="text/javascript">
$(document).ready(function(){
$('#mydiv').hide();
});
</script>
JS;
}
However if that DIV you are trying to hide contains important information which isn't supposed to be seen in case form processing fails you should "hide" your container on the server side.
$status = false; // Status of the form processing
if (isset($_POST['submit']) {
// If processing succeeds you set $status to true
}
<?php if($status){ ?>
<div id="myDiv">
// Your super secret ingredient formula!
</div>
<?php } ?>
精彩评论