PHP Submit form only if checkbox is ticked - php

I have a problem with a wordpress widget that I developed.
It 's just a form with an email field, a button and a checkbox.
When the user click on submit, I want to verify if the checkbox is ticked and IF YES submit the form...
My problem is that the form is submitted even tough the checkbox is not ticked. The page is reloaded.
Here is a short version of my code :
<?php if(isset($_POST['rules']) && $_POST['rules'] == 'Yes')
{
echo 'The checkbox was selected';
} else {
echo 'The checkbox wasn\'t selected';
} ?>
<form id="form-invite" method="post" action="">
<label>Your friend(s) email :</label>
<br/>
<small style="text-transform:uppercase;font-family:Arial;font-size:9px;color:#333;"<em>Multiple emails separated by comma.</em></small>
<input class="kolom" type="text" name="email" id="email"/>
<input class="button-primary classic-button" type="submit" name="send-them" value="Send Invitation"/>
<input type="checkbox" name="rules" value="Yes" /> <span id="rulesInfo">I read the Privacy Policy</span><br/>
<span id="emailInfo"></span>
</form>

Add a simple onsubmit handler to the form, e.g.:
<script>
document.getElementById("form-invite").onsubmit = function() {
return this.rules.checked;
}
</script>
Demo: http://jsfiddle.net/vqVEF/

Related

How Can I reset Html form's value with php?

This is my code:
<?php
class islem
{
function topla($a,$b,$c)
{
$c=$a + $b;
return $c;
}
}
if ($_POST) {
$a=intval($_POST['a']);
$b=intval($_POST['b']);
$c=intval($_POST['c']);
$toplama=new islem;
}
?>
<form action="" method="post">
Sayı 1
<input type="text" name="a">
<br>
<br>
<br>
Sayı 2
<input type="text" name="b">
<br>
<br>
<br>
Sonuç
**<input type="text" name="c" value="<?php echo $toplama->topla($a,$b,$c);?>">**
<br>
<button>Gönder</button>
<button type="reset" value="Temizle">Temizle</button>
</form>
I can reset input text fields, but how can I reset Post['C'] text fields?
When I click the reset(temizle) button, adding on its
The reset button will reset the form fields to what they were when the page was loaded. In this case, you have pre-filled content in your form, so clicking reset will simply undo any user changes since the page-load.
Here is an example of how you can reset the form fields that have pre-loaded data.
$(document).ready(function(){
$("#btn").click(function(){
$("#form")[0].reset();
});
});

Why are the nested forms processed with $_SERVER['PHP_SELF'] (same html file) not displaying/processing correctly?

I'm trying to get user input in a progressive sequence that leads to that input being sent by email. Sending by email is a whole other issue that I haven't tackled yet so not really worried about that.
The part I am having difficulty with is once the user gets to the "Send Email?" (Yes/No) radio buttons, the input from that question is not processed correctly.
I've gotten further with this by using a separate php file as the form action but still get errors related to emailName, emailAddress, and emailMsg not existing ("Notice: Undefined index...").
Furthermore, I still need to be able to use the $_POST[athletes] array further down but I'm guessing it's outside of the variable scope at that point.
So to bring that all together, I'm really asking a few questions:
1) How can I get all of the forms to work together in the same file?
2) When the program actually goes past the "Send Email?" radio buttons when I use a separate php file as the form action, why am I getting undefined index errors?
3) Why do I get an error when I try to use the athletes[] array further down in the code? Should I somehow be passing the array values to that part of the code?
The exact steps the user would take to get to the issue is:
Select 1 or more athlete checkboxes and click the 'Display Selection(s)' button.
Select 'Yes' for "Send Email?" and click the 'Submit' button.
Restarts the code for some reason.
Any help would be greatly appreciated. Also, this is my first post so sorry if I asked the question incorrectly or not according to site etiquette.
I also apologize for the long code fragment but I'm not sure what parts might be causing this to be incorrect.
<b><h1><center>Athelete Selection Screen</center></h1></b>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<fieldset>
<legend>Athletes Available: </legend>
<input type="checkbox" id="student1"
name="athletes[]" value="Student1 Test">
<label for="student1">Student1 Test</label><br/>
<font color="grey">Football - Running back</font><br/>
<p>
<input type="checkbox" id="student2"
name="athletes[]" value="Student2 Test">
<label for="student1">Student2 Test</label><br/>
<font color="grey">Soccer - Left Forward</font><br/>
</p>
<p>
<input type="checkbox" id="student3"
name="athletes[]" value="Student3 Test">
<label for="student1">Student3 Test</label><br/>
<font color="grey">Baseball - Pitcher/Left Outfield</font><br/>
</p>
</fieldset>
<p>
<?php echo("\t\t\t\t\t"); ?><button type="submit" name="submit" value="submit">Display Selection(s)</button>
</p>
</form>
<fieldset>
<legend>Athletes You Selected: </legend>
<?php
if (!empty($_POST['athletes']))
{
echo "<ul>";
foreach($_POST['athletes'] as $value)
{
echo "<li>$value</li>";
}
echo "</ul>";
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<fieldset>
<legend>Send Email? </legend>
<input type="radio" id="Yes"
name="radioSendMsg[]" value="Yes">
<label for="student1">Yes</label>
<p>
<input type="radio" id="No"
name="radioSendMsg[]" value="No">
<label for="student1">No</label><br/>
</p>
<button type="submit" name="submitRadio" value="submit">Submit</button>
</p>
</form>
<?php
if (!empty($_POST['radioSendMsg']))
{
foreach($_POST['radioSendMsg'] as $radioMsg)
{
if($radioMsg == "Yes")
{
echo "\tPlease enter information regarding the email to be sent: ";
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<label for="emailName"> Name: </label><br/>
<input type="text" size="25" id="emailName" name="emailName" />
</p>
<p>
<label for="emailAddress">E-mail Address: </label></br>
<input type="text" size="25" id="emailAddress" name="emailAddress" />
</p>
<p>
<textarea id="emailMsg" name="emailMsg" cols="30" rows="5"></textarea>
</p>
<button type="submit" name="emailSubmit" value="send">Send Message</button>
</form>
<?php
$msg = "Name: ".$_POST['emailName']."\n";
$msg.= "E-Mail: ".$_POST['emailAddress']."\n";
$msg.= "Message: ".$_POST['emailMsg']."\n";
$msg.= "<ul>";
foreach($_POST['athletes'] as $value)
{
$msg.= "<li>$value</li>\n";
}
$msg.= "</ul>";
$emailRecipient = "sjzerbib#gmail.com";
$emailSubject = "Athlete Selection Submission";
$emailHeaders = "From: Sebastien\n"."Reply-To: ".$_POST['emailAddress'];
mail($emailRecipient,$emailSubject,$msg,$emailHeaders);
echo "Message sent: \n".$msg;
}
else
{
?> <p /> <?php
echo "\n\nNo email will be sent for your last athlete selection.";
?>
<br/>Please click here
to return to the Athlete selection screen.
<?php
}
}
}
}
When you submit a form, only those controls contained within that form are included. The exception is successful controls that have the form attribute set to the id value of the form that was submitted.
So, given you had something like:
<form id="form-1" method="post">
<input type="text" name="first-input" />
</form>
<input type="text" name="second-input" />
The only value to be submitted would be that of first-input. If you add the form attribute to second-input:
<input type="text" name="second-input" form="form-1" />
Then the submission of the form would include both values. Unfortunately, the form attribute is not fully supported (IE and Edge have no support).
Of course, your markup is invalid, so that's a moot point. For starters, you cannot nest a form within a form. How a browser responds to markup that violates that rule is up to it's vendor, but in my experience is somewhat unpredictable. You're also using deprecated tags (<font> and <center> are no longer valid) and nesting elements incorrectly (<h1> is a block level element, whereas <b> is inline).
If you're doing a full submit each time (so the page gets submitted to itself and then reloads), then just use some sort of conditional to only render the dependent controls if the preceding form submissions were successful:
<?php
$canDoNextStep = !empty($_POST['input-1']);
?>
<form id="form-1" method="post">
<input type="text" name="first-input" />
<?php if(canDoNextStep): ?>
<input type="text" name="second-input" />
<?php endif; ?>
</form>
Lastly, whitespace is (mostly) ignored when your browser parses and displays your HTML, so you can lose the \t and \n values in your strings, unless you're concerned about how your markup looks if someone chooses to view source when using your form.

Associate input type checkbox to input type text

I have a problem, I need to associate a input type checkbox to a input type text.
The situation is as follows:
Extract data from a database. The PK data are the value of the checkbox. When a checbox select an input type text where you can enter a specific number is activated.
Now the problem is that selecting a checkbox input text all kinds are activated. And what I hope is that by selecting the checkbox input only the input associated with the checkbox enabled.
My HTML code (This code creates a input checkbox and input text for each record in the database, and what I want is to activate a specific checkbox is activated, the input type text):
<form action="send.php" method="POST" id="form-touch">
<?php foreach ($data as $key): ?>
<div id="inputsForm">
<input type="checkbox" class="id-check" name="nuevoid[]" value="<?php echo $key['pr_id'] ?>">
<input type="newquantity[]" class="myinput" disabled name="newQuantity" value="" placeholder="Enter quantity">
</div>
<?php endforeach; ?>
<input type="submit" value="Send">
</form>
My jquery code (code that activates or deactivates the text field by selecting a checkbox):
$('.id-check').change(function(){
if ($('.id-check').is(':checked') == false){
$('.myinput').val('').prop('disabled', true);
} else {
$('.myinput').val('1').prop('disabled', false);
}
});
How I can achieve what I want? Greetings from Chile.
Try
$('.id-check').change(function() {
if ($(this).is(':checked') == false) {
$(this).closest('div').find('.myinput').val('').prop('disabled', true);
} else {
$(this).closest('div').find('.myinput').val('1').prop('disabled', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="send.php" method="POST" id="form-touch">
<div id="inputsForm">
<input type="checkbox" class="id-check" name="nuevoid[]" value="">
<input type="newquantity[]" class="myinput" disabled name="newQuantity" value="" placeholder="Enter quantity">
</div>
<div id="inputsForm">
<input type="checkbox" class="id-check" name="nuevoid[]" value="1">
<input type="newquantity[]" class="myinput" disabled name="newQuantity" value="" placeholder="Enter quantity">
</div>
<input type="submit" value="Send">
</form>
you can use .next() jQuery selector. I have modified your jQuery change handler below. It works for me so try it. It should work for you too.
$('.id-check').change(function(){
if ($(this).is(':checked') == false){
$(this).next().val('').prop('disabled', true);
} else {
$(this).next().val('1').prop('disabled', false);
}
});
Goodluck and happy coding! :-)

Redirecting to the other page after submitting radio button option

I have a problem with my form. I need it to redirect user to different pages basing on which radio button was selected. User has to choose one of two options and click next, and according to his choice, page should redirect him to other page.
Here is the code as it looks for now
<fieldset>
<legend>Select option</legend>
<center>
<form method="post" action="">
<input type="radio" name="radio1" value="Osoba fizyczna"/>Non-company
</br>
<input type="radio" name="radio2" value="Firma"/>Company
</br>
<input type = "submit", class = "buttonStyle2", value=""/>
</form>
</center>
</fieldset>
and then php code
if(isset($_POST['Company'])
header("Location: http://myaddress.com/company.php");
Big thanks in advance for your help
Here is one way to achieve this.
Sidenote: Make sure you're not outputting before header. Consult this page on Stack about possible Headers already sent..., should this occur and making sure error reporting is set/on.
Otherwise, PHP will fail silently.
if(isset($_POST['radio1']) && ($_POST['radio1']) == "Osoba fizyczna"){
header("Location: http://www.example.com/non_company.php");
}
elseif(isset($_POST['radio1']) && ($_POST['radio1']) == "Firma"){
header("Location: http://www.example.com/company.php");
}
else{
header("Location: http://www.example.com/redirect_to_home.php");
}
Nota: The else would be if the person did not make a choice and simply clicked on submit without making a selection.
while using radio buttons of the same group name in your form:
<input type="radio" name="radio1" value="Osoba fizyczna"/>Non-company
</br>
<input type="radio" name="radio1" value="Firma"/>Company
Note about
<input type = "submit", class = "buttonStyle2", value=""/>
remove the commas
<input type = "submit" class = "buttonStyle2" value=""/>
Since HTML source in FF will reveal No space between attributes in red/as an error.
<fieldset>
<legend>Select option</legend>
<center>
<form method="post" action="">
<input type="radio" name="radio1" value="Osoba fizyczna"/>Non-company
</br>
<input type="radio" name="radio1" value="Firma"/>Company
</br>
<input type = "submit" class = "buttonStyle2" value=""/>
</form>
</center>
</fieldset>
and
if ( isset($_POST['radio1']) ) {
$filename = $_POST['radio1'] . "php";
header("Location: http://myaddress.com/".$filename);
}
Might be even better to set up an array with allowed values and check if radio1 is in that array.

Checking which radio button is selected in PHP

I have an HTML page that contains two radio buttons ("yes" and "no") along with a submit button.
How can I specify that I want to execute a PostgreSQL query ONLY if the submit button is pressed AND the "yes" radio button is selected?
Your radio buttons need to have the same name, so check the value that is submitted for that field:
if ($_POST['radio'] == 'Yes')
{
// Execute query
}
Given HTML like this
<form action="foo.php" method="post">
<label for="yesno_yes">
<input type="radio" name="yesno" value="yes" id="yesno_yes"> Yes
</label>
<label for="yesno_no">
<input type="radio" name="yesno" value="no" id="yesno_no"> No
</label>
<input type="submit" name="submit_btn" value="Submit">
</form>
You can check using this
<?php
if (isset($_POST['submit_btn'], $_POST['yesno']) && $_POST['yesno'] == 'yes') {
// do stuff here
}

Categories