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

$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>

Related

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>

Passing select value to another select tag

I am using Materialize CSS as my CSS framework and I also wasted 1 hour searching for the answers in google/stackoverflow etc.. but I can't seem to find the answer to solve this problem. So, what I am doing is I'm trying to pass the value of Select 1 to Select 2. Here is my code below
Select 1:
<select id="Accounts">
<option value="">Choose Account to edit</option>
<?php
$query = "SELECT * FROM personnel_list WHERE status = ?";
$result = $this->db->query($query, array("Active"))->result_array();
foreach ($result as $row) {
extract($row);
echo "<option value=\"$id-$name-$position-$status\">$name</option>";
}
?>
</select>
Select 2:
<select id="editPosition">
<option value="">Choose Position</option>
<?php
$Position = array("Manager", "Supervisor", "Assistant Manager", "Assistant Supervisor")
for ($x=0; $x < count($Position); $x++) {
echo "<option value=\"$Position[$x]\">$Position[$x]</option>";
}
?>
</select>
<label for="editPosition">Position:</label>
JS:
$("#Accounts").change(function(){
var accval = $(this).val().split("-");
var id = accval[0];
var name = accval[1];
var post = accval[2];
var status = accval[3];
$("#editPosition").val(post);
})
Other JS that I have tried is:
$("#editPosition option[value='"+post+"']").prop("selected", true);
Rendered Select 1:
<select id="Accounts">
<option value="">Choose Account to edit</option>
<option value="1-John-Manager-Active">John</option><option value="2-Mark-Assistant Manager-Active">Mark</option>
</select>
Rendered Select 2:
<select id="editPosition">
<option value="">Choose Position</option>
<option value="Manager">Manager</option>
<option value="Supervisor">Supervisor</option>
<option value="Assistant Manager">Assistant Manager</option>
<option value="Assistant Supervisor">Assistant Supervisor</option>
</select>
Thanks in advance for those who will answer and help me!
Use event delegation to listen for changes on the Accounts select instead:
$("#Accounts").on("change", function(){
var accval = $(this).val().split("-");
var id = accval[0];
var name = accval[1];
var post = accval[2];
var status = accval[3];
$("#editPosition").val(post);
});
See this jsFiddle for a working example.
Materialize CSS does a lot of modifications to the DOM when it renders its components, making straightforward JavaScript operations on UI elements from your part break at times.

how to select a specific option when a condition exists

I want to select the specific option in drop down list when a condition is existed.I set the Session in php and if the combo box has the value of 1 , it will be shown the option with value 1. I mean if session is 1, select the option with value of 1, if session is 2, select the option with vlaue of 2, and so on... . I want to set automatically select(I see the changes) with session in php.
sth like blewo:
<select id="sel" >
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
<?php $_SESSION['num']='1'; ?>
<script>
//must be shown the option with value of `1`.
<script>
Try this .
<select id="sel" >
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
<?php $_SESSION['num']='1'; ?>
<script>
//set local variable value so that I don't have to do it for each of the following ways to do this.
var num = "<?php echo $_SESSION['num']; ?>";
//normal javascript
document.getElementById("sel").value = num;
//using jQuery
$("#sel").val(num);
<script>
Or this try vikingmaster's way
You don't necessarily need js to do this. You can simply use php since you're already grabbing the num from the session.
Easiest way to do it would be:
<select id="sel" >
<?php if($_SESSION['num'] == 1): ?>
<option value='1' selected>one</option>
<?php else: ?>
<option value='1'>one</option>
<?php endif; ?>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
But if you want to use javascript(jQuery in particular here), you can do something like this:
<script>
$(document).ready(function(){
var num = <?php echo $_SESSION['num']; ?>;
$('#sel > option').each(function(){
if($(this).val() == num){
$(this).prop('selected', true);
}
});
});
</script>
Here's a fiddle.
There are a lot of ways to do this. This is what approach I would take, I'm sure others can provide just as viable or probably better answers.
Just set the value with the selected attribute
<select id="sel" >
<option value='1' selected>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
</select>
<?php $_SESSION['num']='1'; ?>
<script>
//alternately, set it explicitly
var element = document.getElementById('sel');
element.value = 1;
<script>
<select id="sel" >
<option value='1' <?php if($_SESSION['num']=='1') echo "selected"; ?> >one</option>
<option value='2' <?php if($_SESSION['num']=='2') echo "selected"; ?> >two</option>
<option value='3' <?php if($_SESSION['num']=='3') echo "selected"; ?> >three</option>
</select>

PHP - Fetch value based on what is selected from option

<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;
}

split function in javascript to input type = "text"

I've found some code via google that I could use it should be corrected to fit my but when I select something from my drop down menu, nothing happens. have no idea of what I'm doing wrong.
<select name="h1" id="h1">
<?php
echo "<option value=".$rowlift['H1'].">".$rowlift['H1']."</option>";
$pris = mysql_query("SELECT * FROM priser ORDER BY id ASC");
while($rowP = mysql_fetch_assoc($pris))
echo "<option value='".$rowP['pris'].",".$rowP['id']."'>".$rowP['hojde']. "</option>";
?>
</select>
<?php
if($rowlift['p1'] != '')
echo "<input type='text' id='pris1' name='p1' value='".$rowlift['p1']."'>";
else
echo "<input type='text' id='pris1' name='p1'>"
?>
<script type="text/javascript">
var mytextbox = document.getElementById('pris1');
var mydropdown = document.getElementById('h1');
var mySplitResult = mydropdown.split(",");
mydropdown.onchange = function(){
mytextbox.value = mySplitResult[0];
}
</script>
i hope this the think you was looking for.. when i select something nothing happens.
<select name="h1" id="h1">
<option value=""></option>
<option value="80,1">1000m</option>
<option value="90,2">1200m</option>
<option value="100,3">1500m</option>
<option value="110,4">2000m</option>
<option value="120,5">2250m</option>
<option value="130,6">2500m</option>
<option value="140,7">3000m</option>
<option value="150,8">3500m</option>
<option value="160,9">4000m</option>
<option value="160,10">Elev man.</option>
<option value="160,11">Elev auto</option>
<option value="0,12">HM</option>
<option value="2000,13">Tandem pass u/video</option>
<option value="2300,14">Tandem håndhold video</option>
<option value="2600,15">Tandem pass m/video</option>
<option value="0,16">Tandem master</option>
<option value="-100,17">Tandem video</option>
</select>
<td>
<input type="text" id="pris1" name="p1"> <script type="text/javascript">
var dropdownId = document.getElementById("h1");
var mytextbox = document.getElementById('pris1');
var mySplitResult = strUser .split(",");
dropdownId.onchange = function(){
mytextbox.value = mySplitResult[1] //to (not) appened
//mytextbox.innerHTML = this.value;
}
</script>
</td>
I think it should be mydropdown.value.split(',');
var dropdownId = document.getElementById("yourdropdownId");
var strUser = dropdownId .options[dropdownId .selectedIndex].value;
var mySplitResult = strUser .split(",");
wrap the above code in onchange()
this is how it should be.. :D
<select name="sel1" id="sel1" onchange ="show()" >
<option value="">Choose .....</option>
<option value="80~1">1000m</option>
<option value="90~2">1200m</option>
<option value="100~3">1500m</option>
<option value="110~4">2000m</option>
<option value="120~5">2250m</option>
<option value="130~6">2500m</option>
<option value="140~7">3000m</option>
<option value="150~8">3500m</option>
<option value="160~9">4000m</option>
<option value="160~10">Elev man.</option>
<option value="160~11">Elev auto</option>
<option value="0~12">HM</option>
<option value="2000~3">Tandem pass u/video</option>
<option value="2300~14">Tandem håndhold video</option>
<option value="2600~15">Tandem pass m/video</option>
<option value="0~16">Tandem master</option>
<option value="-100~17">Tandem video</option>
</select>
<td>
<input type="text" id="pris1" name="pris1">
<script type="text/javascript">
function show() {
var dropdownId = document.getElementById("sel1").value;
var mytextbox = document.getElementById('pris1');
var mySplitResult = dropdownId .split("~");
mytextbox.value = mySplitResult[0];
}
</script>

Categories

Resources