retrieve id from dropdown/select box codeigniter - javascript

Im trying to figure how to retrieve the ID number from a selected value in a dropbox, displaying a list of projects from a table.
At this point what i did was retrieve the value and then search it and get the ID number for that value in the table. Well the field name_project it's "unique" so it's not so bad but i want to retrive the id directly without querying the database offcourse! It's really necessary the use of jquery or javascript to do that?
<?php echo form_open('solucao/inserir',array('class' => 'form-horizontal')); ?>
<select class="form-control" id="project" name="project">
<option>--Choose Project--</option>
<?php foreach($projects as $data):?>
<option><?php echo $data->name_project?></option>
<?php endforeach;?>
</select>
<?php form_close(); ?>
Note: $data is an array wich contains the ID number!
Thank you!

Hope you have project_id and project_name as field names in your project table
In model:
function getProjectArr()
{
$res = $this->db->get("project");
$ret_arr = array();
if($res-<num_rows()>0)
{
foreach($res->result() as $r)
{
$ret_arr[$r->project_id] = $r->project_name;
}
}
return $ret_arr;
}
In your controller,
$data["project_list"] = $this->MODEL_NAME->getProjectArr();
In View file
echo form_dropdown("project",$project_list,'','id="project" class="form-control"');
You will get dropdown with ids as option value and names as option text.

When you will get the id on select or options tag.
Then get the id of selected option you can use something like this.
document.getElementById('project').addEventListener('change', selectId);
function selectId(){
alert(this.options[this.selectedIndex].id);
}
Demo
OR
Get the id of select tag then you can use
document.getElementById('project').addEventListener('change', selectId);
function selectId(){
alert(this.id);
}
Demo2

Related

Value disappear after dropdown selected

I've searched around to find the answer of my problem but I didn't find any.
I have a table contain 2 columns: kode_barang (Item ID) and nama_barang (Item Name). Kode_barang is a dropdown option which it's data populated dynamically from another table. Each time user select an option, the name of the item will appear automatically.
Here is my code:
<td>
<select name='kode_barang' type = "text" id='kode_barang1' onchange="changeValue(this.value)">
<option>Choose</option>
<?php
$sql="SELECT * FROM input_data_barang ";
$result=mysql_query($sql);
$met = "var kode_barang = new Array();\n";
while ($row = mysql_fetch_array($result)) {
$id=$row["kode_barang"];
echo "<OPTION VALUE=$id>$id</option>";
$met .= "kode_barang['" . $row['kode_barang'] . "'] = {name:'" . addslashes($row['nama_barang']) . "',desc:'".addslashes($row['nama_barang'])."'};\n";
}
?>
</select>
</td>
<td><input type="text" name='nama_barang' id="nama_barang1"/readonly>
<script type="text/javascript">
<?php echo $met; ?>
function changeValue(id){
document.getElementById('kode_barang1').value = kode_barang[id].name;
document.getElementById('nama_barang1').value = kode_barang[id].desc;
};
</script>
</td>
Dropdown option and Item ID appear perfectly. The problem is, when I select an Item ID, the name of the ID (nama_barang) appear automatically, but then the Item ID disappear. The dropdown become blank. I need the Item ID persist after option selected so the ID can be saved to the database.
Anybody please help me.
The issue that I can see is that you are assigning kode_barang1 the name stored. kode_barang1 is the name of a SELECT object which uses numbers for the ID so when you assign it, it goes to NULL because a name doesn't exist in the <OPTION>.
Create a new input variable called kode_barang2 and change
document.getElementById('kode_barang1').value = kode_barang[id].name;
to
document.getElementById('kode_barang2').value = kode_barang[id].name;
And you will see that would work.

Disable the dropdown value which already exist in database

Can anyone guide me to get a solution. For example , there is a dropdown down in the form contains some animals name. If the user select the one animal from that, it saved in dropdown. Again in selection process, that saved data want to become disabled. The other options only able to select. This is the solution i want.
You can achieve this with a helper method for your view, or you could set instance variables in your controller but here is some pseudo code to get you going.
def disabled_animals
Animal.where(already_selected: true).pluck(:name)
end
def selectable_animals
Animal.all.pluck(:name) - disabled_animals
end
the idea is to get 2 arrays, one without the disabled animals and one with the disabled animals and pass those to your select helper method, then you could do something like this in your view.:
select("post", "animal", selectable_animals, {disabled: disabled_animals})
Which would produce this:
<select name="post[animal]" id="post_animal">
<option value=""></option>
<option value="joke">joke</option>
<option value="poem">poem</option>
<option disabled="disabled" value="zebra">zebra</option>
</select>
Reference: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
Highlevel idea:
Get selected value from UI and pass it to mysql query to exclude it
Code:
Get value from dropdown through jQuery:
var selectedAnimal = $('.animals').find('#animal option:selected').text().trim();
Please change according to your UI
Pass selected animal in query to exclude it
$sql = "SELECT DISTINCT `animal` FROM " . $animalTable . " where animal <> '<selectedAnimal>';
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_num_rows($result);
if ( $num_rows > 0 ) {
for ($row_no=1; $row_no <= $num_rows; $row_no++) {
$row = mysqli_fetch_array($result);
$dropdown.= "<option value='" .$row['animal']. "'>" .$row['animal']. "</option>";
}
}
echo "<select class='dropdownselect' id='animal'> " .$dropdown. "</select>";
Please change according to your query and language used

How to fill Textbox using dropdownlist

Please help me.. i have dropdownlist which i have populated from the database table, now i want to fill textbox from the database list...
i have one table
id | juice | rupees
now when i select Mango Juice from juice column from dropdownlist it should show the cost of Mango Juice in textbox by retrieving from rupees column
here is the dropdownlist which is populated from the table
<select name="drink" id="drinkid">
<option id="0">-- Select the drink --</option>
<?php
require("dbcon.php");
$getalldrinks = mysql_query("SELECT * FROM tableone");
while($viewalldrinks = mysql_fetch_array($getalldrinks)){
?>
<option id="<?php echo $viewalldrinks['id']; ?>"><?php echo $viewalldrinks['juice'] ?></option>
<?php
}
?>
</select>
and here is the textbox
<input type="text" name="juicename" id="juiceid" placeholder="Juice">
Please help me.. thanks in advance.
First add onChange() event to your select tag to call function fillTextBox() every time you change option, then the function will fill the textbox:
<select name="drink" id="drinkid" onChange="fillTextBox()">
Now you have to get rupees column & store it in every option using data attribute :
<option data-rupees="<?php echo $viewalldrinks['rupees']; ?>" id="<?php echo $viewalldrinks['id']; ?>" ><?php echo $viewalldrinks['juice'] ?></option>
Create the function fillTextBox() that will fill the textbox by rupees value of selected option :
function fillTextBox(){
var myselect = document.getElementById("drinkid");
var rupees = myselect.options[myselect.selectedIndex].getAttribute("data-rupees");
document.getElementById("juiceid").value = rupees;
}
That should do the work, hope this helps.
You'll need to use javascript to detect changes in your select box, store those values, and then populate the text box with the desired values. You haven't listed a text box in your html, so I'll have to assume that I can access this value using input[type=text]. Here's an approximation of what your javascript should look like given that I am working with incomplete information. Note that your should probably contain an attribute called value to store your id instead of using the id attribute.
var el = document.getElementById('drinkId');
el.addEventListener("click", function(){
var data = {"id": el.value, "text": el.innerHTML};
document.querySelectorAll('input[type=text]')[0].value = data.text;
});
You'll need to provide more detail and more of your code if you want an exact solution to your problem.
UPDATE: I see you've added the text box HTML, so here's the updated version of the event handler:
var el = document.getElementById('drinkId');
el.addEventListener("click", function(){
var data = {"id": el.value, "text": el.innerHTML};
document.getElementById('juiceId').value = data.text;
});

Populate html dropdown list dynamically from other dropdown

I have two dropdown lists, the first is populated from database and works fine, the second dropdown must be populated dynamically from what user has chosen from the first dropdown list. For example, my first dropdown contains many country's name, when user choose a country, the second dropdown will be populated by city's of that country which are in same database. Have anyone an example of this?
This is the first dropdown list
<select size="1" name="listeOrg">
<option value = "0" selected>---Choisir une région---</option>
<?php
$link3 = mysql_connect_db();
$query3 = "SELECT nom_region FROM region ";
$result3 = mysql_query($query3, $link3) or die();
while ($row = mysql_fetch_array($result3)) {
echo '<option value="'.$row['nom_region'].'">'.$row['nom_region'].'</option>';
}
mysql_close($link3); ?>
</select>
And the second:
<?php
$link4 = mysql_connect_db();
$selectregion=$_POST['listeOrg'];
$query4 = "SELECT organisme FROM region_organisme where nom_region='$selectregion' ";
$result4 = mysql_query($query4, $link4) or die();
while ($row2 = mysql_fetch_array($result4)) {
echo '<option value="'.$row2['nom_region'].'">'.$row2['nom_region'].'</option>';
}
mysql_close($link4); ?>
<option value="1" >autre
</select>
I found finally a good solution with a proper code. This is the link to the tutorial if someone has been stacked on this case.
A good explained tutorial with demo

How to show dropdown selected data in textbox

I want to show the drop down selected value in textbox.
This is my design.
This is my php code for drop downlist...
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("storedb", $con);
$s=mysql_query("select * from dealerdetail order by Dealer asc ");
?>
Select Dealer Name:
<select name="dealer" id="dealer">
<option value="">---- select Dealer -----</option>
<?php
while($dd=mysql_fetch_array($s))
{
?>
<option value="<?php echo $dd['D_id'] ?>"><?php echo $dd['Dealer'] ?></option>
<?php
}
?>
</select>
Please help.
I think you are looking for
$('#dealer').val(); //return selected value
$( "#dealer option:selected" ).text() // return selected options text
Use the change event and text property of select box to access the value
$('#dealer').change(function () {
$("#idOfTextBox").val($("#dealer option:selected").text());
});
use jquery:
Live demo : http://jsfiddle.net/t6YHK/25/
$('#dealer').change(function () {
$("#your_input_id").val($(this).val());
});
Use this:
$("#dealer").change(function(){
$("textarea").val( $(this).val() );
});
AngularJS
http://angularjs.org/
Scroll down to below the black area.
Seems like you're taking your first steps in web development, and for this, i strictly recommend that you stop using DreamWeaver to learn more about the code and how things go.
Each element in your web page is in the DOM (see HTML Document Object Model). So using native javascript all of your elements using :
document.getElementById("elementId")
And this is ALL what you need. All other solutions using frameworks will use this line of code whether you see this or not.
so for your specific question we will create a javascript function to be used in the event of value change of your dropdown list (assuming your text field's id is myText)
function updateMyText()
{
var dd = document.getElementById("myDropDown");
var ddtext = dd.options[dd.selectedIndex].text;
document.getElementById("myText").value = ddtext;
}
to call it when a dropdown list item is selected you need the attribute onchange
<select name="dealer" id="dealer" onchange='updateMyText()'>

Categories