toggle() div element with submitting form data - javascript

this is my problem:
After submitting a form I want to see some data from a database (MySQL) for the selected object in a div-element. This element was set to “display:none” when the page starts.
If the user clicks a button the <div> should become visible and the data should be seen. With another click the <div> should become invisible again. To achieve this I use the jQuery function toggle().
If I use an input-element with “type=submit” the form is submitted and I get the data due to the php statements in the <div>. But unfortunately the <div> will disappear immediately. I guess the submit is starting the page again by default and therefore the <div> is set to “display:none” again.
If I use a button-element instead I am able to toggle the <div> but the form is not submitted, the $_POST is not filled and therefore I did not get any data from the database for the object. The idea was to use the name of the object to set a value for an $id variable to start the SQL-statement.
I tried to keep the source code very short and therefore I did not program the database related statements here. This is not the problem – I am able to get data for the object when I used a normal submit and no toggle function for the <div>.
As you can see in the source code I tried it with three variations of input types. But none of it works like I want it to work.
I know that everything would be easy using another extra page to show the data. But I want to realize it with the <div>.
How can I solve this situation?
Here is my source code:
<!DOCTYPE html>
<html>
<head>
<style>
#wbtogdiv {
width:30%;
height:100px;
border:6px solid green;
display:none;
}
</style>
<script language="JavaScript" src="jquery-1.11.2.js"></script>
<script language="JavaScript">$(document).ready(function(){$("#btn").click(function(){$("#wbtogdiv").fadeToggle(20);return true;});});</script>
</head>
<body style="color:#FF004C;">
<!-- I tried also with this
action="<?php $_SERVER['PHP_SELF']?>"
but of course then the page is fired again and the <div> is not visible due to the
CSS-->
<form method="post">
<input type="text" name="customer">
<input type="submit" id="btn" value="submit:Toggle div green">
<!--
<input type="submit" id="btn" value="submit:Toggle div green">
<input type="button" id="btn" value="input button: Toggle div green">
<button type="button" id="btn">Button: Toggle div green</button>
-->
</form>
<div id="wbtogdiv">KASTEN: <?php echo print_r($_POST)?></div>
</body>
</html>

By default, a button element will submit a form, however, you overrode that behavior by setting type="button". (A tad counterintuitive, I agree.)
Since you're already using jQuery, you can take advantage of its built-in AJAX support and override the default form submission behavior. That's an approach that degrades gracefully: if a user is running in an environment that doesn't execute JavaScript, they will submit the form using default browser behavior and still see the results. (You would tweak your CSS to make your div visible by default in that case, and use JS to hide it during page load.) DEMO jsFiddle
var $form = $('form');
var $resultDiv = $('#wbtogdiv');
$resultDiv.hide();
var successHandler = function(data, textStatus, jqXhr) {
$resultDiv.html(data);
$resultDiv.fadeToggle(200);
};
$form.submit(function(ev) {
ev.preventDefault();
if (! $resultDiv.is(':visible')) {
$.post(
'/path/to/your/script',
$form.serialize(),
successHandler
);
} else {
$resultDiv.fadeToggle(200);
}
});
(Also, since this is a test post, it's possible you aren't doing this in your actual code, but for heaven's sake, be extremely careful about a script that reveals information about its internal working to a user, or a script that echoes user-supplied content, unescaped, back to a web page. These are the first steps toward a fairly major security hole.)

You can try this :
Do not use display: none; in CSS and instead do it by JQuery.
<style>
#wbtogdiv {
width:30%;
height:100px;
border:6px solid green;
}
</style>
And this is what you do :
<div id="wbtogdiv" form-submitted = "no">KASTEN: <?php echo print_r($_POST)?></div>
<script>
$(document).ready(function(){
if($('#wbtogdiv').attr('form-submitted') == "no") {
$('#wbtogdiv').hide();
}
});
$(document).ready(function(){
$("#btn").submit(function(event){
$("#wbtogdiv").fadeToggle(20);
return true;
$("#wbtogdiv").attr('form-submitted', "yes");
});
});
</script>

Related

Append input field value to url on button click

I'm very new to coding, so please forgive me if this is a dumb question.
I'm working on an assignment where I have to add functionality and styles to an existing bootstrap HTML doc. The purpose is to allow people to enter a dollar amount into an input field either by typing in an amount or by clicking buttons that populate the field with set amounts. One of my instructions was to update the donate submit button so that it appends the chosen donation amount to the "/thank-you" URL.
This is what I have for the input field:
<form id="amountSend">
<input type="text" class="form-control donation-amount-input" placeholder="Other" id="other-amount"/>
</form>
This is what I have for the button:
<button id="donateBtn" type="submit" action="/thank-you"
method="get">DONATE<span class="metric-amount"></span></button>
And I was thinking that the jQuery would look something like this, though the submit function is not currently giving me any visible results.
$("#donateBtn").click(function() {
if (!$.isNumeric($("#other-amount").val())) {
$("#dataWarning").show();
$(".metric-amount").hide();
$(".metric-message").hide();
} else {
$("#amountSend").submit(function() {
var url = "/thank-you";
$(".metric-amount").appendTo("url");
});
}
})
I also got some decent results using a PHP method:
<form id="amountSend" method="post" action="/thank-you.php">
<input type="text" class="form-control donation-amount-input" placeholder="Other" id="other-amount" name="donation"></input>
</form>
<button id="donateBtn" type="submit">DONATE<span class="metric-amount"></span></button>
<script>
$("#donateBtn").click(function() {
if (!$.isNumeric($("#other-amount").val())) {
$("#dataWarning").show();
$(".metric-amount").hide();
$(".metric-message").hide();
} else {
$("#amountSend").submit();
}
});
</script>
This one will open the PHP file I set up (/thank-you.php, which i have stored just in the same root folder as my main HTML doc), but all the browser gives me is the raw HTML code of the PHP file. Here's the code I have in the PHP file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
Thank you for your donation of
<?php echo $_POST["donation"]; ?><br>
</body>
</html>
Anyway, I guess I'm wondering if I'm on the right track? Should I pursue the jQuery or PHP method? Can I even do this using only jQuery? I've seen a few posts on this subject already, but I thought I'd make a new one since the ones I've seen are all fairly vague, I haven't seen the same answer twice, and I'm not sure I fully understand exactly what I'm trying to accomplish, in terms of a visual confirmation of results.
Thanks!
First of all, you have several issues with your code.
Number one: The formulary you have there is bad coded, the form tag needs to have the action and method attributes, not the submit button.
And in top of that, the submit button needs to be inside the form tag, if is not in there, it will not have and kind of effect.
Number two: If you are gonna submit the formulary to a php file and handle the request there ,you need the file to be running on a server (local or whatever). PHP is a server language, if you open the file directly in a browser, it will show you the code it has inside and will not work.
Hope it helps!

JavaScript code keeps failing

I have hidden a div tag and I am using JavaScript to make that div tag appear on the screen upon form submission, the problem is that the div tag appears but then it quickly disappears, I have no idea what is going on, I need it to stop disappearing, once the form is submit the div tag should remain visible on the page, the div tag only contains a p tag with some text, I have tried onClick on the button but I get the same result.
<html>
<body>
<form onSubmit="validateRadio()">
<div style="display: none" id="validationText" >
<p style="border: 1px solid black;">
"This field is mandatory".
</p>
</div>
<div>
<input type="submit">
</div>
</form>
</body>
<script type="text/javascript">
function validateRadio(){
validationText.style.display="block";
}
</script>
</html>
Your page is likely refreshing (the action parameter defaults to the current URL if it isn't provided) which causes the DIV to "reappear". If you would like to block the form submission, use onSubmit but make sure to return false in your method.
function validateRadio(){
validationText.style.display="block";
// returning false will prevent the form submission
return false;
}
You're not doing anything to prevent the form from actually being submitted. Change your function to return false:
function validateRadio() {
validationText.style.display = "block";
return false;
}
and your handler to <form onSubmit="return validateRadio()">
jsFiddle example
Yes..
when you submit form, a new page is loaded (or same page is reloaded)
If you will see your validationText, you did'nt submit page, for example transform your
<form onSubmit="return validateRadio()">
and
function validateRadio(){
validationText.style.display="block";
return false
}

How to create an HTML button that show more text same page

I'm working with html and javascript. My problems is, in one webpage a show a plot and a few button. When the user press any of this button I need show 3 or 4 options but in the same page without switching pages.
Below is my code
<form action="MyPage">
<button type="submit" value="More Options">
</form>
redirect to an other page.What I can do?
First of all, get rid of type="submit". That's what's causing the page to do stuff you don't want. The second thing is to add an onclick handler. It should return false to avoid behavior like "submit". The variable 'this' will pass the button to your function, which you might need in that code. Then fill in the body of addMoreStuff() with your code to, well, add more stuff!
<form action="MyPage">
<button onclick="addMoreStuff(this); return false; ">More Options</button>
</form>
<script type="text/javascript">
function addMoreStuff(button) {
/* your code here */
}
</script>
Drop the form (use the button alone), and look into jQuery. It's extremely easy to use, and it'll help you quickly build code your application.
HTML
<button type="submit" value="More Options" id="more">
JavaScript (jQuery)
// run "add_options" when someone clicks on the button
jQuery('button#more').on('click', add_options)
function add_options() {
//code here to add more options
}

How do I use this JQuery code to clean input fields of their content onclick of reset button?

Code:
<script type="text/javascript">
$(".reset_form").click(function() {
$(this).closest('form').find("input, textarea").val("");
});
</script>
Button:
<div class="reset_form">
<a class="anchor_link">
<span class="reset_button">
Reset
</span>
</a>
</div>
Using the code above I want to be able to clean input fields of their content when a user clicks on reset_form. However, being new to JS/JQuery I am unsure as to how to accomplish this since I am not using an input button but a div that looks like a button.
Question
How can i tweak my code so that when a user clicks on .reset_button that the fields will be cleared?
<div class="form-container">
<form>
<input type="text" />
<textarea></textarea>
</form>
<div class="clear-form">
<span class="reset_button">Reset form</span>
</div>
</div>
$(document).ready(function() {
$('.clear-form').on('click', function() {
$(this).closest('.form-container').find('input, textarea').val('');
});
});
Fiddle
In order to help you use the DOM traversal selectors like closest() and find(), it is first necessary to know roughly where your form is in relation to the .reset_form <div>, does it have an ID attribute (which makes it very easy to select the form), etc.
However, assuming there is only one form on the page, then this code will work:
Working jsFiddle example
$(".reset_form").click(function() {
$('form').find("input, textarea").val("");
});
As Jedediah mentions below, the above code will reset/clear all forms on the page. If you only wish to clear one specific form, then you can specify an ID in your form tag, thus:
<form id="justthisform"> ... </form>
You can clear only that form by modifying the active line as follows:
$('#justthisform').find("input, textarea").val("");
If you want to clear all elements in the form (radio reset to defaults, dropdowns, etc) you can use the native reset on the form DOM object but use jquery to find it like this:
<script type="text/javascript">
$(".reset_form").click(function() {
$(this).closest('form')[0].reset();
});
</script>
Well one thing to note is that HTML forms natively support resetting via a reset function in the browser:
$(".reset_form").click(function() {
$(this).closest('form')[0].reset();
});
But yeah if your function isn't working then it looks like your (fake) button isn't embedded within the form itself. jQuery's .closest() function will find the form if you do
$(this).closest("form")
So the only thing you need to fix is finding that form.

Automatically making a div appear based on status of radio button with JavaScript

I have a form which posts data to the same page. Based on the user's radio button selection I am inserting checked="checked" into the radio button form element to redisplay the correct selection. This works fine, however when the form is redisplayed (in case of bad input etc), I need a div to be revealed (containing the relevant fields from the form).
I have an onclick event that reveals the div in the first place (before the user has posted the form), and this works fine, but when I redisplay the form I don't want the user to have to manually reveal the form again by clicking.
Therefore I've been trying something along the following lines (heavily cut down for the purposes of this post)...
<link href="styles/style1.css" rel="stylesheet" type="text/css" />
<script language="JavaScript">
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
</script>
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes
<input id="complete_no" type="radio" name="complete" value="false"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
... but it returns an Object Required javascript error (as it does in the 'real' page):
Message: Object required
Line: 3
Char: 1
Code: 0
URI: http://localhost/repair_system/javascript_test.php
Why is this? Am I not correctly referencing the form element? Apologies if I'm being a "div" (deliberate bad pun intended!), I'm yet to learn about the fun and games of javascript!
Because your javascript is not wrapped inside a function, the browser is executing it as soon as it "gets to it". In this case, the JS is being executed before the browser has reached the html declaring your form.
The simplest fix therefore is to move the Javascript to after your form. A more robust solution would be to wrap you code in a function, and have that triggered somehow - from what you appear to be trying to do, in this case it'll be the onLoad event of the body tag:
<head>
<script language="JavaScript">
function showHelpDiv() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
</script>
</head>
<body onload="showHelpDiv()">
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes
<input id="complete_no" type="radio" name="complete" value="false"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
Your code is being executed as the document is being loaded, and the DOM tree isn't ready yet. So it is trying to access an element that doesn't exist yet.
You probably want to instead write an event handler that toggles the div whenever the checkbox is checked.
I prefer jQuery, which abstracts away things like cross-browser event handling, provides lots of nice helpers and generally makes code look cleaner (when written properly). Something like this should work:
$(document).ready(function() {
$('#repair_complete').toggle($('#complete_yes').is(':checked'));
}
The above can be roughly translated as:
When the document loads, perform the following:
Add an event handler for the 'change' event to any elements of type 'input' with a name of 'complete'
When the event handler fires, toggle the visibility of the element with ID 'repair_complete' where it should be visible if the element with ID 'complete_yes' is checked
Update: The JS above now actually does what you want, originally I had it written as an onclick
This is because Javascript is executed just before rest of the objects are created.
Place your javascript code into the function body, and add this function into onclick event for whatever you need.
<link href="styles/style1.css" rel="stylesheet" type="text/css" />
<script language="JavaScript">
function test() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
</script>
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true" onClick="javascript: test();"/>Yes
<input id="complete_no" type="radio" name="complete" value="false" onClick="javascript: test();"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
</form>
It looks to me as though your script is firing before the form is drawn, you may want to move your script block to after the form element. Basically I think that the document.getElementById('complete_yes').checked is looking at null.checked, which would trigger the object required error.
You should make the action of the radio button be to change the visibility of the div (that is, "push" the status to it), rather than to "pull" the div status via the radio button status at render time (which as Andrejs said, will be unset).
Sounds like the problem is in your initialization code. The javascript is being called before the page is finished rendering. It's one annoying aspect of the "onload" event that in my opinion simply doesn't work as it should in every browser.
There's a cross-browser technique to call initialization code once and only once after the DOM is fully loaded.
Try this code in the HEAD of your HTML:
function showHelpDiv() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
function InitOnce()
{
if (arguments.callee.done) return;
arguments.callee.done = true;
showHelpDiv();
}
/* for Mozilla */
if (document.addEventListener)
{
document.addEventListener("DOMContentLoaded", InitOnce, null);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script defer src=ie_onload.js><"+"/script>");
/*#end #*/
/* for other browsers */
window.onload = InitOnce;
And then you need to create an ie_onload.js file that contains this line for IE compatibility:
InitOnce();
I've tried other techniques but none work as perfectly as this. I believe I originally found this solution here:
http://dean.edwards.name/weblog/2005/09/busted/
I use it in an online application that receives 500 unique visits a day or so and this has been reliable for us.

Categories

Resources