Displaying "required" in just one checkbox (dynamic display) - php

I've created a database-driven test with three types of questions - input type = radio, text and checkbox. If I insert required before the closing tag, it works fine for the radio and text questions, but not the checkboxes.
The problem is that each checkbox question has several possible answers - anywhere from three to six. And the number of those choices that are correct answers also varies.
But when I add "required" to the checkbox script, the user has to select EVERY answer in order to proceed to the results page. This is what the code looks like:
<label for="q'.$QID.'-'.$Value.'"><input type="checkbox" name="q'.$QID.'[]" id="q'.$QID.'-'.$Value.'" value="'.$Value.'" **required**> '.$QA.'</label>
I found the HTML5 Required Attribute page, which appears to address this problem. If I understand correctly, you can fix the problem by inserting "required" in just one element. So if you insert it in answer A, a user could presumably choose answers C and D, and everything would work just fine.
If that's correct, then is there a way to make "required" display in just one checkbox, instead of all of them?

Use required using a condition for the first checkbox of a group. I assume your html code is written in .php files.
$required = ($Value == 0) ? "required" : ""; //condition to check if the value is first. since it is database driven it would be better to check the key instead of the value.;
echo '<label for="q'.$QID.'-'.$Value.'"><input type="checkbox" name="q'.$QID.'[]" id="q'.$QID.'-'.$Value.'" value="'.$Value.'" '. $required .'> '.$QA.'</label>';
Another solution is to add required attribute using Jquery. For eg if gender is the name of the group of checkboxes, then:
$('input[type=checkbox][name=gender]')[0].attr('required', 'required');;

Related

php $_POST variable variables

I am trying to populate an HTML form with values from a previous form being posted. The first form is created dynamically and is a list of t-shirt styles with 5 different sizes available.
I'm having trouble figuring out a way to populate the second form.
The HTML is this:
echo '<input name="'.$filename.'-s" type="text" size="3" value="'.$quantity.'"'>;
What I'd like to do for $quantity is something like this:
$quantity = $_POST['{$filename.$size}'];
Is it possible to use a variable with $_POST?
I think you're looking for this:
$quantity = htmlentities($_POST["$filename$size"]);
htmlentities() is necessary in case you have " or other junk in the input
$_POST[$var1.$var2] worked. Nothing came up in my initial search of previous answers, although I see several applicable questions in the related questions on this page.

Getting multi Values from a dropdown list in PHP

This is my drop down list.
<p align="center"><select size="1" name="bo_chose" id="boID">
<option selected value="Select...">Select...</option>
<?php
while ($list_bo = mysql_fetch_array($select_brof)) {
echo "<option value=\"$list_bo[bo_name] $list_bo[bo_code]\">$list_bo[bo_code],$list_bo[bo_name]</option>"; }
?>
</select></p>
So the drop down will show first "select..."
and then will retrieve data andlist the bo_name, bo_code in <option>
It works well.
The problem is, I want to carry the value to another PHP page which will delete the
selected option in the drop down.
Of course the MySQL and PHP will complain that it does not exist ...why?
Its taking the new value $bo_chose (name of the dropdown list) as a new value
as (bo_name, bo_code) — as one value not as a split values.
So if the dropdown list is (george Mike GM)
the data will complain that there is no value called "George Mike GM"
when I want it to carry only "GM" which is the bo_code.
Can anyone help?
Just split the value with space as delimiter and pick the first value. May I know why do you
need to carry both name and id in first place.
You should just add $list_bo['bo_code'] as option value instead of both.
If I understand you correctly you have this select inside a POST form or you are sending it by ajax to the script you want to parse the value. Use a separator to merge these two variables. The separator should be a char that you are sure, it will never be in either of two variables. So, you can for example use ; for the separator and write $list_bo[bo_name].';'.$list_bo[bo_code]. In the recieving script you just explode the value by separator and you will get both values as array. If you are unsure which chars will be in both variables, you can either json_encode or serialize it before puting it into html.

PHP Array combining 2 or more values together

I am curious know if and how it is possible to combine 2 values of an array together instead of overriding the other. I will show you an example:
I have a form that is mapping fields to a database from a CSV file. The problem I am running into is say for example there are 2 address fields that need to be merged into 1 address field in my database. (IE: photo below)
So my problem comes when I look at the $_POST[] array. It will show that there are 2 HOME ADDRESSES Selected and import into my database with the LAST selected home-address.
How can I merge the information into 1. I hope this gives you enough information on my problem, please let me know if you need something specific.
I am dealing with all arrays, and when I post into my database it requires an Array to loop through, as I use a reflection class. I hope this makes sense...
Any light would be appreciated on this matter.
Cheers,
I appreciate the quite comments back, the problem that I have with your responses is that I can't create my inputs to be address[] as that will be dynamic and I won't know which one will be set to address and which would perhaps be set to 'phone'... I hope this new picture helps a bit in understanding.
Some of the code (Shortened):
<select name="Home_Address_1"> // name is dynamically generated from the CSV headings
<option>...</option>
</select>
<select name="Home_Address_2"> // name is dynamically generated from the CSV headings
<option>...</option>
</select>
Example of using two posted values in a single array:
<!-- HTML -->
<input name="address[]" type="text" value="111" />
<input name="address[]" type="text" value="222" />
Notice the name attributes.
// PHP
$address = $_POST['address'][0] . ' ' . $_POST['address'][1];
echo $address; // prints "111 222"
UPDATE
Before your script loops through the $_POST array, merge the fields, like so:
$preformat = $_POST['Home_Address_1'];
$preformat .= ' ' . $_POST['Home_Address_2'];
$preformat .= ' ' . $_POST['Home_Address_3'];
$_POST['Home_Address_3'] = trim($preformat);
Then the last Home Address field contains all three.
Try array_merge()...http://php.net/manual/en/function.array-merge.php
Try array_merge with shuffle
$merged = array_merge($arr1,$arr2);
shuffle($merged);
with regards
Wazzy

if statement in php form and form output

I am creating a order form for a meat locker company that sends the form to their email. There is a lot of where if you select one item you can not select another item; such as t-bone and New York Strip, you can have one or the other, but not both. Here is what my code looks like.
<P>T-bone steak <input type="radio" name="T-bone and NY" id="T-bone steak" />
or New York Strip steak <input type="radio" name="T-bone and NY" id="New York Strip" /> </p>
This does prevent a person from selecting both, but when he views in in his email he sees name="T-bone and NY" so he doesn't know which one they selected. I thought it would display the id="T-bone" or "NY Strip". I'm sure there is a better way of doing this with an if statement.
Second, when they receive the email it has all of the names of the fields people selected and it says on afterwords. For example if someone selected Prime rib the email would say:
Prime Rib: on
Is there a way to send the form exactly as the user sees it. Maybe in an image, word doc, or access data base?? I'm open to anything.
If your want to see it the url is www.spillvillelocker.com/beef.php
Thank you very much:)
Your code should look like this:
<P>
T-bone steak <input type="radio" name="steak" value="T-bone steak" id="tbonesteak" />
or New York Strip steak <input type="radio" name="steak" value="New York Strip" id="nystrip" />
</p>
Notice, I have "name" be the same for both, with different "values". Also, "id" attributes shouldn't contain spaces, so I changed them to something alphanumeric only.
I think you just need to provide a VALUE="" attribute to show which value each radio button specifies... also NAME and ID should be equal.
<P>T-bone steak <input type="radio" name="MEAT1" id="MEAT1" value="TBONE"/>
or New York Strip steak <input type="radio" name="MEAT1" id="MEAT1" value="NYSTRIP"/> </p>
You need to set value attributes of those inputs.
BTW you should not have spaces in name attributes.
In addition to what Mike posted, regarding your second question "why the email says 'Prime Rib: on', it is again because there is no value attribute assigned to the element. The default values for radio buttons are 'on' and 'off'. Without setting an explicit value, you're left with the defaults.
There are two things that you can do for this.
Set an explicit value for the form element, something like
<input type="radio" name="primeRib" value="Yes"> Prime Rib
That will show up as 'primeRib: Yes' in the email.
The second thing you can do is use PHP to parse your responses to only send the data you want. Something along the lines of:
<?php
foreach ($_POST as $key=>$value) {
if ($value=="off") {
continue;
}
else {
$email.="$key\n";
}
}
?>
Something like that would skip over each $_POST variable that is set to "off" and for each variable that isn't, it would add the $key (the data inside the "name" attribute) to the $email variable, or however you add the data to the email to be sent out. There's a number of things that you can do, but at least this would allow you to filter only for variables that are on/checked.

populating a text area/field with existing data

I have a page to edit user information, and I wish to show the current information and allow it for editing, to avoid overwriting existing information.
At the moment, I am fetching the data and displaying it in a text area like so:
$usernameQuery = "select username, firstname from USERS where username = '" . $con->escape_string($username) . "'";
$xblah = $con->query($usernameQuery);
while ($row = mysqli_fetch_assoc($xblah))
{
$checkUsername = $row['username'];
$checkFirstName = $row['firstname'];
}
echo "<form name=\"userForm\">
<h1>Editing information for: ".$username."</h1>
<p>
First name:
<textarea rows=\"1\" id=\"firstname\">".$checkFirstName."</textarea>
<br />
</form>"
This text area does not display correctly in firefox, due to a bug of displaying two rows when one is specified. Is there any way to do the same thing with input type=text?
Also, at present, the contents of firstname in the database is john for my testrecord, but var_dump($checkFirstName) shows just s. What must I do to get the actual contents of the field?
Is there any way to do the same thing with input type=text?
<input type="text" name="firstname" value="<?= $checkFirstName ?>" />
As for your other issue, is there another user that has a first name of 's', but also has the same username as the user with the first name of 'john'? The reason I'm saying this is that you use a while loop to fetch your data, so if there are multiple matches, you are going to be left with the last row that matched your query.
Possible ways to resolve this issue include not using a while loop (which implies that you want to fetch/process multiple rows of data) and making sure that all usernames are unique.
Other than that, I don't see why the value fetched from 'firstname' wouldn't match what is in the database.
If you use the input type=text input, anything you put in the value attribute will be shown by default.
echo '<input type="text" value="' . $checkFirstName . '">';
Of course, you'll want to make sure you do some sanitation on $checkFirstName before outputting it into that field, just in case.
As for getting the values of your field, trying var_dumping $row before your while loop, and see if you can figure out what's going wrong with that. If it doesn't show anything helpful, maybe var_dump inside your while loop with a nice < hr > in between each iteration? This should give you a full view of exactly what is being returned in its entirety from your query. Also, if var_dump is a bit too much information for you, check out:
print_r($var)
print_r documentation
Use the 'value' attribute of the input tag.
First name: <input type=\"text\" name=\"name\" value=\"$checkFirstName\"/><br />
textareas are meant to display multiline text with linebreaks. user- and first names are usually not meant to contain those, so better use the input element
<?php
echo '<input type="text" name="name" value="' . htmlentities($checkFirstName) . '">';
?>
don't forget about htmlentities or htmlspecialchars (depends on the encoding - if your encoding is unicode, htmlspecialchars should be sufficient, otherwise its htmlentities). don't use htmlentities just for form fields, but whenever you print user-provided data. otherwise someone could inject xss (cross site scripting) attacks or at least generate faulty html by providing an username like
<script type="text/javascript">execute_evil_code();</script>
as for displaying only one char instead of a full string: normally, this happens if you think you're working with an array and instead have a string. use var_dump($variable); to see the type of your variables.
also, as htw said, check if $username really is unique and you're getting the right row. run the resulting query (echo $usernameQuery;) in phpmyadmin (or whatever tool you're using). if more than one line is returned, your username's not unique (probably a bug in itself) and the row you get is nor the first, but the last one. it's strange, because 's' is not part of "john", so maybe the mysql result set is something completely different. debug at a higher level, and var_dump the whole $row.
Try put all your php code over here:
<textarea id="firstname" rows="1">
<?php
//connect to database
//Select data
if(mysql_num_rows($sql)) {
$row = mysql_fetch_row($sql);
echo nl2br($row['0']);
}
?>
</textarea>

Categories