Hi Guys I have this search from that takes a search term matches it with a table.field and in php it searches all matching data.
I want to add autocomplete to it, can anyone PLEASE assist?
Here is the HTML FORM
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<input type="text" id="searchThis" name="searchThis" placeholder="search" value="" size="14" />
<select name="searchItems" id="searchItems">
<optgroup value="Vehicles" label="Vehicles">Vehicles
<option value="vehicles.Make">Make</option>
<option value="vehicles.model">Model</option>
<option value="vehicles.RegNumber">Registration Number</option>
<option value="vehicles.licenseExpireDate">License Expire Date</option>
</optgroup>
<optgroup value="Owners" label="Owners">Clients
<option value="owners.OwnerName" label="" >Name</option>
<option value="owners.mobile">Mobile Number</option>
</optgroup>
</select>
<input type="submit" id="doSearch" name="Search" value="Search" />
</form>
<ul id="result">
</ul>
There is the JS
<script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
(function($j){
$j(document).ready(function (){
$j("#searchThis").keyup(function()
{
var searchThis = $j('#searchThis').val();
var searchItems = $j('#searchItems').val();
var dataString = {'searchThis': searchThis,'searchItems':searchItems};
if(searchThis!='')
{
$j.ajax({
type: "POST",
url: "doAutocomplete_search.php",
data: dataString,
dataType: "html",
cache: false,
success: function(data)
{
$j("#result").html(data).show();
}
});
}return false;
});
$j("#result").live("click",function(e){
var clicked = $j(e.target);
var name = clicked.find('.name').html();
var decoded = $j("<div/>").html(name).text();
$j('#searchThis').val(decoded);
});
$j(document).live("click", function(e) {
var clicked = $j(e.target);
if (! clicked.hasClass("search")){
$j("#result").fadeOut();
}
});
$j('#searchid').click(function(){
$j("#result").fadeIn();
});
});
})($j);
And the PHP
function implement($cxn,$searchThis, $field) {
$show = "";
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
$srchData = array();
$rows = mysqli_fetch_row($selectc);
echo $rows;
//if() {, MYSQL_ASSOC
//echo var_dump($srchData);
$show .= '
<table style="border:2px solid #0000">';
//foreach($srchData as $fields=>$data) {
for($s=0; $s < $rows && $srchData = mysqli_fetch_assoc($selectc);$s++) {
if($srchStack[0] == 'vehicles' && $fields == 'RegNumber') {
$dataItem = $data;
$editTbl = 'Vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
} elseif($srchStack[0] == 'vehicles' && $fields == 'Make') {
$dataItem = $data;
$editTbl = 'vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
}
$show .= '<tr><td><a '.$link.'>'.$data.'</a></td></tr>
';
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
//}
}
echo implement($cxn, $_POST['searchThis'], $_POST['searchItems']);
$cxn->close();
Hi Guys so i had to do some refactoring, realized it was more the PHP MySQL code.
Here is the refactored PHP code
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
//$srchData = array();
$rows = mysqli_num_rows(#$selectc) or die(mysqli_error($cxn).'<br>No Rows returned...');
if($rows > 0) {//, MYSQL_ASSOC
//$link = ''; $l_c = 0;
$show .= '<table style="border:2px solid #0000">';
for($c = NULL;$c != $rows && $srchData = mysqli_fetch_assoc($selectc); $c++) {
foreach($srchData as $fields=>$data) {
if($fields == $srchStack[1]) {
$dataItem = $data;
$editTbl = $srchStack[0];
$show .= '<tr><td>'.$dataItem.'</td></tr>';//$a_json_row($dataItem);
//$show .= $link[$c];$link[$c]
}
}
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
Of-course the JS code still needs some more work but this greatly improved the results...
Hope this help someone...
Related
I have a notifications system on my site, that utilizes AJAX to update in real-time. The problem is that it works on every browser except IE 11. After looking around I noticed some people advising to use cache:false in the call. However, this makes the code non-functional across all browsers. Anyone know what the solution is?
JAVASCRIPT:
<script>
$(document).ready(function(){
$('.notif_count').html('0');
function load_unseen_notification(view = '')
{
$.ajax({
url:"notif_follow.php",
method:"POST",
data:{view:view},
dataType:"json",
success:function(data)
{
$('.notif_follow').html(data.notification);
if(data.notif_count > 0)
{
$('.notif_count').html(data.notif_count);
}
}
});
}
load_unseen_notification();
$(document).on('click', '.notif', function(){
$('.notif_count').html('0');
load_unseen_notification('yes');
});
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
</script>
PHP:
<?php
session_start();
require_once 'class.channel.php';
$user_notif = new USER();
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
if($_POST["view"] != '')
{
$stmt = $user_notif->runQuery("UPDATE notif_follow SET status = 1 WHERE receive_id = ?");
$stmt->bindValue(1,$user_id);
$stmt->execute();
}
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if(count($notifs) > 0)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT * FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetchAll(PDO::FETCH_ASSOC);
if(count($query2result) > 0){
$follow = '<button class="button" style="margin:2px;">Remove Channel</button>';
}
else{
$follow = '<button class="button" style="margin:2px;">Add Channel</button>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
<button class="button" style="margin:2px;">View Channel</button>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}
$count = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? AND status= 0");
$count->bindValue(1,$user_id);
$count->execute();
$countresult = $count->fetchAll(PDO::FETCH_NUM);
if(count($countresult) > 0){
$notif_count = count($countresult);
}
else{
$notif_count = 0;
}
header('Content-type: application/json');
$notif_array = array('notification'=>$notification,'notif_count'=>$notif_count);
echo json_encode($notif_array);
}
?>
I mixed an "ajax select" and "while scrolling load data" script, and this is working, but I don't know how to print "not found data" in div.status when the output variable (on animals.php) is empty.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Animals</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="search">
<div class="filter category">
<select name="category" id="category">
<option value="">All</option>
<option value="free">Free</option>
<option value="lost">Lost</option>
<option value="found">Found</option>
</select>
</div>
<div class="filter chipnumber">
<input type="text" name="chipnumber" id="chipnumber"></div>
</div>
<div class="send">
<button type="submit" id="submit">Search</button>
</div>
</div>
<script>
$(document).ready(function() {
var animal_limit = 6;
var animal_start = 0;
var animal_action = 'inactive';
function load_animal_data() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
$.ajax({
url: "animals.php",
method: "POST",
data: {animal_limit:animal_limit, animal_start:animal_start, animal_action:animal_action, category:category, chipnumber:chipnumber},
success:function(data) {
$('div.animals').append(data);
if (data == '') {
animal_action = 'active';
} else {
animal_action = 'inactive';
}
}
});
}
load_animal_data();
function search() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
animal_start = 0;
load_animal_data();
}
$('#search').on('click', function() {
search();
});
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $('div.animals').height() && animal_action == 'inactive') {
animal_action = 'active';
animal_start = animal_start + animal_limit;
setTimeout(function() {
load_animal_data();
}, 1000);
}
});
});
</script>
<div class="animals"></div>
<div class="status"></div>
</body>
</html>
animals.php
<?php
$connect = mysqli_connect("localhost", "root", "", "petsdata");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($connect,"utf8");
$output = '';
$animal_start = $connect->real_escape_string($_POST["animal_start"]);
$animal_limit = $connect->real_escape_string($_POST["animal_limit"]);
$category = $connect->real_escape_string($_POST["category"]);
$chipnumber = $connect->real_escape_string($_POST["chipnumber"]);
if (isset($animal_start, $animal_limit, $category, $chipnumber)) {
if (!empty($category) && !empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($category)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND status = '1' ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
else {
$query = mysqli_query($connect, "SELECT * FROM animals ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
while ($row = mysqli_fetch_array($query)) {
$output .= '<div class="animal">';
$output .= '<span>Category: ' . $row["category"] . '</span>';
$output .= '<span>Chipnumber: ' . $row["chipnumber"] . '</span>';
$output .= '</div>';
}
}
echo $output;
?>
if($query->num_rows > 0){
//Proceed as normally
}else{
$output = 'No data Found';
}
I have a question about drilldown combo boxes using php and javascript.
When I choose parent data, child data become selectable; and it is controlled in javascript.
I tried to keep the two values after post, but the following code remain only the parent data. How do I remain the two values in drilldown combo boxes after submission?
HTML&php
<select id="SEL1" name="SEL1">
<option value="">---</option>
<?php
foreach ($parent_list as $parent => $children_list) {
echo '<option value="'.$parent.'"';
if ($parent == $_GET['SEL1']){
echo 'selected';
}
echo '>'.$parent.'</option>';
}
?>
</select>
<select id="SEL2" name="SEL2">
<option value="">---</option>
<?php
foreach ($parent_list as $parent => $children_list) {
echo '<optgroup label="'.$parent.'">';
foreach ($children_list as $children => $grandson_list) {
$view_children = str_replace($parent,"",$children);
echo '<option value="'.$children.'"';
if ($children == $_GET['SEL2']){
echo 'selected';
}
echo '>'.$view_children.'</option>';
}
echo '</optgroup>';
}
?>
</select>
javascript
function ConnectedSelect(selIdList){
for(var i=0;selIdList[i];i++) {
var CS = new Object();
var obj = document.getElementById(selIdList[i]);
if(i){
CS.node=document.createElement('select');
var GR = obj.getElementsByTagName('optgroup');
while(GR[0]) {
CS.node.appendChild(GR[0].cloneNode(true));
obj.removeChild(GR[0]);
}
obj.disabled = true;
}
if(selIdList[i+1]) {
CS.nextSelect = document.getElementById(selIdList[i+1]);
obj.onchange = function(){ConnectedSelectEnabledSelect(this)};
} else {
CS.nextSelect = false;
}
obj.ConnectedSelect = CS;
}
}
function ConnectedSelectEnabledSelect(oSel){
var oVal = oSel.options[oSel.selectedIndex].value;
if(oVal) {
while(oSel.ConnectedSelect.nextSelect.options[1])oSel.ConnectedSelect.nextSelect.remove(1);
var eF = false;
for(var OG=oSel.ConnectedSelect.nextSelect.ConnectedSelect.node.firstChild;OG;OG=OG.nextSibling) {
if(OG.label == oVal) {
eF = true;
for(var OP=OG.firstChild;OP;OP=OP.nextSibling)
oSel.ConnectedSelect.nextSelect.appendChild(OP.cloneNode(true));
break;
}
}
oSel.ConnectedSelect.nextSelect.disabled = !eF;
} else {
oSel.ConnectedSelect.nextSelect.selectedIndex = 0;
oSel.ConnectedSelect.nextSelect.disabled = true;
}
if(oSel.ConnectedSelect.nextSelect.onchange)oSel.ConnectedSelect.nextSelect.onchange();
}
ConnectedSelect(['SEL1','SEL2']);
//-->
</script>
I have a problem with form. After i click Dodaj button nothing happens.
I've putted alert dialog to see when it stops and it stops after
$.post('dodaj_ztoner.php', post_data, function(response){
I have made similar forms with similar code (names and number of items was different) and it worked
alert('post'); is not displaying. so looks like problem is here $.post('dodaj_ztoner.php', post_data, function(response){
html code:
<body>
<div id="dialog" title="Błąd Wprowadzania!">
<p>Proszę uzupełnić podświetlone pola.</p>
</div>
<div class="container">
<fieldset id="contact_form">
<h2>Zużycie Tonera</h2>
<div id="zresult"></div>
<label for="id"><span>ID</span></label>
<input type="text" name="zid" id="zid" value="<?php
$zapytanie = "select max(id) as id from zuzycie_toner";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo $wynik['id']+1;
}
mysql_free_result($widok);
?>" disabled />
<label for="zdata"><span>Data wydania</span></label>
<input type="text" name="zdata" id="zdata" />
<label for="ilwyd"><span>Ilość wydrukowanych</span> </label>
<input type="text" name="ilwyd" id="ilwyd" />
<label for="drukarka"><span>Drukarka</span></label>
<select type="text" name="zdrukarka" id="zdrukarka" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from drukarki order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="toner"><span>Toner</span></label>
<select type="text" name="ztonery" id="ztonery" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from tonery order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="user"><span>Użytkownik</span> </label>
<select type="text" name="zuser" id="zuser" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwisko_imie as id from uzytkownicy order by nazwisko_imie";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[id]</option>";
}
mysql_free_result($widok);
?>
</select>
<label><span> </span>
<button type="submit" class=submit_btn" id="zsubmit_btn">Dodaj</button>
</label>
JavaScript:
<script type="text/javascript">
$(document).ready(function() {
var divObj = $('#dialog');
divObj.dialog({
autoOpen: false
}
);
$( "#zdrukarka" ).selectmenu();
$( "#zuser" ).selectmenu();
$( "#ztonery" ).selectmenu();
$("#zdata").datepicker();
$( "button[type=submit]" )
.button()
$("#zsubmit_btn").click(function() {
//Pobieramy dane
var ztoner_id = $('input[name=zid]').val();
var ztoner_data = $('input[name=zdata]').val();
var ztoner_wydr = $('input[name=ilwyd]').val();
var ztoner_toner = $('select[name=ztonery]').val();
var ztoner_user = $('select[name=zuser]').val();
var ztoner_drukarka = $('select[name=zdrukarka]').val();
//Prosta walidacja (kolorujemy na czerwono pole jeśli jest puste
var proceed = true;
alert( '1');
//wszystko w porządku idziemy dalej
if(proceed)
{
//Dane do wysłania
post_data = {'ztonerID':ztoner_id, 'ztonerWydr':ztoner_wydr, 'ztonerData' :ztoner_data, 'ztonerToner' :ztoner_toner,
'ztonerUser':ztoner_user, 'ztonerDrukarka':ztoner_drukarka};
//Przesłanie danych poprzez AJAX
$.post('dodaj_ztoner.php', post_data, function(response){
alert( 'post');
//wczytanie danych zwrotnych JSON
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
}
$("#zresult").hide().html(output).slideDown();
}, 'json');
} else divObj.dialog("open");
});
//resetujemy kolorowanie po zaczęciu pisania
});
</script>
PHP file:
<?php
include './includes/html_elements.php';
//pokaz_zmienna($_SERVER);
$db_link = connect_db();
if(!$db_link)
{
$out='<p>Brak połączenia z bazą danych</p>';
print_page($out, 'Baza książek');
exit;
}
if($_POST)
{
//Sprawdzamy czy jest to rządanie Ajax, jeśli nie..
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//Kończymy skrypt wysyłając dane JSON
$output = json_encode(
array(
'type'=>'error',
'text' => 'Rządanie musi przejść przez AJAX'
));
die($output);
}
//Sprawdzamy czy wszystkie pola zostały wysłane. kończymy skrypt jeśli nie (tutaj dodawaj więcej pól, które są wymagane)
if(!isset($_POST["ztonerID"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'POLA SĄ PUSTE!'));
die($output);
}
//Pobieramy dane z formularza
$ztoner_id = filter_var($_POST["ztonerID"], FILTER_SANITIZE_STRING);
$ztoner_data = filter_var($_POST["ztonerData"], FILTER_SANITIZE_STRING);
$ztoner_wydr = filter_var($_POST["ztonerWydr"], FILTER_SANITIZE_STRING);
$ztoner_drukarka = filter_var($_POST["ztonerDrukarka"], FILTER_SANITIZE_STRING);
$ztoner_toner = filter_var($_POST["ztonerToner"], FILTER_SANITIZE_STRING);
$ztoner_user = filter_var($_POST["ztonerUser"], FILTER_SANITIZE_STRING);
//Dodatkowa validacja PHP (tylko dla pól wymaganych)
if(!is_numeric($ztoner_id)) //sprawdzamy czy telefon jest numeryczny
{
$output = json_encode(array('type'=>'error', 'text' => 'Tylko liczby są dozwolone'));
die($output);
}
die($output);
}
$zapytanie = "select idd from drukarki where nazwa = '$ztoner_drukarka'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_drukarka = $wynik['idd'];
}
mysql_free_result($widok);
$zapytanie = "select idu from uzytkownicy where nazwisko_imie = '$ztoner_user'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_user = $wynik['idu'];
}
mysql_free_result($widok);
$zapytanie = "select idt from tonery where nazwa = '$ztoner_toner'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_toner = $wynik['idt'];
}
mysql_free_result($widok);
$insert = "Insert INTO zuzycie_toner Values ($ztoner_id, '$ztoner_data', $ztoner_wydr, $ztoner_drukarka, $ztoner_toner, '$ztoner_user')";
$wykonaj = mysql_query($insert);
if ($wykonaj)
{
$output = json_encode(array('type'=>'message', 'text' => 'Dodano '.$drukarki_nazwa.' do tabeli'));
die($output);
}else{
$output = json_encode(array('type'=>'error', 'text' => 'Dodawanie nie powiodło się '.$insert));
die($output);
}
}
?>
Your page doesn't conatains any form tag, so simple use
<button class=submit_btn" id="zsubmit_btn">Dodaj</button> instead of input type = submit
This will Work!!!!
I have two selected menu the 1st one we chose the type so the next will filter the mysql database to show the depertments numbers, and i need to show the depertment price in a textfiled after i select the depertment number from the second selectedmenu.
1st selected menu
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>"> <?php echo $row['name']; ?>
<?php } ?>
</option>
<?php } ?>
</select>
2nd selected menu
<select name="category"
disabled="disabled" class="update" id="category" onChange="precio()" onClick="show()" >
<option value="">----</option>
</select>
this is how i get the value for the 2nd selected value
update.php
<?php
if (!empty($_GET['id']) && !empty($_GET['value'])) {
$id = $_GET['id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=name', 'root', '1234');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `depertamientos`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
if ($row['visible'] == 0) {
$out[] = '<option value="'.$row['name'].'" id="'.$row['precio'].'">'.$row['name'].'</option>';
}
}
echo json_encode(array('error' => false, 'list' => implode('', $out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
core.js
var formObject = {
run : function(obj) {
if (obj.val() === '') {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
} else {
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON('mod/update.php', { id : id, value : v}, function(data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
} else {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
}
});
}
}
};
$(function() {
$('.update').live('change', function() {
formObject.run($(this));
});
});
js function
> <script src="javascripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function show() {
var select = document.getElementById('category');
var input = document.getElementById('ds');
var change = document.getElementById('dpto');
var deptprecio = document.getElementById('11');
select.onchange = function() {
input.value = select.value;
deptprecio.value = "I don't know what to do here ???? ";
change.value = select.value;
}
}
</script>
my data base :
id master name visible precio
-------------------------------------------------
1 0 Type a 0 0
2 0 type b 0 0
3 1 101 1 20000
4 1 201 1 10000
5 2 103 1 30000
why putting the price as the id of your options tag ? Why not putting it in the value propertie as in #WebDevRon example?
$out[] = '<option value="'.$row['name'].'">'.$row['name'].'</option>';
remove javascript event in your your HTML tag:
<select name="category"
disabled="disabled" class="update" id="category" >
<option value="">----</option>
</select>
and if i understand your request you could just replace your javascript function "show" by something like this:
$("#category").change(function () {
var price = $(this).val();
$('#price-input').val(price); // where "price-input" is the id of your input.
});
Edit:
use data-attibute to store the price:
$out[] = '<option value="'.$row['name'].'" data-price="'.$row['precio'].'">'.$row['name'].'</option>';
JS:
$(function() {
$('.update').live('change', function() {
formObject.run($(this));
});
$("#category").change(function () {
var dept_number = $(this).val();
var price = $(this).find(':selected').data('price');
$('#dept-input').val(dept_number);
$('#price-input').val(price);
});
});
FIDDLE DEMO
Here is your complete solution - Demo
var $select2 = $('#select2');
var $text = $('#price');
$("#select1").change(function () {
var id = $(this).val();
if ($select2.data('options') == undefined) {
$select2.data('options', $select2.find('option').clone());
}
var options = $select2.data('options').filter('[value=' + id + ']');
$select2.html(options);
$text.val(id);
});