php radio box values - php

Given that when using an html radio box, to send values to a php script, only the selected values is sent to the php script, still holds true.
Do I still need to check that the user has selected something, when I am only interested in the selected value being sent to the php script, if the user does not select anything we do nothing or I guess I could prompt the user to select something.
If so, whats the best way to handle this with regards to radio boxes?
<!--Using the radio box, a single selected value is sent to the php script for processing-->
<td width="100px" height="30px">
<input type = "radio"
name = "selection"
value = "Lays" />Lays Chips 0.99c<br />
<input type = "radio"
name = "selection"
value = "Ruffles" />Ruffles $1.85<br />

The user will be able to click the "submit" button even without selecting an option from your radiobox.
If it's ok to send the form without a selection and you just want to do something different (or ignore it) when nothing is selected, you can do this:
<?php
if (isset(($_POST['selection'])) {
//Use it.. and make sure to validate user input.
} else {
//nothing was selected. Do something or just ignore?
}
?>
OTOH, if you want to prevent submiting without a selection, you will need to use some JavaScript to do it.

Even if the radiobox is not set, you can still post the form back to the server. Unless, of course, you have Javascript that prevents one from clicking on the submit form if the radiobox is not set.
So, you still need to check whether the radiobox is set or not, before working on it.

Related

Override checkbox value set by PHP

The form used to add a new item into the database and edit existing items is the same form. A "Mode" is passed into the form to tell it if were adding something new or to load the existing item for editing. So....
<input type="checkbox" name="fflreq" id="fflreq" value="<?=$row['FFLr']?>" <?php if ($row['FFLr']=="Yes") {echo 'checked';} ?>>
When a new item is being added, $row['FFLr'] doesn't exist so of course the value is BLANK or NULL or i guess 0 if i don't initially check the checkbox- The form processor coverts this into a "No" and inserts it into the database.
Now here is my problem - When I come back to a item and the form is in edit mode, the VALUE in this checkbox is now "No" - when I am clicking the checkbox to change its status, I see the checkbox become 'checked' but the value is not changing. in other words the click/check status is not setting the value of $_POST['fflreq'] to YES or 1.
I thought, that checking or unchecking a form checkbox replaces whatever is currently in the value='' attribute with a 1 or 0 to represent yes/no on/off or whatever. Why would the value pulled in from the database not change on form submission?
You need to do it in this way:
<input type="checkbox" name="fflreq" id="fflreq" value="Yes" <?php if ($row['FFLr']=="Yes") {echo 'checked';} ?>>
and when submit the form if the above checkbox is checked then you recieved the $_POST["fflreq"] in the form submit page and if it is not checked you recieve nothing in $_POST
so in the submit page you can do this:
$fflreq = "No"
if(isset($_POST["fflreq"]) && $_POST["fflreq"] == "Yes")
{
$fflreq = $_POST["fflreq"];
}
//then you can simply do anything with the $fflreq such as inserting it into database etc.
I hope this can be of some help.
That's not how it works. If you have "checked" the check box then it (along with it's value) will be sent with the post/get (i.e. submission) of the form. If you haven't checked it, then it won't be set...
If the checkbox is active, the browser sends the key/value pair defined in the input tag. However, if the checkbox is not active, nothing at all is sent for this checkbox.
There are two options to deal with this:
The clean option is to be aware of this on the server side, and assume that the checkbox was not active whenever no value comes through.
A more dirty variant is having a <input type="hidden"> tag just before the checkbox, using the same name, but the value you need to see when the checkbox is inactive. This way, when the checkbox is active, you'll still get the desired value from the checkbox, because it will overwrite the hidden value. However, if the checkbox is inactive, you'll get the value from the hidden field.
Not really, the check/unchecked status is read out by looking if the HTML name attribute value is present in the $_POST param.
You can check this with:
<?
if (!empty($_POST['fflreq'])){ /*checked*/ }
else{ /*unchecked*/ }
?>
The value of the HTML attribute value always stays whatever it is in your HTML. So no user interaction (except JS) can change that.
Working with PHP empty() function lets you bypass all the "Yes" "1" string int casting issues.
Further I would use ternary notation for these kind of things:
<input type="checkbox" name="fflreq" id="fflreq"
value="<?=$row['FFLr']?>" <?=(!empty($row['FFLr'])?'checked':'')?>>

Calculating values in PHP with buttons

I am creating a calculator in PHP and I should have this kind of structure of my HTML, where my numbers are clickable buttons, and the number that has been first clicked will be the first value and the second number I click will be the second value. I have no idea on how its gonna work, is it possible? if so how here's my code
<html>
<head>
<title>Calculator</title>
</head>
<body>
<div id = "structure">
<?php
if(isset($_GET)){
$value += $_GET;
}
?>
<form method = "GET " action = "calculator.php">
<input type = "submit" name = "one" value = 1>
<input type = "submit" name = "two" value = 2>
<input type = "submit" name = "three" value = 3>
<input type = "submit" name = "operand" value = "+">
</br>
<input type = "submit" name = "four" value = 4>
<input type = "submit" name = "five" value = 5>
<input type = "submit" name = "six" value = 6>
<input type = "submit" name = "operand" value = "-">
</br>
</form>
</div>
</body>
</html>
I haven't put all the numbers in the calculator for posting purposes
As others mentioned, the best way to do this is to use Client-side coding (Javascript). However, if you have to write a PHP code, then you need to submit the form twice. The first time, put the input variable (first number) in a hidden input element of the form and have print the html again this time with the extra hidden input element. The second time, look for that hidden input value: if it exists then it means that the new input is the second number and the hidden input is the first number. Get the value of the hidden input, get the new number, add them together and display the results. Make sure you reset the hidden input value.
Since this is a book exercise and the point is for you to write the code, I'm not going to give you any code. But, I can point you in the right direction (or at least one of them).
Consider using some kind of value that can be sent with each request that stores the current accumulated value of all operations. This probably should be displayed somewhere and also placed in a field that PHP will be able to read on form submit (Hint: have you ever heard of the hidden input type?). How will you keep track of the last operation? Maybe you could use another one of these fields to store the operation until another button is pushed.
What code can you use to check if the form is submitted? How can you check which button is pushed. Which values will be set if + is pushed? How about if a number is pushed? What if multiple numbers are pushed in a row?
More things to consider: Try playing with a real calculator. When are results displayed? What order of operations is used? Every operation has a left hand side and a right hand side. What happens when you push multiple numbers in a row. What about decimals? Should there be a clear button?
You'll need a way to keep track of previous inputs. Every time you click a button, a request gets sent to the server with that info (in $_GET) but the old inputs are no longer available. A few methods:
Hidden form elements
Each time the user clicks, you read the value and output it back into the page in a hidden form element. Each time you have to read the value of the hidden element using your existing method with $_GET, figure out what you need to do mathematically, and save the old stuff and new stuff into the hidden element again for the next input.
See this page for an example.
Cookies
You can use setcookie to set a cookie with the value the user entered. Each time the user clicks a button, you want to load the value from the cookie and append the current input. When the user clicks the = button, you load the cookie data and parse the expression. You make it easier and store the parts of the expression in some kind of delimited string in the cookie so you have operand,operator,operand and then you can easily compute the result. Hitting a clear button would clear the value of the cookie.
This tizag tutorial is a pretty good example of what you want to do with cookies.
Javascript
Obviously the easiest way. Since the state will be maintained, you don't need to pass values back and forth.

Changing an checkbox input name with a button click function

I'm running into a problem with changing the name attribute on an input element when a button is clicked.
I have 3 buttons:
* Add Renter
* Delete Customer
* Update Customer
This is the input element:
<input type=\"checkbox\" name=\"todelete[]\" value=\"$busRow[0]\" class=\"check\" />
$busRow is the user's id..
The form is submitted to a php script that checks to see what button was set and does different actions for that button. When the user clicks the delete it loops through and deletes each customer that was in the todelete[] array. When the user clicks the Update Customer button i want to change the checkbox input's name to "id". Then my php script will grab the user's id instead of grabbing the array value and then redirect the user to the Update Customer page with the id stored on the URL.
This is the javascript i'm using at the bottom of the page:
<script type="text/javascript">
$("button").click(function () {
if ($(this).text() == "Update Customer") {
$('input.check').attr("name", "id");
}
});
</script>
When i get to the Update Customer page the id is not there in the URL and i can't pull any values based upon the ID :(
You're setting the name value to "id", instead of the value stored in value. Try this:
$("button").click(function () {
if ($(this).text() == "Update Customer") {
var element = $('input.check');
element.attr("name", element.attr("value"));
}
});
Although, I think you could just simply pass the value of the input tag instead of the name when the btn clicked is 'Update'. That would save you the hassle of changing these different attributes and could save you trouble.
Edit: I'm reading the OP again and see you want to set the name att to "id" and not the user's id??? You're question is vague and hard to understand what you're trying to do. You're leaving out crucial code that grabs this "id" and redirects the user.
Edit2: What's up with the semi-colon between your string concat? I hope that's not in your source code. Now seeing your redirect code. I think your problem lies in trying to change the tag's attributes/values with an 'input.check' selector. I would also say you should redesign the way you are implementing this. Your checkboxes shouldn't hold your user information. But regardless, I don't think you need to even change the name value. If update isset() then just make $id = (its current name value); Download firebug to debug your javascript code. Firebug will also show you errors in your code that wouldn't see otherwise. It should help you out a lot
Try putting an alert inside the if statement to check if that is actually becoming true, to narrow down what might be the cause.
Also I've never seen input.check used as a selector. Perhaps give the button an id making it:
<input id=\"customercheck\" type=\"checkbox\" name=\"todelete[]\" value=\"$busRow[0]\" class=\"check\" />
Then change the attribute via the ID like so:
$('#customercheck').attr("name", "id");
that also saves you if you add another input to the field later down the road.

replace input field with data from mysql php

I created this layout of successive text input fields,
1- Enter data into empty fields
2- Click on button which submits to a php page that updates into database
Now the problem is that i want when i return to the main page again the empty field is replaced with data just added but there are still other empty fields to enter new data.
How can i establish that?
Thanks in advance.
You haven't given a lot of detail but here goes!
You could build your inputs like this:
<input type="text" name="age" value="<?php echo $age; ?>">
When the form first loads, it won't have values for variables like $age, so the input will appear empty. Have the form submit via POST to the same PHP file, run your validation checks, and if everything passes, insert into to your database. (Is it required that you write to the database at this point, or should it wait until the second section is filled out?)
You'll need to use some kind of conditional statement to display the second part of the form. Depending on how complex this is, or whether users will be returning later, you could:
Read the data back out of the
database to check for completeness,
and then display the second part.
Set a variable to track what stage of the form you're in, and based on that, display different sections to be completed.
If you have a way of tracking what stage of the process you're in, you could do something like this:
$formStage = 2;
function isReadOnly($formStage='')
{
if ($formStage == 2) {echo 'READONLY';}
}
and then in your HTML:
<INPUT NAME="realname" VALUE="Hi There" <?php isReadOnly($formStage)?>>

JQuery help with checkboxes and their values

I am very new to javascript and JQuery but I managed to get my first ajax script almost working 100%. Maybe today will be my lucky day and I can finish this up. :)
Let me give you guys a sample of each file so you know what is what. I believe that my last try at figuring this out was not successful because I was confusing these files. They are all js and have the exact same syntax.
What I have are 2 javascript files. One is called ajax.js and has the folling syntax. it calls ajax.php.
$("#admEmpID").bind("change", function(e){
$.getJSON("ajax.php?e=" + $("#admEmpID").val(),
function(data)
{
$.each(data, function(i,item)
{
if (item.field == "admEmpStatus")
{
// ?? radio buttons
}
............. etc
The next file I have is this script and is called admEmp.js. I think that this one is for my form validation.
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".admEmpBtn").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var admEmpID = $("input#admEmpID").val();
var admEmpStatus = $("input[name='admEmpStatus']:checked").val();
$.ajax({
type: "POST",...............etc.
What I would like to do is toggle my checkboxes according to the database results. If the result from the database is = 1 then the checkbox should be checked otherwise it should be unchecked.
These scripts that I have in place now will populate my textboxes from the values in the database so for someone like myself who has no idea what is happening with JQuery and its innerworkings, it is only natural for me to assume that the checkboxes will also be filled with the on/off values. Maybe I am incorrect. The last time I posted on SO looking for help, a guy mentioned that I needed to toggle the results with server side code. Is this correct or will JQuery do it for me?
I also have radio buttons in addition to the checkboxes that I need to show the values for as well. Just as a side note, the checkboxes are not grouped; they each have their own value.
Thanks for any help you guys can provide.
OK. "dz" said that I should put ('#admCustRptDly').attr('checked', true); into my script to see if that will allow me to see the checked attribute but it doesn't. The database has a 0 for that checkbox so I sould be seeing no checkmark. I put that into the ajax.js file. Here is what it looks like now.
else if (item.field == "admCustRptDly" && item.value == "1")
{
// $("checkbox#admCustRptDly").attr("checked", "checked");
$('#admCustRptDly').attr('checked', true);
}
Here is what I did that makes me think that I may be making some progress. I put an alert inside of the condition and I do NOT get an alert. If I go to a customer that does have the db value set to 1, then I do get the alert. That's more than I was getting before. But again, I am still seeing the checkmark even though the data in the db = '0'
Checkboxes behave a little differently than other input fields. When you have <input type="text" name="field1" value="foo" /> for example, the text field is automatically populated with "foo".
However, if you have <input type="checkbox" name="field2" value="1" />, the checkbox doesn't have anything to populate. This is because the checkbox has a special "checked" attribute that determines whether or not it is checked by default. As such, it's very possible your script that populates your textboxes are putting in the correct value for the checkbox, but are not setting the checked attribute.
To do so with jQuery, you can do $('#checkboxid').attr('checked', true);.
If I understand correctly, you have a form that is updated asynchronously via an Ajax call when you change the value in the #admEmpID field (first js file).
The second js file contains code to post changes you made to the form back to the server. I don't think it's for form validation (at least not the part you're showing).
But I'm not sure what the problem is. The first js file gets data from the server when you change some text field (#admEmpId). Is that data not shown correctly? You mention that textboxes are filled with the correct data. Are the checkboxes and radiobuttons not selected when they should be? In that case, you must first make sure you understand what data is returned from the server (contained in the data variable in the first js file). Then you must verify that the script addresses the right elements on your page to be updated.
You may just need another else if clause in your javascript for the case when you want to uncheck a box:
else if (item.field == "admCustRptDly" && item.value == "0")
{
$('#admCustRptDly').attr('checked', false);
}
You could, however, simplify both cases into a single statement like so:
else if (item.field == "admCustRptDly")
{
$('#admCustRptDly').attr('checked', ((item.value == "1") ? true : false));
}

Categories