PHP - Fetch value based on what is selected from option - javascript

<select class="selectpicker" name="mscr_type" id="mscr_type">
<?php $fpp_type = '';
foreach ($getmilestone_cr as $mscr_list) {
$description = $mscr_list['FIX_PRJ_DESC'];//fetch description
if ($fpp_type != $mscr_list['FIX_PRJ_TYPE']) {
if ($fpp_type != '') {
echo '</optgroup>';
}
if($mscr_list['FIX_PRJ_TYPE'] == 'MS'):
echo $fpp_label = "Milestone";
elseif($mscr_list['FIX_PRJ_TYPE'] == 'CR'):
echo $fpp_label = "Change Request(CR)";
endif;
echo '<optgroup label="'.$fpp_label.'">';
}
echo '<option value="'.$mscr_list['FIX_PRJ_TYPE'].'">'.htmlspecialchars($mscr_list['FIX_PRJ_NAME']).'</option>';
$fpp_type = $mscr_list['FIX_PRJ_TYPE'];
}
if ($fpp_type != '') {
echo '</optgroup>';
}
?>
</select>
The above code outputs:
<select class="selectpicker">
<optgroup label="Picnic">
<option value ="1">Mustard</option>
<option value ="2">Ketchup</option>
<option value ="3">Relish</option>
</optgroup>
<optgroup label="Camping">
<option value ="4">Tent</option>
<option value ="5">Flashlight</option>
<option value ="6">Toilet Paper</option>
</optgroup>
</select>
How could I fetch description based on what is selected from selected option. For example if Mustard is selected, then input value should be filled
with value 'Mustard is yellow in color'.
Tried using <select class="selectpicker" name="mscr_type" id="mscr_type" onchange="document.getElementById('mscr_description').value=this.options[this.selectedIndex].text"> but it fetches the name and not description.
<label for="name" class="label">Description</label>
<input type="text" disabled="" id="selectpicker_description" name="selectpicker_description" class="span3">

Add the description to the HTML using a data-XXX attribute:
echo '<option value="'.$mscr_list['FIX_PRJ_TYPE'].'" data-description="'.htmlspecialchars($description).'">'.htmlspecialchars($mscr_list['FIX_PRJ_NAME']).'</option>';
Then you can use
onchange="updateDescription(this)"
with the Javascript function:
function updateDescription(sel) {
var output = document.getElementById('mscr_description');
var desc = sel.options[sel.selectedIndex].getAttribute('data-description');
output.value = desc;
}

Related

Quick Edit Menu add new dropdown with selected on current post [duplicate]

Typically when you need to select an item by default, you do:
<select>
<option value="1"> Volvo </option>
<option value="2" selected="true"> Saab </option>
<option value="3"> Mercedes </option>
<option value="4"> Audi </option>
</select>
Is it possible to get something like this?
<select selectedValue="2">
<option value="1"> Volvo </option>
<option value="2"> Saab </option>
<option value="3"> Mercedes </option>
<option value="4"> Audi </option>
</select>
It works out easier in PHP since you only have to soft-code one value, instead of handling the selected attribute on any possible <option/>.
There is no attribute like that on the <select> element. Assuming your <option> output is in a loop, I don't see how it makes a huge difference:
$selected = "2";
foreach($values as $key => $val) {
echo "<option value=\"" . $key . "\"" . ($key == $selected ? " selected=\"selected\">" : ">") . $val . "</option>";
}
(my PHP is a little rusty, that may not be 100% correct)
No, but you can add your default value to your id like
<select id="default-value-2">
then in your options, you have
<option value="2" <?php echo is_this_the_default_value ? selected='true' : '' ?>
or something to that effect(forgive me i forgot my php syntax, but i hope you get the point).
Anyway, that is a dirty fix also, so i suggest just adding a method to check for the default selected tag and printing it selected="selected" when it is the default. You can just call it once if you loop through your select options
Put JavaScript after the declaration of the listbox and set the selected index there:
<script>
document.getElementById('listBoxId').selectedIndex=<?php echo $INDEX ?>;
</script>
Something like this.
You can do it like this:
$value = 1;
<select>
<?php if($value==1) echo "<option selected='true'> Volvo </option>";
else echo "<option> Volvo </option>"; ?>
<?php if($value==2) echo "<option selected='true'> Saab </option>";
else echo "<option> Saab </option>"; ?>
</select>
PHP:
<select>
<option value="1" <?php echo ($row['status']==1) ? 'selected' : '' ?>>Permitido</option>
<option value="2" <?php echo ($row['status']==2) ? 'selected' : '' ?>>Bloqueado</option>
</select>
I found myself googling this to see if there was a better way to do it.
The best and cleanest answer is from #roryf, however if you are not looping through your data I thought it would be a lot cleaner to wrap it up in a function:
function set_selected($desired_value, $new_value)
{
if($desired_value==$new_value)
{
echo ' selected="selected"';
}
}
Then you would use it like this:
<?php $selected_value = 2; ?>
<select>
<option value="1"<?php set_selected('1', $selected_value); ?>> Volvo </option>
<option value="2"<?php set_selected('2', $selected_value); ?>> Saab </option>
<option value="3"<?php set_selected('3', $selected_value); ?>> Mercedes </option>
<option value="4"<?php set_selected('4', $selected_value); ?>> Audi </option>
</select>
This would set Saab as selected :)
Preload $statusid from DB then -> (i have to escape ")
PHP:
$option_0 = '';
$option_11 = '';
$option_12 = '';
$option_13 = '';
$option_14 = '';
$option_15 = '';
$option_16 = '';
if ($statusid ==0 ){
$option_0 = 'selected=\"\"';
}elseif($statusid ==11 ){
$option_11 = 'selected=\"\"';
}elseif($statusid ==12 ){
$option_12 = 'selected=\"\"';
}elseif($statusid ==13 ){
$option_13 = 'selected=\"\"';
}elseif($statusid ==14 ){
$option_14 = 'selected=\"\"';
}elseif($statusid ==15 ){
$option_15 = 'selected=\"\"';
}elseif($statusid ==16 ){
$option_16 = 'selected=\"\"';
}
HTML:
."<select id=\"id\" name=\"name\" >"
." <option {$option_0} value=\"0\">...TEXT...</option>"
." <option {$option_11} value=\"11\">TEXT</option>"
." <option {$option_12} value=\"12\">TEXT</option>"
." <option {$option_13} value=\"13\">TEXT</option>"
." <option {$option_14} value=\"14\">TEXT</option>"
." <option {$option_15} value=\"15\">TEXT</option>"
." <option {$option_16} value=\"16\">TEXT</option>"
."</select><br /><br />"
work Perfect for me.

How to get a PHP array index converted to a javascript variable

I'm getting a set of user roles from the database using PHP and they are put in a <select> tag's <option>s as follows:
<div class="col-md-3">
<select name="role" id="user_role" class="form-control" onkeyup="clearMsg('roleerr')" onchange="getRole()"/>
<option value="">Select a Role</option>
<?php while($rowrole = $resultrole->fetch(PDO::FETCH_BOTH)) { ?>
<option value="<?php echo $rowrole ['role_id']; ?>">
<?php echo $rowrole ['role_name']; ?>
</option>
<?php } ?>
</select>
<span id="roleerr" class="error">*</span>
</div>
And I want to get the selected value of the dropdown 'onchange' and for that getRole() javascript function is written. How to get this done?
When the element changes, the value of the dropdown will be set to the value attributed to the selected option. So you would just define your javascript function and have it fetch the value of the dropdown:
function getRole(){
var finalVal = document.getElementById("user_role").value;
// And then here you can do whatever you want with the information
}
You can assign value in paramater in onchange()
this should work below
function getRole(value) {
if(value != "")
alert(value)
}
<div class="col-md-3">
<select name="role" id="user_role" class="form-control" onchange="getRole(this.value)"/>
<option value="">Select a Role</option>
<option value="23">select 23</option>
<option value="24">select 24</option>
<option value="25">select 25</option>
</select>
<span id="roleerr" class="error">*</span>
</div>
You could try event of onchange.
onchange="getRole(event)"
Javascript.
function getRole(event) {
var selectElement = event.target;
var value = selectElement.value;
alert(value);
}
I tested it with hard data.
function getRole(event) {
var selectElement = event.target;
var value = selectElement.value;
alert(value);
}
<div class="col-md-3">
<select name="role" id="user_role" class="form-control" onchange="getRole(event)"/>
<option value="">Select a Role</option>
<option value="1">admin</option>
<option value="2">user</option>
<option value="3">support</option>
</select>
<span id="roleerr" class="error">*</span>
</div>

Set option values in a dropdown list based on the option from previous dropdown

So there are two drop-down lists in my code. One is "Specialization" which has options such as General, Cardiologist, Pediatrician, etc, and the other one is "Doctor" which has the name of the doctors as options. What I want is to show the names of the doctors in the "Doctor" drop-down based on the values selected in the "Specialization" drop-down.
This is how my JSON looks like:
[{"username":"Ashok","spec":"General"},{"username":"arun","spec":"Cardiologist"},{"username":"Dinesh","spec":"General"},{"username":"Ganesh","spec":"Pediatrician"},{"username":"Kumar","spec":"Pediatrician"},{"username":"Amit","spec":"Cardiologist"},{"username":"Abbis","spec":"Neurologist"}]
Eg: If I select 'General' from the "Specialization" drop-down, then only the doctors with General (Ashok and Dinesh) will be shown as the drop-down options in the "doctor" drop-down.
Here is the HTML and JS part:
<div class="col-md-4">
<label for="spec">Specialization:</label>
</div>
<div class="col-md-8">
<select name="spec" class="form-control" id="spec">
<option value="" disabled selected>Select Specialization</option>
<?php display_specs();?>
</select>
<script>
let data = <?php echo json_encode($docarray); ?>
document.getElementById('spec').onchange = function updateSpecs(e) {
let values = data.filter(obj => obj.spec == this.value).map(o => o.username);
document.getElementById('doctor1').value = document.querySelector(`[value=${//query that matches the doctor name in json}]`).getAttribute('data-value');
};
</script>
</div><br><br>
<div class="col-md-4"><label for="doctor">Doctors:</label></div>
<div class="col-md-8">
<select name="doctor" class="form-control" id="doctor1" required="required">
<option value="" disabled selected>Select Doctor</option>
<?php display_docs();?>
</select>
<script>
document.getElementById('doctor').onchange = function updateFees(e) {
document.getElementById('docFees').value = document.querySelector(`[value=${this.value}]`).getAttribute('data-value'); // fees will be added based on the doctor mentioned in the db
};
Here is the PHP code for 'display_specs()' and 'display docs()':
function display_docs()
{
global $con;
$query="select * from doctb";
$result=mysqli_query($con,$query);
while($row=mysqli_fetch_array($result))
{
$username=$row['username'];
$price=$row['docFees'];
echo '<option value="' .$username. '" data-value="'.$price.'">'.$username.'</option>';
}
}
function display_specs() {
global $con;
$query="select distinct(spec) from doctb";
$result=mysqli_query($con,$query);
while($row=mysqli_fetch_array($result))
{
$spec=$row['spec'];
$username=$row['username'];
echo '<option value="' .$username. '" data-value="'.$spec.'">'.$spec.'</option>';
}
}
Screenshot:
I did my best my couldn't able to do that. So any suggestions are welcome. Thanks in advance!
You can use additional attribute in docs list
data-spec="'.$spec.'"
function display_docs()
{
global $con;
$query = "select * from doctb";
$result = mysqli_query($con,$query);
while( $row = mysqli_fetch_array($result) )
{
$username = $row['username'];
$price = $row['docFees'];
$spec = $row['spec'];
echo '<option value="' .$username. '" data-value="'.$price.'" data-spec="'.$spec.'">'.$username.'</option>';
}
}
function display_specs() {
global $con;
$query = "select distinct(spec) from doctb";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$spec = $row['spec'];
$username = $row['username'];
echo '<option value = "' .$username. '" data-value = "'.$spec.'">'.$spec.'</option>';
}
}
then use JS to filter second select
document.getElementById('spec').onchange = function foo() {
let spec = this.value;
let docs = [...document.getElementById('doctor').options];
docs.forEach((el, ind, arr)=>{
arr[ind].setAttribute("style","");
if (el.getAttribute("data-spec") != spec ) {
arr[ind].setAttribute("style","display: none");
}
});
};
<div class="col-md-4">
<label for="spec">Specialization:</label>
</div>
<div class="col-md-8">
<select name="spec" class="form-control" id="spec">
<option value="" disabled selected>Select Specialization</option>
<option value="General">General</option>
<option value="Cardiologist">Cardiologist</option>
<option value="Pediatrician">Pediatrician</option>
<option value="Neurologist">Neurologist</option>
</select>
</div><br>
<div class="col-md-4"><label for="doctor">Doctors:</label></div>
<div class="col-md-8">
<select name="doctor" class="form-control" id="doctor" required="required">
<option value="" disabled selected>Select Doctor</option>
<option value="Ashok" data-spec="General">Ashok</option>
<option value="arun" data-spec="Cardiologist">arun</option>
<option value="Dinesh" data-spec="General">Dinesh</option>
<option value="Ganesh" data-spec="Pediatrician">Ganesh</option>
<option value="Kumar" data-spec="Pediatrician">Kumar</option>
<option value="Amit" data-spec="Cardiologist">Amit</option>
<option value="Abbis" data-spec="Neurologist">Abbis</option>
</select>
</div>

can i use variable outside function when i select by onchange event

$sql3 = "SELECT * FROM `job`";
$result3 = mysqli_query($conn, $sql3);
<select class="form-control " id="jobposition" onchange="getSelectValue(this.value)">
<?php
if(mysqli_num_rows($result3) > 0){
while($row3 = mysqli_fetch_assoc($result3)){
?>
<option value=<?php echo $row3["jobid"];?> ><?php echo $row3["position"]; ?></option>
<?php }} ?>
</select>
<script>
var job ;
function getSelectValue(jobid) {
this.job = jobid;
}
I want to use selector outside the function.
Can you help me, please?
Yes, you can access the variable outside the function. The variable just needs to be defined globally, i.e. outside the functions.
var selector = document.getElementById("jobposition");
var disp = document.getElementById("optSelected");
function getSelectValue() {
disp.innerHTML = selector.options[selector.selectedIndex].value;
}
<select class="form-control " id="jobposition" onchange="getSelectValue()">
<option value="none">Select position</option>
<option value="1">Position 1</option>
<option value="2">Position 2</option>
<option value="3">Position 3</option>
<option value="4">Position 4</option>
</select>
<div>Selected option is = <span id="optSelected"></span></div>

Selected values dropdownlist value using javascript

I get these type of array in my javascript function as shown in image.Now i want selected all city in my dropdownlist which i get in my javascript array.
I have tried it but i didn't get success.How to do it.
function searchitem(id,name)
{
var ADDRESS = value.Address;
console.log(ADDRESS);
$("#Address option[value='" + vin + "']").prop("selected", true);
}
HTML Code
<select class="ct-js-select ct-select-lg" multiple="multiple" id="Address" name="Address[]" style="margin-left:14px;">
<option value="any">Any</option>
<optgroup label="City">
<?php foreach($Locations_Response->city as $CITIES){ ?>
<option value="<?php echo $CITIES; ?>"><?php echo $CITIES; ?></option>
<?php } ?>
</optgroup>
</select>
You need a loop:
var ADDRESS = ['Aberdeen Twp.','2'];
$.each(ADDRESS,function(i,vin) {
$("#Address option[value='" + vin + "']").prop("selected", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="ct-js-select ct-select-lg" multiple="multiple" id="Address" name="Address[]" style="margin-left: 14px; " tabindex="-1">
<option value="any">Any</option>
<optgroup label="City">
<option value="Aberdeen Twp.">Aberdeen Twp.</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</optgroup>
</select>
<select id='slc' name='slc'>
<?php
for($c=0;$c<10;$c++)
{
echo"<option> ".$c." </option>";
}
?>
script here
var txt=$('#slc').find(":selected").text();

Categories

Resources