Display option selected with codeigniter - javascript

I want to ask for my code option selected with 2 tabel in page register
table prodi
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| id_prodi | varchar(3) | NO | PRI | NULL | |
| nama_prodi | varchar(30) | NO | | NULL | |
| id_fakultas | varchar(3) | NO | MUL | NULL | |
| id | int(2) | NO | MUL | NULL | |
+-------------+-------------+------+-----+---------+-------+
and
table jurusan
+---------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| id_fakultas | varchar(3) | NO | PRI | NULL | |
| nama_fakultas | varchar(40) | NO | | NULL | |
+---------------+-------------+------+-----+---------+-------+
here's view :
<label for="fakultas">Fakultas : </label>
<select id="fakultas" name="fakultas_user" onChange="fakultas">
<?php
foreach ($qfakultas as $fakultas) {
echo "<option value=".$fakultas->kd_fakultas.">".$fakultas->nama_fakultas."</option>";
}
?>
</select>
<hr>
<label for="jurusan">Jurusan : </label>
<select id="jurusan" name="jurusan_user" onChange="jurusan">
<?php
foreach ($qprodi as $prodi) {
echo "<option value=".$prodi->kd_prodi.">".$prodi->nama_prodi."</option>";
}
?>
</select>
but I will display 'nama_prodi' based on 'id_fakultas"
register with option value
How to display when I click 'nama_fakultas' then display 'nama_prodi' based on 'id_fakultas' ?
Thanks

Here is the Ajax code that I can help, only to get nama_prodi based on id_falkutas.
You can use this code for your project, there is something you need to do. Not just copy the code. Just a few step (ID Lang : Jangan dicopy mentah2, hanya beberapa langkah saja untuk edit).
Change YOUR_URL_HERE into your base_url() or create var for it.
Change nama_controller into your controller name in CI_Controller
Change nama_fungsi into your function to get the data from your model (database). Example : ambil_data_jurusan.
Remove your foreach - echo <option> and onchange from your view.
Add the script into your view files or create a new .js file.
Please help me to mark as correct answer if this code helped you. ( tolong dibantu gan )
See Code Example :
<script>
$("#falkutas").on('change', function() {
$.ajax({
type:"POST",
url:'YOUR_URL_HERE/nama_controller/nama_fungsi',
data:{"falkutas_user":falkutas_user,"csrf_token":$("input[name=csrf_token]").val()},
dataType:'json',
success: function(result) {
for(var i=0; i<result.length; i++) {
res += '<option value="'+result[i]['id_prodi']+'">'+result[i]['nama_prodi']+'</option>';
}
$(document).ready(function() {
$("#prodi").html(res);
});
},
error: function(result) {
$(document).ready(function() {
$("#prodi").html(''); //empty select value
});
}
});
}
</script>
Then, in your function code :
// Inside function ambil_data_jurusan(), harusnya sudah jalan kalau gini
$return = $this->model->get_jurusan($this->input->post('falkutas',TRUE));
if(count($return)>0) {
echo json_encode($return);
}
In your view, just let select empty like this.
<select id="jurusan" name="jurusan_user">
</select>

Related

Dynamic dependent dropdown php how to compare two strings?

I am trying to compare two strings using ajax and php. I am based on this code https://github.com/webhostguru/dynamic-drop-down. I change the code on the ajaxdata.php file and it looks like this
<?php
include_once 'config.php';
if (isset($_POST['country_id'])) {
$query = "SELECT * FROM state where state_name=".$_POST['country_name'];
$result = $db->query($query);
if ($result->num_rows > 0 ) {
echo '<option value="">Select State</option>';
while ($row = $result->fetch_assoc()) {
echo '<option value='.$row['id'].'>'.$row['state_name'].'</option>';
}
}else{
echo '<option>No State Found!</option>';
}
The rest of the code is the same. I change also some of sql tables and i have a state named India to compare the strings with country (India also) but it doesn't work. Any ideas?
Thank you in advance!!!
To use a prepared statement you can try like this:
<?php
if( isset(
$_POST['country_id'],
$_POST['country_name']
)) {
$output='<option selected hidden disabled>Please Select State';
require 'config.php';
$query = 'select `id`, `state_name` from `state` where `state_name`=?';
$stmt=$db->prepare( $query );
$stmt->bind_param('s', $_POST['country_name'] );
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->bind_result( $id, $name );
if( $rows > 0 ){
while( $stmt->fetch() ) $output .= sprintf('<option value="%s">%s',$id,$name);
}else{
$output='<option selected hidden disabled>No state found';
}
exit( $output );
}
?>
Based upon the database cited but modified slightly for table names:
mysql> select * from tbl_country;
+----+--------------+---------------------+
| id | country_name | time_stamp |
+----+--------------+---------------------+
| 1 | India | 2019-12-05 16:29:16 |
| 2 | USA | 2019-12-05 16:29:16 |
| 3 | Australia | 2019-12-05 16:29:44 |
| 4 | England | 2019-12-05 16:29:44 |
+----+--------------+---------------------+
mysql> select * from tbl_state;
+----+-----------------+------+---------------------+
| id | state_name | c_id | time_stamp |
+----+-----------------+------+---------------------+
| 1 | Delhi | 1 | 2019-12-05 16:30:15 |
| 2 | Maharashtra | 1 | 2019-12-05 16:30:15 |
| 5 | South Australia | 3 | 2019-12-05 17:02:22 |
| 6 | West Australia | 3 | 2019-12-05 17:02:22 |
+----+-----------------+------+---------------------+
mysql> select * from tbl_city;
+----+------------+------+---------------------+
| id | city_name | s_id | time_stamp |
+----+------------+------+---------------------+
| 1 | East Delhi | 1 | 2019-12-05 16:31:42 |
| 2 | West Delhi | 1 | 2019-12-05 16:31:42 |
| 3 | Mumbai | 2 | 2019-12-05 16:32:49 |
| 4 | Pune | 2 | 2019-12-05 16:32:49 |
| 5 | Adelaide | 5 | 2019-12-05 17:03:01 |
+----+------------+------+---------------------+
And a marginally different piece of PHP
<?php
#hardcode POST values for testing...
$_POST['country_id']=1;
$_POST['country_name']='India';
if( isset(
$_POST['country_id'],
$_POST['country_name']
)) {
$output='<option selected hidden disabled>Please Select State';
#require 'config.php';
# pertinent to my system
require '../../dbo/db-conn-details.php';
require '../../dbo/mysqli-conn.php';
# joining all tables
$query='select distinct ct.`id`,s.`state_name` from `tbl_country` ct
join `tbl_state` s on s.`c_id`=ct.`id`
join `tbl_city` c on c.`s_id`=s.`id`
where ct.`country_name`=?';
$stmt=$db->prepare( $query );
$stmt->bind_param('s', $_POST['country_name'] );
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->bind_result( $id, $name );
if( $rows > 0 ){
while( $stmt->fetch() ) $output .= sprintf('<option value="%s">%s',$id,$name);
}else{
$output='<option selected hidden disabled>No state found';
}
exit( sprintf('<select>%s</select>',$output ) );
}
?>
Results in generated HTML like this:
<select>
<option selected="" hidden="" disabled="">Please Select State</option>
<option value="1">Delhi</option>
<option value="1">Maharashtra</option>
</select>

Find nth TD in table

I trying to get find out the value(td text) in column C if I click on any cell in the same row
+----------+----------+-----+----------+----------+----------+----------+
| A | B | C | D | E | F | G |
+----------+----------+-----+----------+----------+----------+----------+
| click me | click me | ok1 | click me | click me | click me | click me |
+----------+----------+-----+----------+----------+----------+----------+
| click me | click me | ok2 | click me | click me | click me | click me |
+----------+----------+-----+----------+----------+----------+----------+
| click me | click me | ok3 | click me | click me | click me | click me |
+----------+----------+-----+----------+----------+----------+----------+
I have tried the following with an onclick event but nothing:
var tellMe = $(this).closest('tr').find('td:eq(2)').text();
alert(tellMe) //ok1 | ok2 | ok3
Thanks!

1 out of 3 dropdown list creating conflict using mysql

Ok so here are the tables I have:
departments associates
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
| dep_id | dep_name | date_added | | asso_id | asso_name | dep_id | date_added |
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
| 1 | Pick a Department| Date | | 1 | A Associate | 2 | Date |
| 2 | Department A | Date | | 2 | B Associate | 3 | Date |
| 3 | Department B | Date | | 3 | C Associate | 4 | Date |
| 4 | Department C | Date | | 4 | D Associate | 5 | Date |
| 5 | Department D | Date | | 5 | A Associate 2 | 2 | Date |
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
key_list key_log
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
| key_id | key_name | date_added | | id | key_assigned | key_status | assigned_to | assigned_by |
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
| 1 | Key 1 | Date | | 1 | Key 1 | 0 | A Associate | logged in name |
| 2 | Key 2 | Date | | 2 | Key 4 | 0 | B Associate | logged in name |
| 3 | Key 3 | Date | | | | | | |
| 4 | Key 4 | Date | | | | | | |
| 5 | Key 5 | Date | | | | | | |
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
So I'm trying to create a key log where I can store key names and associate names, and if the key was logged out or in. My first issue came when trying to link dropdown menus for departments and associates. I learned that you don't put comas for joins and someone suggested to just go ahead and use multiple querys.
So after some research I went about it this way:
<?php
$dbhost_name = "localhost";
$database = "db_name";
$username = "user_name";
$password = "password";
try {
$dbo = new PDO('mysql:host='.$dbhost_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<script>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='dd.php?cat=' + val ;
}
</script>
</head>
<body>
<?Php
#$cat=$_GET['cat']; // Use this line or below line if register_global is off
if(strlen($cat) > 0 and !is_numeric($cat)){ // to check if $cat is numeric data or not.
echo "Data Error";
exit;
}
$quer3="SELECT DISTINCT key_name, key_id FROM key_iv order by key_name";
$quer2="SELECT DISTINCT category,cat_id FROM category order by category";
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory";
}else{$quer="SELECT DISTINCT subcategory FROM subcategory order by subcategory"; }
echo "<form method=post name=f1 action='dd-check.php'>";
// Starting of first drop down
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
foreach ($dbo->query($quer2) as $noticia2) {
if($noticia2['cat_id']==#$cat){echo "<option selected value='$noticia2[cat_id]'>$noticia2[category]</option>"."<BR>";}
else{echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
}
echo "</select>";
// This will end the first drop down list
// Starting of second drop downlist
echo "<select name='subcat'><option value=''>Select one</option>";
foreach ($dbo->query($quer) as $noticia) {
echo "<option value='$noticia[subcategory]'>$noticia[subcategory]</option>";
}
echo "</select>";
// This will end the second drop down list
echo "<input type=submit value=Submit>";
echo "</form>";
?>
</body>
</html>
My problem with this is that when you select a key, and after select a department, the key originally selected gets reset and you have to go back and select the key again. You might say o well just place the keys drop down at the end. Well my intention is later to be able to select a key and with ajax or php check if the key status of that key is 0 (logged out) or 1 (logged back in), if it's on status 0, automatically select the radio button for status 1, and vise versa.
After this I did more research and found this Populate another select dropdown from database based on dropdown selection and so decided to go with this approach:
<?php
$db = new mysqli('localhost', 'carlos', 'Security5', 'testing');
$query = "SELECT dep_id, dep_name FROM department";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("id" => $row['dep_id'], "val" => $row['dep_name']);
}
$query = "SELECT ass_id, dep_id, ass_name FROM associates";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['dep_id']][] = array("id" => $row['ass_id'], "val" => $row['ass_name']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<!docytpe html>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
</head>
<body onload='loadCategories()'>
<?php
$quer3="SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
</body>
</html>
The problem with this is again when I place the first drop down before the other two, the other two don't work, and in this case completely disappear. When I place it after the two drop downs, everything works. I know, why am I not placing it after to fix it. Well like I said before, I need this to work for specifically adding other functionality later. Than and I refuse to accept that this can't be done. Can anyone tell me why this is not working for either method, and for that matter which is the better method.
I think the problem with your second attempt is you get key_name and key_id from your query, but where you write out the values in the options you refer to key_name and id (not key_id):
<?php
$quer3="SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
So, fixing that up (and the lack of quotes around names, and lack of escaping of data onto HTML):
<?php
$querykeys = "SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
printf("<select name='key_names'>\n");
printf("<option value=''>Select Key</option>\n");
foreach ($dbo->query($querykeys) as $row) {
printf("<option value='%s'>%s</option>",
htmlentities($row['key_id'], ENT_QUOTES),
htmlentities($row['key_name'], ENT_QUOTES)
);
}
echo "</select>\n";
?>

How to remove duplicates?

I am trying to create a dynamic tab and table headers from an xml file,
The tab name is goign to be "Adapter" or so forth to show up only once ie ignore any duplicates Tab names
Similar for the header names for the table as well
How can I remove teh duplicate tabs and header title?
Currently the output generated form the script below:
Adapters <- TAB
TargetClass | TargetName | DisplayName | AdminStatus | OperStatus | Type |
Interface | IF | IF | UP | UP | EMAC | Normal|
Adapters - <- TAB
TargetClass | TargetName | DisplayName | AdminStatus | OperStatus | Type |
Interface | IF | IF | UP | UP | EMAC | Alert|
Adapters - <-TAB
TargetClass | TargetName | DisplayName } AdminStatus | OperStatus | Type |
Network | IF | IF | UP | UP | EMAC | NA|
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "view.xml",
dataType: "xml",
complete: function(data,status) { parseXml(data.responseXML); }
});
});
function parseXml(xml)
{
$(xml).find("cView").each(function()
{
$("#output").append('<b>' + $(this).attr("type") + " - TAB CView type </b><br />");
$(this).find("field").each(function()
{
$("#output").append('<b>' +$(this).attr("name") + " -- </b>");
// $("#output").append($(this).text() + " -- ");
});
$("#output").append("<br />");
$(this).find("field").each(function()
{
//$("#output").append('<b>' +$(this).attr("name") + " -- </b>");
$("#output").append($(this).text() + " -- ");
});
$("#output").append("<br /><br/>");
});
}
XML bit
<?xml version="1.0" encoding="utf-8"?>
<feed>
<entry>
----
----
<cView type="D1">
<field name="TargetObjectClass">Disk</field>
<field name="TargetObjectName">DISK A1</field>
<field name="DisplayName">DISK-Name</field>
<field name="MaxAvgDataRate KB/sec">50.00 KB/sec</field>
<field name="MaxAvgQueueDepth">50.00</field>
</cView>
<cView type="D1">
<field name="TargetObjectClass">Disk</field>
<field name="TargetObjectName">DISK B2</field>
<field name="DisplayName"> Disk-Name 2 </field>
<field name="MaxAvgDataRate KB/sec">60.00 KB/sec</field>
<field name="MaxAvgQueueDepth">60.00</field>
</cView>
...
</entry>
</feed>
I don't understand what elements need to be clean, but maybe are you looking for that :
http://api.jquery.com/jQuery.unique/

table setAttribute not working properly in IE

I am trying to build an application that generates a custom list item which will be displayed on the screen dynamicly(like contact list update), and have the following code which works pretty well on both IE and Firefox.
<html>
<head>
<style type="text/css">
.divCss table{
width:100%;
height:130px;
}
.divCss {
width:100%;
height:100%;
border:solid 1px #c0c0c0;
background-color:#999000;
font-size:11px;
font-family:verdana;
color:#000;
}
.divCss table:hover{
background-color :#FF9900;
}
</style>
<script type="text/javascript" language="javascript">
var elementCounts = 0;
function myItemClicked(item)
{
alert("item clicked:"+item.id);
}
function createItem()
{
var pTag = document.createElement("p");
var tableTag = document.createElement("table");
tableTag.id = "" + (elementCounts++);
tableTag.setAttribute("border","1");
tableTag.setAttribute("cellpadding","5");
tableTag.setAttribute("width","100%");
tableTag.setAttribute("height","130px");
tableTag.onclick = function() {myItemClicked(this);};
var tBody = document.createElement("tbody");
var tr1Tag = document.createElement("tr");
var tdImageTag = document.createElement("td");
tdImageTag .setAttribute("width","100px");
tdImageTag .setAttribute("rowspan","2");
var imgTag = document.createElement("img");
imgTag.setAttribute("width","100px");
imgTag.setAttribute("height","100px");
imgTag.id = "avatar";
tdImageTag .appendChild(imgTag);
var tdTextTag= document.createElement("td");
tdTextTag.setAttribute("height","30%");
tdTextTag.setAttribute("nowrap","1");
tdTextTag.setAttribute("style","font-weight: bold; font-size: 20px;");
tdTextTag.id = "text";
tdTextTag.innerHTML = "text";
tr1Tag.appendChild(tdImageTag);
tr1Tag.appendChild(tdTextTag);
var tr2Tag = document.createElement("tr");
var tdAnotherTextTag = document.createElement("td");
tdAnotherTextTag.setAttribute("valign","top");
tdAnotherTextTag.id = "anotherText";
tdAnotherTextTag.innerHTML = "Another Text";
tr2Tag.appendChild(tdAnotherTextTag );
tBody.appendChild(tr1Tag);
tBody.appendChild(tr2Tag);
tableTag.appendChild(tBody);
tableTag.className ="divCss";
pTag.appendChild(tableTag);
document.getElementById("list").appendChild(pTag);
}
function clearList()
{
document.getElementById("list").innerHTML = "";
elementCounts = 0;
}
</script>
</head>
<body>
<input id="btn1" type="button" value="create item" onclick="createItem();" />
<input id="btn2" type="button" value="clear list" onclick="clearList();" />
<div id="list" class="divCss" style="overflow: scroll;"></div>
</body>
</html>
This code generates a new table element on click of "create item" button and adds it inside a div element on the main page.
The table element is supposed to be like the following
+---------------+--------------------+
| | Text |
| Image with | |
| rowspan of +--------------------|
| 2 | Another Text |
| | |
+---------------+--------------------+
The above code does showup properly on firefox, however on IE, the rowspan is kinda ignored and the output looks like
+---------------+--------------------+
| Image with | Text |
|rowspan ignored| |
|---------------+--------------------|
| Another Text | |
| | |
+---------------+--------------------+
Can anyone help me why this must be happening? I also checked writing direct tags ( instead of using createElement and appendChild), and that works, but the dynamic generation seems to be problamatic. Am I doing anything worng here?
Also, after adding the generated table elements in the div element ( "list" ), there seems to be some gap between consecutive table elements and am not able to remove it even if i specify margin and padding as 0 in div tag.
Any help would be much appreciated.
Thanks.
EDIT: About the gap between table elements inside div.
Here is the output as expected: ( This works in jsfiddle as suggessted by Shadow Wizard ).
+------------------------------------+
| List Element 1 |
+---------------+--------------------+
| | Text |
| Image with | |
| rowspan of +--------------------|
| 2 | Another Text |
| | |
+---------------+--------------------+
| List Element 2 |
+---------------+--------------------+
| | Text |
| Image with | |
| rowspan of +--------------------|
| 2 | Another Text |
| | |
+---------------+--------------------+
| List Element 3 |
+---------------+--------------------+
| | Text |
| Image with | |
| rowspan of +--------------------|
| 2 | Another Text |
| | |
+---------------+--------------------+
Here is the output that i get on chrome, ie, firefox..
+------------------------------------+
| List Element 1 |
+---------------+--------------------+
| | Text |
| Image with | |
| rowspan of +--------------------|
| 2 | Another Text |
| | |
+---------------+--------------------+
Gap
+------------------------------------+
| List Element 2 |
+---------------+--------------------+
| | Text |
| Image with | |
| rowspan of +--------------------|
| 2 | Another Text |
| | |
+---------------+--------------------+
Gap
+------------------------------------+
| List Element 3 |
+---------------+--------------------+
| | Text |
| Image with | |
| rowspan of +--------------------|
| 2 | Another Text |
| | |
+---------------+--------------------+
Sorry for explaining things like this. I was not able to upload my snapshots. However, you can see the difference between jsfiddle and other browser effects by opening the page as html file in any browser.
EDIT (Shadow_Wizard) - here is the screenshot:
In IE, the attributes are pretty limited and better be set "directly" and not via setAttribute.
Try this instead:
tdImageTag.rowSpan = 2;
Same for width and height: those better be set as part of the style:
imgTag.style.width = "100px";
imgTag.style.height = "100px";
Edit: by gaps do you mean the parts marked with red circles?
Edit II: if you see difference between jsFiddle and your own file it might mean you're missing DOCTYPE declaration. Try adding this line on top of your code, above the <html> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
jsFiddle is adding such line by itself, you can View Source to see it.
Also, I saw you're running the file locally... that's also not good you better run it as part of website to simulate "real" web page.
Try tdImageTag.setAttribute("rowSpan","2"); - it needs to be the upper case S
The gaps between the table elements may happen because the default cellspacing try this code: tableTag.cellSpacing=0;
Also if you are using the strict mode you can set the cellspacing in the css:
table.divCss {border-spacing:0;}

Categories