Reputation: 125
I have a form with two div elements see code below:
id="hide_onclick"
: should hide when a submit button is clickedid="show_onclick"
: should display when a submit button is
clickedHowever when the Javascript executes on onClick
, DIV2 displays query results in a flash and hides back. If i change the input type="submit"
to type="button"
, DIV2 shows properly but i wont be able to get query results.
I could not figure out how to fix this.
<!--Form uses vehicle registration to pull record from database -->
<form class="form-horizontal" method="post">
<div class="row" style="padding-bottom:10px;">
<div class="col-sm-4">
Vehicle Registration
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="vehiclereg" value="<?php echo $vehiclereg;?>" />
</div>
</div>
<!--Visible div to hide on button click -->
<div id="hide_onclick">
<div class="row" style="padding-bottom:10px;">
<div class="form-group">
<div class="col-xs-12">
<input type="submit" name="retrieve_vehicle" value="Click to retrieve vehicle" onclick="show_hideDiv();" />
</div>
</div>
</div>
</div>
<!--Hidden div to display after the onclick event from the button above and displays the records-->
<div id="show_onclick" style="display:none;">
Upadates from database
</div>
</form>
<!--Javascript to hide the first div and display the second div -->
<script>
function show_hideDiv() {
document.getElementById("hide_onclick").style.display = "none";
document.getElementById("hide_onclick").disabled = true;
document.getElementById("show_onclick").style.display = "block";
}
</script>
Upvotes: 1
Views: 2427
Reputation: 121
The explanation is as LcSalazar says. The solution (or perhaps a hack) I found, is using the display code from within the hidden div AGAIN.
Remember, you should keep all the rest of your codes.
<!--Hidden div to display after the onclick event from the button above and displays the records-->
<div id="show_onclick" style="display:none;">
<!-- keeps the div visible after the page refresh -->
<script>$('#show_onclick').css('display','block');</script>
<!-- Updates from database -->
</div>
Upvotes: 0
Reputation: 886
There is a basic difference between type ="submit" and type="button". type="submit" will submit your form and reload the page. Thats why your div2 shows up untill the page load back. On the other hand type="button" do not submit the page ( page does not reload) , it only calls your show_hidediv() function. My suggestion is to use ajax for this kind of situation where you dont want to reload your page but want to retrieve data from database.
Upvotes: 1
Reputation: 16841
It's because when you submit a form, it redirects the page to the action
attribute. In your case, since you have none, it will refresh the page.
So, you are changing the div2 to visible, but then the page refreshs and goes back to the initial state...
Upvotes: 1