Dynamically Hide Form Fields - php

I have a form for a 'user profile' with the following fields:
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
Phone Number: <input id="phone_number" />
City: <input id="city" />
</form>
However, what if I don't want "phone number" and "city" to be visible to a select set of users?
How can I dynamically hide these fields, depending on, say for example, which user is logged in? I am currently using PHP and MySQL. Would it be best to add the "field id's" to the database, and then query the database record to see which fields should be hidden and which fields should be visible? Or is there a better way to do this?
My apologies if this is a bit ambiguous. If it doesn't make sense, I can try to clarify.
Thanks very much.
EDIT: I'd like to clarify what I am trying to achieve. I am trying to dynamically show the fields based on which user logs in. Also, when I said "hidden", I actually should have said "removed." See my example below
E.g.,
If JoeUser logs in, he would see:
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
Phone Number: <input id="phone_number" />
City: <input id="city" />
</form>
But, if JaneUser logs in, she would see (based on preferences set in the database):
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
</form>
My question is: What is the best way to achieve this? I'm assuming these preferences need to be database-driven. Any input would be great.

Depending on how you've built the site there are quite a few ways to do this but since you're new to PHP I'll assume that it's just an inline procedural script. In which case you need to check whether or not the user is set in the session and then show or hide depending on the output.
Something similar to the following
<?php if(isset($_SESSION['id'])) : ?>
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
Phone Number: <input id="phone_number" />
City: <input id="city" />
</form>
<?php endif; ?>
The if statment checks if a session ID is set (this will likely change depending on how you're handling user sessions etc) and then shows the form.
Edit:
Just noticed that you've edited your original question. To do this you could so something similar to the following, this assumes once again that you're using sessions and that you have the users user type set in a session (not great, but as a beginner it's quick).
<?php if(isset($_SESSION['id'])) : ?>
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
</form>
<?php else if(isset($_SESSION['id']) && (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'phoneuser')) : ?>
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
Phone Number: <input id="phone_number" />
City: <input id="city" />
</form>
<?php endif; ?>

You can hide dinamycally on the server side inside php file or try set variable via php for js and operate with fields on the client side via javascript.
Can you explain what you want do with these forms? I don't understood

1) You should use jQuery (don't forget to include this library to head section).
$('#hide_name').click(function() {
$('#first_name').hide('slow', function() {
});
});
First Name: <input type="text" id="first_name" /> <a href="#" id="hide_name" /> Hide name </a>
2) OR next way:
if ($_SESSION['login']) {
$visible = "visibility: visible;";
}
else {
$visible = "visibility: hidden;";
}
First Name: <input type="text" style=<?php echo $visible; ?> />
3) OR easiest way:
if ($_SESSION['login']) {
First Name: <input type="text" id="first_name" />
}

You'll need to store some kind of data that defines what the user sees, or what they don't. Pick whatever feels intuitive based on your data. Once you know the user is logged in, get the data on what to show them. You could make an array of boolean values based on this, let's call it form_fields[]. Then output the form with PHP, and decide what parts to show based on this data, possibly like so:
$form = "<form>\n";
if(form_fields['first_name'])
{
$form .= 'First Name: <input id="first_name" />';
}
if(form_fields['last_name'])
{
$form .= 'Last Name: <input id="last_name" />';
}
if(form_fields['phone'])
{
$form .= 'Phone Number: <input id="phone_number" />';
}
if(form_fields['city'])
{
$form .= 'City: <input id="city" />';
}
$form .= "</form>";
Keep in mind, validating your data gets more complex too - your form processing script will also need to know what fields it's lookling for.

Related

keep form value after submit it

I know there are lots others question like this and i found 1.000 answer on the web but none of those work with my code :(
So can someone help me with how to keep email value after submit?
<form name="login-registration" onSubmit="return validateForm()" method="post" action="" >
<label>Email</label>
<input type="email" name="emailinput" id="emailinput" value ="" />
<p id="emptyEmail" class="hidden">Email field is required</p>
<p id="invalidEmail" class="hidden">Email you insert is invalid!</p>
<label>Your password</label>
<input type="password" name="pswinput" id="pswinput" value=""/>
<p id="pswMinMax" class="hidden">Password should be from 4 to 8 caracters</p>
<p id="pswLettNum" class="hidden">Password should be letters and numbers. No special caracters are allow</p>
<label>Repeat password</label>
<input type="password" name="pswrepeatinput" id="pswrepeatinput" value="" onblur="isValidPswRep()"/>
<p id="pswR" class="hidden">Your passwords is different</p>
<input type="checkbox" id="policy" name="policy" value="policy" /> <label>I agree</label>
<p id="checkN" class="hidden">You must agree to our term</p>
<input type="submit" name="submit" value="Login" />
</form>
I try to put some code like:
<input type="email" name="emailinput" id="emailinput" value = "<?php echo htmlspecialchars($_GET['lastname']); ?>" />
But that php line is just displayed inside the field input.
try using $_POST['lastname'] instead of $_GET['lastname']
1)If i am not wrong,i don't see any field with name="lastname" in your code above.
2)Use $_POST because you are posting your form data with method="post".
Assuming that your file have .php as extension and php is installed on your server i would like you to notice that you have an error because you used a POST form while when you apply value to your input field you are trying to use $_GET Further more you did not assign lastnameto any input field, so use emailinput as you apply to this field name="emailinput". You should change htmlspecialchars($_GET['emailinput']); to be htmlspecialchars($_POST['emailinput']);
So your code would look like this
<input type="email" name="emailinput" id="emailinput" value = "<?php echo htmlspecialchars($_POST['emailinput']); ?>" />
This should print your variable inside your input field
There are at least 2 problems there.
The fact that the php is displayed inline suggests that either you have wrong file extension (like the comments suggested), either file is not included in your "know how to read by php" (for lack of a better way to say it, my English is not perfect) directory.
You echo a get when you sent a post (as other answer suggested)
Also... WHY DOES YOUR QUESTION HAVE JS TAG (sorry for caps, wanted to be sure it sticks out)?

Replacing <input name="city" type="text" /> with $_POST['city'] dynamically

I've been two days searching how to do this. I have this form:
<form action="preview.php" method="post">
In the city of <input name="city" type="text" /> at <input name="days" type="text" /> days of <input name="month" type="text" /> gathered the following people: <input name="name1" type="text" /> and <input name="name2" type="text" /> with the objective of...
<button type="submit">Preview</button></form>
And preview.php should have this:
In the city of <?php echo $_POST['city'];?> at <?php echo $_POST['days'];?> days of <?php echo $_POST['month'];?> gathered the following people: <?php echo $_POST['name1'];?> and <?php echo $_POST['name2'];?> with the objective of...
The thing is the form is created via CMS so I have no way of knowing what the names of the inputs will be.
Is there a way to dinamically replace, for example, <input name="city" type="text" /> with <?php echo $_POST['city'];?>?
There are some thing I have in mind but since I'm new to PHP I don't know how to implement them.
Maybe preg_replace could do it but I don't know how to prevent the name of the input from changing.
Or maybe I could use an array, for example <input name="data[]" type="text" /> and something like:
for($i=0;"";$i++){
if( isset( $_POST["data{$i}"] )) {
$string = $form;
$patterns = '<input name="data[]" type="text" />';
$replacement = $_POST["data{$i};
preg_replace($patterns, $replacements, $string);
}
}
I'm really lost here and I'd appreciate it if someone could help me with this.
PS: I'm not a native english speaker son I'm sorry if I made some mistake.
UPDATE:
The user can make different forms in the CMS that will be saved in a database. Then he can choose which one he wants to fill. Once he fills it he can preview it and save it as a pdf.
The preview.php will have the same text in the form but instead of the inputs it will have the value that the user entered.
(I have been a bit out of touch with PHP.)
Capture the HTML of the form with ob_ functions (output buffer).
if ($_SERVER['REQUEST_METHOD'] == 'POST' {
ob_start();
... the CMS outputs HTML
ob_end_flush();
$s = ob_get_contents();
Use the name attribute to replace things
function postText($matches) {
return $_POST[$matches[1]];
}
$s = preg_replace_callback('/<[^>]* name="([^">]+)"[^>]*>/',
"postText",
$s);
echo $s;
This uses a function for replacing a HTML tag with a name attribute.

PHP code inside javascript

I have no idea about how javascript works, but I was able to write the following code by copying from different sites.
My aim is to have 2 radio boxes (1 = India, 2 = Other than India) and if Other than India is selected, then a dropdown box is displayed which shows names of all countries.
The dropdown is selected from a database and it is achieved by a custom php function.
I am able to make the code display the dropdown based on my radio box selection.
What I am unable to do is as follows:
I am not able to select any values from the dropdown.
I'm not able to make the dropdown hide if I change the choice in the radio box
Here is the code of the form:
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<br />
<script type="text/javascript">
function onclickradio(entry){
if (entry === true) {
alert("YOU HAVE CHOSEN INDIA");
}
else {
document.getElementById('OTHER THAN INDIA').innerHTML = '</br><?php dropdown('country');?>';
}
}
</script>
Country: </br>
<input onclick="onclickradio(document.getElementById('INDIA').checked);" id="INDIA" name="country" type="radio" checked="checked"/> INDIA
<input onclick="onclickradio(document.getElementById('INDIA').checked);" id="OTHER THAN INDIA" name="country" type="radio"/> OTHER THAN INDIA
<br /><br /><br />
State: <input type="text" name="State" maxlength="30"/><br />
Line1: <input type="text" name="Line1" maxlength="50" /><br />
Line2: <input type="text" name="Line2" maxlength="50" /><br />
City: <input type="text" name="City" maxlength="40" /><br />
PIN Code: <input type="text" name="PIN_Code" maxlength="8" /><br />
<input type="submit" name="submit_address" value="Submit Address" />
</fieldset>
</form>
Here is the code for the custom PHP dropdown function:
<?php
function dropdown($tablename) /*remember to add single quote around the input*/
{
$sql="SELECT * FROM ".$tablename;
$result=mysqli_query($GLOBALS["connection"], $sql)
or die('Error in running SELECT query');
$options=""; //initialising the variable, so that it can be concatenated later
while ($row=mysqli_fetch_array($result))
{
$x=0; /*$x is the index of the field in a row (it has to start with $x=0;
because the first index is 0 in php*/
$rowstr=" # "; /*initialising the variable,
so that it can be concatenated later*/
while ($x+1<=mysqli_num_fields($result)) /*mysqli_num_fields gives the actual number of fields, and not the index.
Since the index starts with 0, it is to be incremented by 1
before comparison with the mysqli_num_fields*/
{
$rowstr.= $row[$x]." # "; //concatenation operator
$x=$x+1;
}
$options.="<option value=".$rowstr.">".$rowstr."</option>"; //concatenation operator
}
Echo "<select>".$options."</select>";
}
?>
A few things that come to mind:
Don't put spaces in id values. I recommend that you use lower case as well, so you could have "india" and "not-india" instead.
Use Firefox/Firebug or similar to see if you have any JavaScript errors when you run this
Consider using jQuery or similar to catch change events - it is easy to use and uses the 'unobtrusive' method of adding JS functionality to your page.
Id field of an element can not have space. Just try removing spaces in "OTHER THAN INDIA" or replace to looks like OTHER_THAN_INDIA
Try this:
$(document).ready(function() {
// hide address inputs
$('#address').hide();
// show address inputs if the not india button is pressed
$('#not-india').click(function() {
$('#address').show();
});
// re-hide address inputs if india is selected
$('#india').click(function() {
$('#address').hide();
});
});
You will also have to include jQuery in your page.
Fiddle: http://jsfiddle.net/EN4jB/6/
Please note that I used the following markup - particular attention is due to the id of this div.
<input id="india" name="country" type="radio" checked="checked"/> India
<input id="not-india" name="country" type="radio" /> Not India
<br />
<div id="address">
<p><select>
<option>USA</option>
<option>UK</option>
<option>Ireland</option>
<option>etc...</option>
</select>
</p>
<p>State: <input type="text" name="State" maxlength="30"/></p>
<p>Line1: <input type="text" name="Line1" maxlength="50" /></p>
<p>Line2: <input type="text" name="Line2" maxlength="50" /></p>
<p>City: <input type="text" name="City" maxlength="40" /></p>
</div>
To clear the selection if India is chosen
function onclickradio(entry) {
if(entry===true) {
alert("YOU HAVE CHOSEN INDIA");
document.getElementById('OTHER THAN INDIA').innerHTML = '';
}
else {
document.getElementById('OTHER THAN INDIA').innerHTML = '<br/><?php dropdown('country');?>';
}
}

to call same form many times depending upon a value enterd by a user

I am now developing a travel agency website, in this site when the user reserves a trip he/she have to enter trip related details. This information is collected in a forma. The user also enters the number of people who are travelling.
My question is, how do I gather the same information for everyone who is travelling? Basically I need the form to be generated many times depending upon the number of people of same family ,, so I can capture all their data. How do I do this?
well there are my Code;plllz help me am so confused and tried lots of things to solve it;
thanks in advance
<form action = "insertpassenger.php" method = "POST">
<center>Enter all the information below</center>
<?php for ($i=0;$i<$pplno;$i++) : ?>
people<?php echo $i+1 ; ?>
<input type="text" name="cpr" size="9" value="<?php echo $cpr;?>" maxlength="9">CPR
<input type="text" name="pplno" size="30" maxlength="25">Number Of People
<input type="text" name="gcpr" size="9" maxlength="9">dad CPR
<input type="reset" value="clear" name="clear">
<input type="submit" value="join" name="join">
<?php endfor; ?>
</form>
Your code jumps in and out PHP rather a lot.
Just declare the item names as array entries, either with implicit or explicit numbering:
for ($i=0;$i<$pplno;$i++) : ?>
<input type="text" name="cpr[]" size="9" value="<?php echo $cpr[$i];?>" maxlength="9">CPR
<input type="text" name="pplno[]" size="30" maxlength="25">Number Of People
<input type="text" name="gcpr[]" size="9" maxlength="9">dad CPR
<input type="reset" value="clear[]" name="clear">
<input type="submit" value="join[]" name="join">
<?php endfor;
or...
for ($i=0;$i<$pplno;$i++) {
print "<input type=\"text\" name=\"cpr[$i]\" size=\"9\" value=\"$cpr[$i]\" maxlength="9">CPR";
....
}
I would personally use a session variable and count down how many times the form needs to be completed. Unfortunately that would cause to page to reload after each form entry, but this allows you to have as many amount of forms as your user requests, without a screen scrolling down a few pages to create all the forms on one page.
At the start of your code before you displaying anything to the browser :
<?php
session_start ();
?>
And where you receive your count for looping:
<?php
if (!isset($_SESSION['yourAppName']))
}
$_SESSION['yourAppName'] = $pplno;
} else {
$_SESSION['yourAppName']--;
}
if ($_SESSION['yourAppName'] > 0) {
?>
<form action=''>
<input type="text" name="cpr" size="9" value="<?php echo $cpr;?>" maxlength="9">CPR
<input type="text" name="pplno" size="30" maxlength="25">Number Of People
<input type="text" name="gcpr" size="9" maxlength="9">dad CPR
<input type="reset" value="clear" name="clear">
<input type="submit" value="join" name="join">
<input type="submit" value="Proceed">
</form>
<?php
} else {
// code when all forms are filled in
}
?>
remember to have your form return to the same page. This code is only to guide you, don't expect it to work without some editing. :)

jQuery: find id of of a form field

I am creating a dynamic form where the user will have the ability to add a set of inputs to the form. The html looks like this:
<form>
<input id="title1" class="title" name="title1" type="text" value="">
<input id="productionCompany1" name="productionCompany1" type="text" value="">
<input id="year1" name="year1" type="text" value="">
<input id="role1" name="role1" type="text" value="">
<div id="newCredit"> </div>
add another credit
</form>
When the user clicks the link with the id of "addCredit" the following jQuery script is called:
$(document).ready(function() {
var $ac = $('#addCredit');
$ac.click(function() {
/* the following two lines are where the problem lies? */
var $credInt = $(this).prev(".title");
$.get("addCredit.php", {num: $credInt},
function(data){
$('#newCredit').append(data);});
return false;
});
});
The jQuery function queries a php file called "addCredit.php", which looks like this:
<?php
$int = $_GET["num"];
$int = substr($int, -1);
$int++;
?>
<input id="title<?php echo $int;?>" class="title" name="title<?php echo $int;?>" type="text" value="">
<input id="productionCompany<?php echo $int;?>" name="productionCompany<?php echo $int;?>" type="text" value="">
<input id="year<?php echo $int;?>" name="year<?php echo $int;?>" type="text" value="">
<input id="role<?php echo $int;?>" name="role<?php echo $int;?>" type="text" value="">
My problem is getting the javascript variable $credInt set properly so that it can be sent to the addCredit.php page and update the form fields accordingly. I also need to be sure that every time the form is appended, the next value sent is the incremented value.
Any thoughts on how I might accomplish this? Thank you for your help.
This is the wrong way of doing it; PHP can handle array syntax in a variable name. This makes it much easier to handle. It is also unnecessary to call the server to clone the form. You should name your fields like this:
<form>
<div id="originalCredit">
<input name="title[]" type="text" value="">
<input name="productionCompany[]" type="text" value="">
<input name="year[]" type="text" value="">
<input name="role[]" type="text" value="">
</div>
add another credit
</form>
And then your Javascript can be like this:
$(function() {
$('#addCredit').click(function() {
var newCredit = $('#originalCredit').clone(); // create new set
newCredit.find('input').val(''); // empty input fields
$(this).before(newCredit); // append at the end
return false;
});
});
When the form is finally sent to the server, because the variables are in the format of name[] PHP will recognize they are an array and then you can do this:
<? foreach($_POST['title'] as $k => $v) { ?>
Title: <?=$_POST['title'][$k]?><br>
Company: <?=$_POST['productionCompany'][$k]?><br>
Year: <?=$_POST['year'][$k]?><br>
Role: <?=$_POST['role'][$k]?><br>
<? } ?>
Obviously this is just displaying it as an example, but you can then save/update/whatever with it.

Categories