php How can I add additional selected items to an array - javascript

I am having problems with a list box that is set to multiple.
My setup is 3 individual list boxes, Categories(single select), Jobs(single select), and Tasks(multiple select)
When a users selects one item in Categories an ajax request populates the Jobs list box.
when a user selects one item from Jobs an ajax request populates the tasks box with one or more pre-selected items, plus the un-selected items.
All this works well my problem araises when I try to select additional items in tasks the pre selected items clear. I need the pre selected items to remain selected and be able to select additional items. I am using a function to select the additional item and refresh the tasks list box so that I do not have to press ctrl when selecting an item.
Here is my html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<?php
session_start();
include('dbcon/dbconnect.php');
$con=mysqli_connect($host,$user,$password,$db);
?>
<script>
function getSelectedItems(){
var items = "";
var frm = document.forms[0].s1;
var len = frm.length;
for(i=0;i<len;i++){
if(frm[i].selected){
items += frm[i].value + "~";
}
}
alert(items);
}
$(document).ready(function(){
$("select#cat").change(function(){
var cat_id = $("select#cat option:selected").attr('value');
$("#job").html( "" );
if (cat_id.length > 0 ) {
parent.top.$("#jobbtn").val("Change Category");
$.ajax({
type: "POST",
url: "fetch_jobs.php",
data: "cat_id="+cat_id,
cache: false,
beforeSend: function () {
$('#job').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#job").html( html );
}
});
}
});
$("select#job").change(function(){
var job_id = $("select#job option:selected").attr('value');
invid = 0;
$("#task").html( "" );
if (job_id.length > 0 ) {
$.ajax({
type: "GET",
url: "1a.php",
data: "job_id="+job_id+"&invid="+invid,
cache: false,
beforeSend: function () {
},
success: function(html) {
$("#task").html( html );
var selected = $("#task").val();
}
});
}
});
});
function getnotes(){
}
</script>
</head>
<body>
<form id="form1" >
<select id="cat" size="12" style='font-style:arial;font-size:14px;'>
<?php
$result = mysqli_query($con, "SELECT CatID, Catagory FROM catagory ORDER BY Catagory");
while($row = mysqli_fetch_array($result))
{
echo "<option value=\"".$row['CatID']."\">".$row['Catagory']."</option>\n ";
}
echo "</select>";
echo "<Div style='position:absolute;left:70px;top:0px;width:25px;z-index:1014;text-align:center;'>";
echo "<span id='jobl' style='position:fixed;left:180px;top:3px;font-family:Arial;font-size:15px;background-color:#FF9933 ;width:340px;height:20px;'>Jobs</span></div>";
echo "<select name='job' id='job' size='12' style='position:fixed;left:180px;top:23px;width:340px;font-size:14px;font-family:Arial;' onchange='' >";
echo "<option value='' ></option>";
echo "</select>";
echo "<Div style='position:absolute;left:70px;top:px;width:25px;z-index:1014;text-align:center;'>";
echo "<span id='taskl' style='position:fixed;left:535px;top:3px;font-family:Arial;font-size:15px;background-color:#FF9933;width:335px;height:20px;'>Tasks</span></div>";
echo "<select name='task' id='task' size='12' style='position:fixed;left:535px;top:23px;width:335px;font-size:14px;font-family:Arial;' onchange='getnotes()' multiple>";
echo "<option value='' ></option>";
echo "</select>";
echo "<input type='submit' id='taskb' name='taskb' style='position:fixed;top:330px;left:700px;width:150px;height:60px;font-size: 22px;font-weight: bold;white-space:normal;background:Lime;' value= 'Add Task->' onclick='shofinal();'></form></div>";
echo "</form>";
?>
<script>
(function() {
var selected = {};
$('select#task').click(function(e) {
var $this = $(this),
options = this.options,
option,
value,
n;
// Find out what option was just added
value = $this.val();
// Re-apply the selections
for (n = 0; n < options.length; ++n) {
option = options[n];
if (option.value == value) {
// The one being updated
selected[value] = !selected[value];
}
// One of the others
option.selected = !!selected[option.value];
}
});
})();
</script>
</body>
</html>
I believe my problem is in the script at the end of the html but I am unsure of what to change to fix this.

I have finally gotten this worked out thought I would post what fixed it for others to see/use
I added this jquery to the $(document).ready(function()
and now pre selected items stay selected and newly selected items are selected or if I click an item that is already selected it becomes unselected. I am pretty sure I understand what is happening here though I can not put it into words. But it works and I guess that is whats important.
I also removed the script from the end of the original html and everything is good so far.
Works in FF
window.onmousedown = function (e) {
var el = e.target;
if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
e.preventDefault();
// toggle selection
if (el.hasAttribute('selected')) el.removeAttribute('selected');
else el.setAttribute('selected', '');
// hack to correct buggy behavior
var select = el.parentNode.cloneNode(true);
el.parentNode.parentNode.replaceChild(select, el.parentNode);
}
}

Related

Get First Option on Text on Dropdown After Button Click

EDIT 1 - BRIEF
This is how it is. https://ibb.co/9WY5gLL it has a datatable, which is sorted according to dropdown selections and there is a button to reset the sortings. the reset part is working fine except the text in dropdown is not changing. but if I remove the slect box class in dropdown HTML all working fine.
//DROPDOWN HTML
<select name="status" id="status" class="statusbox SlectBox form-control">
<?php echo loadStatus(); ?>
</select>
//DATATABLE
$(document).ready(function() {
var table= $('#tableone').DataTable( {
"serverSide": true,
"ajax": {
url :"sonme.php",
type : "POST",
data : function(data){
var status = $('#status').val();
data.status= status;
}
} );
} );
//TABLE FILTER
$('#status').change(function(){
table.draw();
});
//RESET TABLE
$('#reset').click(function() {
$("select.statusbox").val($("select.statusbox option:first").val()).change();
});
//PHP RETURNED BY AJAX CALL
function location(){
global $con;
$output.= '<option value="_allCity">All Results</option>';
$_selectquery= "SELECT * FROM _tableone";
$result = mysqli_query($con, $_selectquery);
while($row = mysqli_fetch_array($result)){
$output.= '<option value = "'.$row["name"].'">'.$row["name"].'</option>';
}
return $output;
}
Since this is the sumo select jquery plugin, all what I had to is reviewing the documentation.
This line - $('select.SlectBox')[0].sumo.reload(); reset the dropdown and value as the default. Please check the doc: https://hemantnegi.github.io/jquery.sumoselect/

Select2 Custom Tags, Transform Value on Select

I would like a dropdown of text and then when one is selected I would like to load the full value as the tag and have it behave as normal.
I'm capturing the values selected then clearing the list and appending them as text into the .select2-choices div. It appears to work as it should but I've lost the ability to clear the manually appended tags.
Markup:
<div id="select2-container">
<select multiple class="select2" id="select2">
<optgroup label="GroupName">
<option value="John Smith - GroupName (ID:12345678)">John Smith</option>
</optgroup>
</select>
</div>
Script:
$('#select2').select2({
}).on('change', function (e) {
values = $(this).val();
console.log(values);
$('#select2-container .select2-choices').empty();
for (var i = 0; i < values.length; i++) {
console.log(values[i]);
$('#select2-container .select2-choices').append('<li class="select2-search-choice"><div>' + values[i] + '</div></li>');
}
});
I'm going to look into the formatSelection function but any help is greatly appreciated.
You've probably solved this by now, but you are correct that you want to use formatSelection.
Be default, the selected object's text property is used, but you want the id property instead. The id property is the <option> element's value.
$('#select2').select2({
formatSelection: function(object) {
return object.id;
}
});
jsfiddle
This is a solution in my project:
In edit.php file:
solution 1 (cate id is single number):
<?php
$cate_row = $db->fetchRow("SELECT cate_id, cate_name FROM categories WHERE cate_id=".$editdata[cate_id]." AND cate_status='Active'");
$cateArray[] = array("id"=>$cate_row['cate_id'], "text"=>$cate_row['cate_id']." - ".$cate_row['cate_name']);
echo "<script type=\"text/javascript\">
AjaxCombo('#categories', '/ajax/getCategories.php', true)
</script>";
echo "<input type=\"hidden\" name=\"sl2\" id=\"categories\" value='".json_encode($cateArray)."' data-placeholder=\"Select a category for this product..\" style=\"width: 400px !important;\" />";
?>
solution 2 (cate id is array: 12,4,5,6 or ,12,4,5,6,):
<?php
$cate_q = $db->query("SELECT cate_id, cate_name FROM categories WHERE cate_status='Active' ORDER BY cate_name ASC");
// array: ,12,4,5,6,
$editcate_array = explode(",", substr($editdata[cate_id], 1, $editdata[cate_id] - 1));
// or array 12,4,5,6
// $editcate_array = explode(",", $editdata[cate_id]);
while($cate_row = $db->fetch_array($cate_q)){
if(in_array($row['cate_id'], $editcate_array)) {
$cateArray[] = array("id"=>$cate_row['cate_id'], "text"=>$cate_row['cate_id']." - ".$cate_row['cate_name']);
}
}
echo "<script type=\"text/javascript\">
AjaxCombo('#categories', '/ajax/getCategories.php', true)
</script>";
echo "<input type=\"hidden\" name=\"sl2\" id=\"categories\" value='".json_encode($cateArray)."' data-placeholder=\"Select a category for this product..\" style=\"width: 400px !important;\" />";
?>
In JS global.js:
function AjaxCombo(elm, url, multiple) {
$(document).ready(function() {
$(elm).select2({
multiple: multiple,
minimumInputLength: 1,
ajax: {
url: url,
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return { q: term };
},
results: function (data, page) {
return {results: data};
}
},
// Add new category if no exist
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} }
});
$(elm).select2("data", JSON.parse($(elm).val()));
});
}
Default if form edit have cate data select2 init "id - Name category".
in file getCategories.php : from select you get $q = $input->gc['q'] and mysql is cate_name LIKE '%" . $q . "%';
while($row = $db->fetch_array($result)){
$dataArray[] = array("id"=>$row['cate_id'], "text"=>$row['cate_id']." - ".$row['cate_name']);
}
header('Content-Type: application/json');
echo json_encode($answer);
when get value form select2 you can try:
foreach ($_GET['select2'] as $value) {
echo $value;
}
done!

undefined is not a function javascript but works with alert box

I keep getting this error. I found that by giving an alert box as the first line of the function got rid of the problem. Help :(. I would like the function to loop through the select list onkeypress from a search textbox and compare it with the options in the select list. If it doesn't match it will temporarily remove or disable them. I apologize I may have not phrased the question right at first.
Code:
function search()
{
var searchText = document.getElementById("usersearch").value;
var usersList = document.getElementById("users");
usersList.disabled(true);
for(var i = 1; i<usersList.length; i++)
{
alert("test");
}
}
html code:
The problem persists and I have looked all over the internet but this problem I think can be caused for several reasons. I was using opera for testing.
This code creates the select list.
<script type="text/javascript">
var request = $.ajax({
url: "sendmsgprep.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
$(".users").html(msg);
});
request.fail(function(jqXHR, textStatus) {
//alert( "Request failed online 367: " + textStatus );
});
</script>
other file 'sendmsgprep.php"
<?php
$id = $_COOKIE['id'];
$username = $_COOKIE['username'];
require("connect.html");
echo '<select name="users" id="users" tabindex="4" onfocus="wipe(this)">
<option value="">--SELECT--</option>';
$query = "SELECT * FROM users WHERE user_id!='$id'";
$result = mysql_query($query, $connect)or die("Error on line 31<br>".mysql_error());
while ($row = mysql_fetch_array($result))
{
echo "<option value=".$row['user_id'].">".$row['username']."</option>";
}
echo '</select>';
?>

Live table edit display field(s) from other mySQL tables

I have a table that works like this: http://www.datatables.net/examples/api/editable.html without the header sorting, page changing, and search. I have another functionality that allows me to add a row. All of this is done on the same page. The data is drawn directly from a database. I wrote the code generic so it could be used for any table I want to display.
However, I have came across a problem. Let's say an end-user wants to see a list of houses. This list would be drawn from a houses database. Each house has an owner. There is also an owners table. Each owner has an id (primary_key). In the houses table the owner field uses the owner's id to identify the proper owner. Here is where the problem arises. Once the data from the houses table is displayed the owner, for instance, shows up as an id number. Obviously, to the end-user it either is meaningless or at least annoying. I would like to have, in this case the owner's name, the field that is in question to show instead of a "seemingly" meaningless field. I'm posting the relevant code for my predicament.
Also, can I change mySQL booleans through jQuery? What I mean by that is if, for example, a house is not up for rent so the for_rent flag is set to 0 for FALSE. The table will show 0, as that is what is in the table. Can I change that through jQuery? (Find the 0s or 1s and make them say true or false? Any suggestions as to a direction for answering these questions would be great. Thanks.
Here is the relevant code:
PHP to display table:
public function displayTable($table)
{
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo "<table id='table' border='1'>"; //start an HTML table
$dbtable = $table;
$fields =array();
$result = mysqli_query($con, "SHOW COLUMNS FROM ".$dbtable);
//fill fields array with fields from table in database
while ($x = mysqli_fetch_assoc($result))
{
$fields[] = $x['Field'];
}
$fieldsnum = count($fields); //number of fields in array
//create table header from dbtable fields
foreach ($fields as $f)
{
echo "<th>".$f."</th>";
}
//create table rows from dbtable rows
$result = mysqli_query($con, "SELECT * FROM ".$dbtable);
while ($row = mysqli_fetch_array($result))
{
$rowid = $row[$fields[0]];
echo "<tr class='edit_tr' id='".$rowid."'>";
foreach ($fields as $f)
{
echo "<td class='edit_td' data-field='".$f."'><span id='".$rowid."' class='text'>".$row[$f]."</span>
<input type='text' value='".$row[$f]."' class='editbox' id='".$rowid."' data-field='".$f."'/> </td>";
}
$rowid++;
echo "</tr>";
}
echo "</table>"; //close the HTML table
$recordid = $rowid;
//close connection
mysqli_close($con);
}
jQuery to live edit table:
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var table = $('body').attr('id');
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = {table:table, id:id, field:field, text:text};
if (field != text)
{
$.ajax({
type: "POST",
url: "classes/table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
window.location.reload(true);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
jQuery to live add row:
$(document).ready(function()
{
$(".add").click(function()
{
var fieldArray = [];
var $table = $("#table");
var $lastRow = $table.find("tr:last");
var $dataFields = $lastRow.find("td");
$dataFields.each(function() {
fieldArray.push($(this).attr("data-field"));
});
$("#table").each(function()
{
var $table = $(this);
var id=$('#table tr:last').attr('id');
var $tr = $("#table").children('tr');
var tablename = $('body').attr('id');
var n = $('tr:last td', this).length;
var tds = '<tr class="edit_tr" id="' + id++ + '">';
for(var i = 0; i < n; i++)
{
tds += '<td class="edit_td" data-field="' + fieldArray[i] +
'"><span id="'+ id +'" class="text"> </span><input type="text" class="editbox" id="' +
id + '" data-field="' + fieldArray[i] + '"/> </td>';
console.log('id: ' + id);
}
tds += '</tr>';
var dataString = {table:tablename, id:id};
if($('tbody', this).length > 0)
{
$('tbody', this).append(tds);
$.ajax({
type: "POST",
url: "classes/table_new_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
window.location.reload(true);
}
});
}else {
$(this).append(tds);
}
});
});
});
you will probably want to extend your generic function for generating the html table to include a joined db table if necessary, though that would get messy, so, create a new function for when you need to join 2 db tables.
The sql for retrieving the owners name into the list of houses would go something like (with a guess at what your field names are):
select a.housename,a.street,a.for_rent,b.name from houses a, owners b where a.owner_id=b.id

Populating a dropdown list with jquery

I am trying to populate a drop down list using jquery and ajax.
Here's what my code looks like.
<script>
$(document).ready(function(){ //This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ // the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
$("#time").html(data);
}
});
});
});
</script>
Here's time.php
//some code for connecting to database
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query="SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
echo"
<select name='timing' id='timing'>";
$i = 0; //Initialize the variable which passes over the array key values
$row = mysqli_fetch_assoc($result); //Fetches an associative array of the row
$index = array_keys($row); // Fetches an array of keys for the row.
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
$res = $index[$i];
echo jason_encode($res);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo "</select>";
?>
This just puts list on time.php into a div time on my page. Is there some way I could grap individual options from the list on time .php and add them to a dropdown list on my page?
Thanks in Advance.
try:
success:function(data)
{
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.YourReturnParam + '</option>';
});
$('#yourDdlID').html(option);
}
<script>
$(document).ready(function(){ //This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ // the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
var jdata=eval('('+data+')');;
var str='';
for(var i=0;i<jdata.length;i++)
{
str.='<option>'+jdata[i]+'</option>';
}
$("#time").html(str);
}
});
});
});
time.php will return like
$res=array('a','b','v')
echo json_encode($res);
It would make it easier if the data variable that's used in the success callback is JSON or an array.
success:function(data)
{
var option = $('#time');
//Remove old options
option.empty();
//It makes it easier if you create an array to store all of the values that you want to
//populate the select tag with. I'm not sure if the data that's returned is in the form of an array or not
var newOptions = {'key1': 'value1','key2': 'value2', 'key3': 'value3'};
//Loop thru and change each option tag
$.each(newOptions, function(key, value) {
option.append($('<option></option>').attr('value', value).text(key));
});
}
And the html might look something like this, I'm guessing?
<select id="time">
<option value="val">Text</option>
<option value="val">More Text</option>
</select>

Categories

Resources