How to using If else for conditional <select> option in PHP? - php

The scenario is, I have 3 level user (Employer,Manager,Cashier), if the employer login the page, the employer just can see Manager and Cashier option in the select box;if the manager login the page, the manager just can see Cashier option in the select box
User level number I have stored in this variable $user_level, when the user login the id of the user will record in this variable $user_level. In the user value I have set the user level Employer id is 1, Manager id is 2, Cashier id is 3. For example, when the user level 1 (Employer) login the page, the option just can show Manager and Cashier option.When the user level 2 (Manager) login the page, the option just can Cashier option. My problem is how to change below the coding to if/else for conditional option ?
I have declared $user_level = $row['user_level'];
Below is my code:
<div class="form-group col-lg-6">
<label class="control-label col-lg-4">Position<span style="color:red;"> *</span></label>
<div class="col-lg-7">
<select class="form-control required" id="position" name="position">
<option value="">Please Select</option>
<option value="2">Manager</option>
<option value="3">Cashier</option>
</select>
<br>
</div>
</div>
Below the coding is check the user login current position(user level number),this part in the future will hidden:
<div class="form-group col-lg-6">
<label class="control-label col-lg-4">Current Login User Level<span style="color:red;"> *</span></label>
<div class="col-lg-7">
<input disabled type="text" class="form-control required" id="user_level" name="user_level" value="<?php echo $user_level; ?>">
</div>
</div>
Below is my output example:
Hope someone can guide me to solve this problem. Thanks a lot.

You can add if-else logic inline with the options:
<?php if($user_level != 3) { ?>
<div class="form-group col-lg-6">
<label class="control-label col-lg-4">Position<span style="color:red;"> *</span></label>
<div class="col-lg-7">
<select class="form-control required" id="position" name="position">
<option value="">Please Select</option>
<?php if($user_level == 1) { ?>
<option value="2">Manager</option>
<?php } ?>
<?php if($user_level == 1 || $user_level == 2) { ?>
<option value="3">Cashier</option>
<?php } ?>
</select>
<br>
</div>
</div>
<?php } ?>
Updated for revised requirements.

Related

Different ways to display the value of a selected dropdown option in laravel

I am currently working with this site wherein if you are not a local from that country, multiple input fields will be disabled. So, what I am trying to do is to display the selected option from a dropdown that has been queried from a database table. ill provide the code for it and some pictures for you to better understand it.
Here is the Controller:
public function get_citizenship()
{
$citizenships = CitizenshipModel::orderBy('citizens')->get();
$opt="<option selected value''>Select Citizenship</option>";
foreach($citizenships as $citizenship)
{
if($citizenship -> id > 0)
$opt.="<option value={$citizenship->id}>{$citizenship->citizens}</option>";
}
return $opt;
}
public function citizenship(){
$data = UserModel::where('seq_id','=',Session::get('loginId'))->first();
$data['displayCitizenship']=$this->get_citizenship();
$data['displayProvince']=$this->get_province();
$data['displayMunicipality']=$this->get_municipality();
return view ("countries", $data);
}
And here is the Blade file. I have two types of select. one is locally where i coded the value, and the other one is the one i queried from a database table.
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="step1_gender" class="col-sm-3 text-right control-label col-form-label">Gender</label>
<div class="col-sm-9">
<select class="form-control" type="date" id='step1_gender' >
<option>Select Gender</option>
<option value="male" >Male</option>
<option value="female" >Female</option>
</select>
</div>
</div>
</div>
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="step1_citizenship" class="col-sm-3 text-right control-label col-form-label">Citizenship</label>
<div class="col-sm-9">
<select class="form-control" type="text" required="" placeholder="Last Name" id='step1_citizenship' >
{!! $displayCitizenship !!}
</select>
</div>
</div>
</div>
This is the one i chose and inserted in my users info table. but whenever i refresh the page, it returns to Select Citizenship option. how can i show the selected option for each logged in user?
I tried googling and looking for youtube vids but i can't find the nearest answer.
If you want the option of citizenship to be selected based on the current user's data (assuming you $this->get_citizenship() retrieves the correct data from the current user), you can simply add a turnery condition for the selected option.
$current_citizen = $this->get_citizenship();
foreach($citizenships as $citizenship)
{
if($citizenship -> id > 0) {
$selected = $citizenship->citizens == $current_citizen ? 'selected' : '';
$opt.="<option value={$citizenship->id} ${selected}>{$citizenship->citizens}</option>";
}
}

Refresh the page with new request on change select option

I am trying to achieve something via php.
Here there are couple of options.
<select class="custom-select" id="inputGroupSelect01">
<option selected="">Select Clusters ...</option>
<option value="math-related">Math Related</option>
<option value="science-related">Science Related</option>
</select>
There are Group of subject fields which will appear when the options are changed respectively.
<div class="form-row pb-5" id="math-related"">
<div class="form-group col-md-3">
<input type="number" class="form-control" id="num1" placeholder="English">
</div>
<div class="form-group col-md-3">
<input type="number" class="form-control" id="num2" placeholder="Math">
</div>
<div class="form-group col-md-3">
<input type="number" class="form-control" id="num3" placeholder="Science">
</div>
<div class="form-group col-md-3">
<input type="number" class="form-control" id="num4" placeholder="Computer">
</div>
</div>
When the option is changed to Math related OR Science Related option, the related 5-6 subject fields will be populated like image below. Some might have 5, some might have 8.
How to refresh the page and load the new sets of input fields according to selection done via PHP?
Example Image for fields
First of all change your select dropdown with your page url + parameter and make sure to replace YOUR_PAGE_URL with actual url as follows -
<select onChange="window.location.href=this.value" class="custom-select" id="inputGroupSelect01">
<option value="">Select Clusters ...</option>
<option value="YOUR_PAGE_URL?topic=math-related">Math Related</option>
<option value="YOUR_PAGE_URL?topic=science-related">Science Related</option>
</select>
After then just do a GET parameter checking on your page to populate your fields like -
if( issset($_GET['topic']) ){
if( $_GET['topic'] == 'math-related' ){
echo "Add your math related above 5-8 fields html here.";
}elseif( $_GET['topic'] == 'science-related' ){
echo "Add your science related above 5-8 fields html here.";
}
}

Spit data to the select field from the database

enter image description hereI am new to coding. I just started building a website and I am currently working on the profile page. I wanted the input fields to be populated by the information the user has provided (see attached picture). This I have achieved.
My problem now is... I can't spit information from the database to the select tag.
For the other input fields, I just had to echo the data spooled from the database as seen in my HTML below:
<div class="col-sm-6 white-bg">
<div class="row">
<div class="col-sm-6">
<label>
<span class="text-left">FIRST NAME</span>
<input type="text" name="fname" value="<?php echo $first_name ?>" disabled>
</label>
</div>
<div class="col-sm-6">
<label>
<span class="text-left">LAST NAME</span>
<input type="text" name="lname" value="<?php echo $last_name ?>" disabled>
</label>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<label>
<span class="text-left">GENDER</span>
<select name="gender">
<option value="" disabled hidden selected>--Select--</option>
<option value="Female">Female</option>
<option value="Male">Male</option>
<option value="Others">Others</option>
</select>
</label>
</div>
<div class="col-sm-6">
<label>
<span class="text-left">DATE OF BIRTH</span>
<input type="DATE" name="dob" value="<?php echo $dob ?>">
</label>
</div>
</div>
</div>
But I can't do the same for the select tag. How do I have an option selected based on the information the user has provided such that the Male option is selected if the user entered male or the the Female option is selected if the user entered Female.
You should add the keyword based on the value returned from your DB.
So in your code add something like
-- For your default select option do
<?php echo(empty($theGender)?" selected":""); ?>
-- For Male/Female do, checking for value you stored
<option value="Female"<?php echo(($theGender === "female")?" selected":""); ?> >Female</option>

PHP echo select menu value but delete duplicate

I'm working on a profile update page and i have a form field where users can select enabled or disabled. When i echo the value, it has a duplicate and can be confusing for the user. How can i get rid of the duplicate?
<div class="form-group">
<label for="status" class="col-sm-3 control-label">Change Status</label>
<div class="col-sm-9">
<select class="form-control btn-danger" id="status" name="status">
<option value="<?php echo $status ?>"><?php echo $status ?></option>
<option value="Disabled">Disabled</option>
<option value="Enabled">Enabled</option>
</select>
</div>
</div>
As you can see, if the status is enabled and i hit the select menu its gonna say Enabled twice, same thing for disabled.
The only thing i thought of was to have another field labeled current status and have the select menu to change status.
I really dont want to do that.
<div class="form-group">
<label for="currentstatus" class="col-sm-3 control-label">Current Status</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="currentstatus" name="currentstatus" value="<?php echo $status ?>">
</div>
</div>
<div class="form-group">
<label for="status" class="col-sm-3 control-label">Change Status</label>
<div class="col-sm-9">
<select class="form-control btn-danger" id="status" name="status">
<option value="<?php echo $status ?>"><?php echo $status ?></option>
<option value="Disabled">Disabled</option>
<option value="Enabled">Enabled</option>
</select>
</div>
</div>
This worked for me:
<option <?php if ($status=="Disabled") echo " selected"; ?>>Disabled</option>
<option <?php if ($status=="Enabled") echo " selected"; ?>>Enabled</option>
Instead of outputting the selected value as another option, output it as the selected attribute of an existing option. Something like this:
<select class="form-control btn-danger" id="status" name="status">
<option value="Disabled" <?php echo ($status == "Disabled") ? "selected" : ""; ?>>Disabled</option>
<option value="Enabled" <?php echo ($status == "Enabled") ? "selected" : ""; ?>>Enabled</option>
</select>
There are likely a variety of ways to achieve the same end result, but the point is to not add options based on the data you have but instead use that data to determine which of the existing, finite, hard-coded options you already have should be selected.
Here is some jQuery that will let you change the value of the select box.
function setStatusSelect(val) {
$("select#status").val(val);
}
setStatusSelect('Enabled');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="status" class="col-sm-3 control-label">Change Status</label>
<div class="col-sm-9">
<select class="form-control btn-danger" id="status" name="status">
<option value="Disabled">Disabled</option>
<option value="Enabled">Enabled</option>
</select>
</div>
</div>
If you include the Jquery function at the top of the page (so that it loads quickly) then you can do something like this:
<?php
print("<script type=\"text/javascript\">");
print("setStatusSelect(".$status.")");
print("</script>");
?>
to set the value.
I haven't tested the PHP portion, but I know the jQuery portion works.

Form validation using jQuery and Ajax in PHP

I have a form which has education div with course, year of completion, university and percent fields, and I am validating those education div fields using Ajax in PHP, and thats working perfectly, but when I clone education div and then if there is any validation error in second (cloned education) div then it reflect it in first (education field).
this is the form:
Educational Details
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="courses">Course Type</label>
<div class="col-md-6">
<select class="form-control" name="course[]" id="course1[]" onblur="validate('course', this.value)">
<option value="0">--Select--</option>
<option value="FullTime">FullTime</option>
<option value="PartTime">PartTime</option>
<option value="Distance Education">Distance Education</option>
<option value="Executive">Executive</option>
</select>
</div>
</div>
<div id="course" class="text-center course"></div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="year">Year of Completion</label>
<div class="col-md-6">
<select class="form-control" name="year[]" id="year1[]" onblur="validate('year', this.value)">
<?php require('layout/educompletionyear.php'); ?>
</select>
</div>
</div>
<div id="year" class="text-center"></div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 label_usity control-label" for="university">University/Institute</label>
<div class="col-md-6">
<select class="form-control" name="university[]" id="university1[]" onblur="validate('university', this.value)">
<?php require('layout/institute.php'); ?>
</select>
</div>
</div>
<div id="university" class="text-center"></div>
</fieldset>
</div>
<div class="col-md-6">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 label_degree control-label" for="degree">Degree</label>
<div class="col-md-6">
<select class="form-control" name="degree[]" id="degree1[]" onblur="validate('degree', this.value)">
<?php require('layout/degree.php'); ?>
</select>
</div>
</div>
<div id="degree" class="text-center"></div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 label_Grade control-label" for="grade">Grade</label>
<div class="col-md-6">
<select class="form-control" name="grade[]" id="grade1[]" onblur="validate('grade', this.value)" >
<option value="-1">--Select--</option>
<option value="A">A</option>
<option value="A+">A+</option>
<option value="B">B</option>
<option value="B+">B+</option>
<option value="C">C</option>
<option value="C+">C+</option>
<option value="D">D</option>
<option value="D+">D+</option>
<option value="E">E</option>
<option value="E+">E+</option>
<option value="F">F</option>
<option value="F+">F+</option>
</select>
</div>
</div>
<div id="grade" class="text-center"></div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="percentage">Percentage</label>
<div class="col-md-6">
<input id="percentage1[]" name="percentage[]" onblur="validate('percentage', this.value)" type="text" placeholder="Percentage" class="input_percentage form-control input-md">
</div>
</div>
<div id="percentage[]" class="text-center"></div>
</fieldset>
</div>
<a class="close" data-dismiss="alert" style="padding-right: 37px;opacity: 1;"><button type="button" class="addbtn btn btn-danger">Remove</button></a>
</div>
this is the ajax validation:
<?php
$value = $_GET['query'];
$formfield = $_GET['field'];
//EDUCATION PART
// Check Valid or Invalid Course type when user enters Course in select option input field.
if ($formfield == "course") {
if ($value =="0") {
echo "Please select Prefered location.";
}else{
}
}
// Check Valid or Invalid year when user enters Year of completion in select option input field.
if ($formfield == "year") {
if ($value =="-1") {
echo "Please select Year of completion.";
}else{
}
}
// Check Valid or Invalid University type when user enters University in select option input field.
if ($formfield == "university") {
if ($value =="-1") {
echo "Please select University.";
}else{
}
}
// Check Valid or Invalid Degree when user enters Degree in select option input field.
if ($formfield == "degree") {
if ($value =="-1") {
echo "Please select Degree.";
}else{
}
}
// Check Valid or Invalid Grade when user enters Grade in select option input field.
if ($formfield == "grade") {
if ($value =="-1") {
echo "Please select Grades.";
}else{
}
}
// Check Valid or Invalid Persentage when user enters Persentage in lastname input field.
if ($formfield == "percentage") {
if (strlen($value) ==0) {
echo "Please enter your Persentage.";
}elseif (!preg_match("/^((0|[1-9]\d?)(\.\d{1,2})?|100(\.00?)?)$/",$value)) {
echo "Only enter valid persentage";
}else {
}
}
?>
Please help to resolve cloned div validation messages part.
Use Jquery validate built-in library to validate forms very easily.
http://jqueryvalidation.org/
I got the way of implementing this....
i am creating an array of error message showing div and then i am also creating one more array for input fields attribut onblur
<div id="percentage[1]" class="text-center percentage"></div>
onblur="validate('percentage[1]', this.value)"
using jquery.
$('#btnAdd').click(function () {
var num = $('.clonedInput').length, // Checks to see how many "duplicatable" input fields we currently have
newNum = new Number(num + 1), // The numeric ID of the new input field being added, increasing by 1 each time
newElem = $('#entry1').clone().attr('id', 'entry' + newNum).fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value
newElem.find('.percentage').attr('id', 'percentage[' + newNum + ']');
newElem.find('.input_percentage').attr('onblur', 'validate("percentage[' + newNum + ']", this.value)');
and then i am validating these fields in ajjax page.
thank you for helping me...

Categories