I have a Select box and a text box to search through the list in the select box. The Select box is getting populated from a database with PHP. What I am trying to achieve here is as soon as clear the text field; the select box should refresh. I have to reload the whole page to do that. Here is the little script that I using to search through select box.
function filterSelectBox(filterButton) {
var searchValue = document.getElementById('selectFilter').value.toLowerCase();
var selectField = document.getElementById("domainID");
var optionsLength = selectField.options.length;
for(var i = 0; i < optionsLength; i++) {
if(selectField.options[i].innerHTML.toLowerCase().indexOf(searchValue) >= 0) {
selectField.options[i].style.display = 'block';
} else {
selectField.options[i].style.display = 'none';
}
}
}
Here is HTML Elements associated with the code.
<div class="search_domains" id="search_domains">
<input type="text" id="selectFilter" name="selectFilter" />
<input type="button" id="filterButton" value="Filter" onClick="filterSelectBox(this)"/>
</div>
and this is how I am populating the Select box,
<select name="domainID" id="domainID" size="15" style="width:175">
<option>Select a Domain</option>
<? foreach ($domains as $row) {
?>
<option value="<?=$row -> id ?>"><?=$row -> domain ?></option>
<? } ?>
</select>
Put this code:
document.getElementById('selectFilter').onkeyup = function() {
if(this.value.length == 0) {
var selectField = document.getElementById("domainID");
var optionsLength = selectField.options.length;
for(var i = 0; i < optionsLength; i++) {
selectField.options[i].style.display = 'block';
}
}
};
just before the </body> tag in your page, and it will show all of the options when you clear the textbox value.
What I'd do here is populate the list with AJAX from that same PHP file, but have it output JSON. On loading the page, the AJAX request would load the php file, get the JSON and add the items in the list.
For refreshing when the text field is blank, you could use an onChange or onKeyUp and check the length of the value.
I think all this would be much simpler in jQuery or any JS framework than pure JS :)
These will help:
http://css-tricks.com/dynamic-dropdowns/
Using jQuery, JSON and AJAX to populate a drop down
Populate dropdown using json
Populate Dropdown Menu in PHP from JSON
You could definitely use AJAX, but for this example, it may not be necessary. It might be more efficient to just store the original contents in a Javascript array and reset it when you need to. I would actually remove the options instead of hiding them:
<script type="text/Javascript">
var originalOptions = {<?php $echo = array(); foreach ($domains as $row) $echo[] = "\"{$row->id}\":\"{$row->domain}\""; echo implode(", ", $echo); ?>};
function filterSelectBox(text)
{
var selectField = document.getElementById('domainID');
selectField.options.length = 0;
for (var key in originalOptions)
{
if (originalOptions[key].substr(0, text.length) == text)
{
var option = document.createElement("option");
option.value = key;
option.text = originalOptions[key];
selectField.add(option, null);
}
}
}
</script>
<select name="domainID" id="domainID" size="15" style="width:175">
<?php foreach ($domains as $row) {
echo "\t<option value=\"{$row->id}\">{$row->domain}</option>\n";
} ?>
</select>
<input type="text" onkeyup="filterSelectBox(this.value)" />
Related
I'm trying to auto populate some text fields (rate1 and rate2) based on a dropdown selection (instid and instfirstname). The values are all in one mysql table called tbl_insts. I'm trying the solution found in How to Get Content in text field dynamically, based on dropdown selection in php, but can't get it to work. Does anyone have any suggestions? Thanks in advance.
This is my mysql table called tbl_insts
instid instfirstname rate1 rate2
1 john 50 45
2 eric 25 45
This is my html form. I'm able to populate the dropdown correctly but not the text fields.
<select name="instfilter" id="instfilter">
<?php
if ($stmt = $conn->prepare("select instid, instfirstname from tbl_insts order by instid")) {
$stmt->execute();
$stmt->bind_result($instid, $instfirstname);
echo '<option value="-1" selected="selected">Please select...</option>';
while ($stmt->fetch()) {
echo '<option value="'.$instid.'">'.$instfirstname.'</option>';
}
$stmt->close();
}
?>
</select>
<!-- Fields that I want to populate based on the selection on top -->
<input type="text" name="rate1" id="rate1" />
<input type="text" name="rate2" id="rate2" />
This is my code before the tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$('#instfilter').change(function(){
var inst = $(this).val();
$.ajax({
type:'POST',
data:{inst:inst},
url:'getrates.php',
success:function(data){
$('#rate1').val(data);
$('#rate2').val(data);
}
});
});
</script>
This is my code in getrates.php in the same directory as the html file above.
<?php
if (isset($_POST['inst'])) {
$qry = "select rate1, rate2 from tbl_insts where instid = ".
$_POST['inst'];
$rec = mysql_query($qry);
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1'];
echo $res['rate2'];
}
}
}
die();
?>
try change data:{inst:inst} to data:{'inst':inst}
now you returning a string from getrates.php. From you code structure, you can do like this:
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1']."|".$res['rate2'];
}
}
..and
success:function(data){
var inputs = data.split('|');
$('#rate1').val(inputs[0]);
$('#rate2').val(inputs[1]);
}
hope this helps.
Untested, but I think these changes should do the job.
while ($res = mysql_fetch_array($rec)) {
$result = [
'rate1' => $res['rate1'],
'rate2' => $res['rate2']
];
}
.......
die(json_encode($result));
and
success: function(data){
data = $.parseJSON(data);
$('#rate1').val(data.rate1);
$('#rate2').val(data.rate2);
}
I have a menu that is dynamically created. When the user selects a value, I need to get that value and use it for a query statement. This is not a form, just a menu on the page.
I have:
<select name="topic" id="topic">
<option value="optiont" selected="selected">Select topic...</option>
<?php
while ($row = mysqli_fetch_array($sql))
{
echo "<option value=\"optiont$count\" name=\topic[]\">" . $row['topic'] . "</option>";
$count++;
}
?>
</select>
I want to know which option is selected. How can I do this??
This will get the value when you change the DDL:
$('#topic option').on("change", function () {
var opt_ID = $(this).val();
//Do something here using opt_ID as the value e.g.
window.location = '/URL/file.php?' + opt_ID;
});
Try this:
jquery:
var selvalue = $("#topic option:selected").val();
$.get( "demo.php?value="+selvalue, function(data) {
alert(data);
});
Demo.php:
<?php
$sel = $_GET['value'];
// write your query here
?>
Having difficulty getting this to work. Using Chrome javascript console, I can see that my function is firing and getting the result I nee, it just won't populate the multiple select. Here's the code:
jQuery:
$("select[name='field[one]']").change(function()
{
var optionValue = $("select[name='field[one]']").val();
$.get
('/directory/location/getData', {select:optionValue},
function(data)
{
$("select[name='subjects']").val(data);
}
);
}
);
HTML:
<select name="field[one]" id="field_one">
<option value="" selected="selected"></option>
<option value="2011">2011</option>
</select>
<select multiple id="show_results" name="subjects" />
</select>
AJAX PHP Call:
public function executeGetData(sfWebRequest $request){
$year = $request->getParameterHolder()->get('select');
$specialties = Doctrine_Core::getTable('Specialty')->getSpecialtyArray();
$array = array();
foreach($specialties as $specialty){
$array[$specialty['id']] = '';
$count = Doctrine_Core::getTable('HistoricalSalaries')->getCountPerSpec($year, $specialty['id']);
$array[$specialty['id']] .= $specialty['name']." Count($count)";
}
return $this->renderText( json_encode( $array ) );
}
The result is a json encoded array... which I think is the problem... getting the multiple select to interpret that info correctly. Currently nothing happens after the call is made and the data retrieved.
Here is a sample of the json encoded array result shown in chrome debugger:
{
2: "Aerospace Medicine Count(50)",
3: "Abdominal Radiology (DR) Count(65)",
4: "Addiction Psychiatry (P) Count(46)",
5: "Adolescent Medicine (PD) Count(23)"
}
Thanks in advance.
You can do this:
function(data) {
$.each(data, function(index, itemData) {
var newOption = "<option value='" + index + "'>" + itemData + "</option";
$("#show_results").append(newOption);
});
}
Here's a fiddle that demo's looping over the JSON: http://jsfiddle.net/tymeJV/8eUFe/
Here's a fiddle demoing your problem: http://jsfiddle.net/tymeJV/8eUFe/1/
I actually converted the html checkboxes into images(below is the code), now the checkboxes have 3 states one for checked, one for unchecked and one for null,
now i want to add a DRAG feature to it like if we select unchecked and drag on other checkboxes, the other checkboxes should get this value, i meam the image must be changed.
Here is an example on this link http://cross-browser.com/x/examples/clickndrag_checkboxes.php , this example is without images but i want the same thing to happen with images.
Any help will really make my day, Thanks!
here is the code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var inputs;
var checked = 'checked.jpg';
var unchecked = 'unchecked.jpg';
var na = 'na.jpg';
function replaceChecks()
{
//get all the input fields on the funky_set inside of the funky_form
inputs = document.funky_form.getElementsByTagName('input');
//cycle trough the input fields
for(var i=0; i < inputs.length; i++)
{
//check if the input is a funky_box
if(inputs[i].className == 'funky_box')
{
//create a new image
var img = document.createElement('img');
//check if the checkbox is checked
if(inputs[i].value == 0 )
{
img.src = unchecked;
inputs[i].checked = false;
}
else if(inputs[i].value = 1 )
{
img.src = checked;
inputs[i].checked = true;
}
else if(inputs[i].value = 2 )
{
img.src = na;
inputs[i].checked = true;
}
//set image ID and onclick action
img.id = 'checkImage'+i;
//set name
img.name = 'checkImage'+i;
//set image
img.onclick = new Function('checkChange('+i+')');
//place image in front of the checkbox
inputs[i].parentNode.insertBefore(img, inputs[i]);
//hide the checkbox
inputs[i].style.display='none';
}
}
}
//change the checkbox status and the replacement image
function checkChange(i)
{
if(inputs[i].value==0)
{
inputs[i].checked = true;
inputs[i].value = 2;
document.getElementById('checkImage'+i).src=na;
}
else if(inputs[i].value==1)
{
inputs[i].checked = false;
inputs[i].value = 0;
document.getElementById('checkImage'+i).src=unchecked;
}
else if(inputs[i].value==2)
{
inputs[i].checked = true;
inputs[i].value = 1;
document.getElementById('checkImage'+i).src=checked;
}
}
setTimeout(function(){replaceChecks();}, 0);
</script>
</head>
<form name="funky_form" action='checkkkkkkkkkkkkkkkkkkkkkkkkk.php' method='POST'>
<table id="table1" border=1px cellpadding=1px cellspacing=1px>
<tr>
<th>D/T</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
<th>10</th>
<th>11</th>
<th>12</th>
<th>13</th>
<th>14</th>
<th>15</th>
<th>16</th>
<th>17</th>
<th>18</th>
<th>19</th>
<th>20</th>
<th>21</th>
<th>22</th>
<th>23</th>
<th>24</th>
</tr>
<?php
$days = array('SUN');
foreach($days as $key=>$val)
{
print "<tr>";
print"<th>$val</th>";
for($i=0; $i<24; $i++){
print "<td>";
print " <input type=\"checkbox\" id=\"${val}${i}\" name=\"sun${i}\"
class=\"funky_box\" />";
print "</td>";
}
print "</tr>";
}
$days = array('MON');
foreach($days as $key=>$val)
{
print "<tr>";
print"<th>$val</th>";
for($i=0; $i<24; $i++){
print "<td>";
print " <input type=\"checkbox\" id=\"${val}${i}\" name=\"mon${i}\"
class=\"funky_box\" />";
print "</td>";
}
print "</tr>";
}
?>
</table>
</form>
It really is quite simple, bind an event to mousedown and not click, set a variable to indicate that the button is held down and at the same time check/uncheck the current checkbox etc.
Set another event to the mouseenter event of any checkbox, then check it the mousebutton is held down, and set the state to the same as the first checkbox where the mousebutton was first pressed down.
var state = false, mouse=false;
$('checkbox').on({
click: function(e) {
e.preventDefault();
},
mousedown: function(e) {
this.checked = !this.checked;
state = this.checked;
if(e.which === 1) mouse = true;
},
mouseup: function(e) {
if(e.which === 1) mouse = false;
},
mouseenter: function(e) {
if (mouse) this.checked = state;
}
});
Here's a fiddle to show how : FIDDLE
This will still have some bugs in it, and will need some additional checks etc. but it's basically how it's done.
I'm not going to go through all your code with bits of PHP and javascript sprinkled in it, you should probably have set up a fiddle with the HTML and some images if that is what you wanted, so you'll have to figure out how and where to switch the images yourself, but that should be pretty straight forward
There are several ways to add event listeners. The following concept can also be used using jQuery (and personally what I prefer).
object = document.getElementById("objectName");
$(object).bind('dragstart', eventStartDrag);
$(object).bind('dragover', eventStartDrag);
$(object).bind('drag', eventDragging);
$(object).bind('dragend', eventStopDrag);
And there are jQuery shortcuts such as:
$(object).mousedown(eventMouseDown);
$(object) is the object you want to listen for the event. Not all browsers support event capturing (Internet Explorer doesn't) but all do support event bubbling, so I believe the most compatible code is adding the event listener without jQuery.
object.addEventListener('mousedown', eventStartDrag, false);
According to this post, the preferred way of binding an event listener to a document in jQuery is using .on() rather than .bind(), but I have not tested this yet.
Hope this helps.
I guess that jQuery Draggable and Droppable could help you.
SAMPLE CODE
One more SAMPLE without drag and drop that is more similar to your example with regular checkboxes.
I have a page that lets people assign items to a category and javascript that lets user move as many items as desired from one box on left to one on right and back so that users can preview and fine tune choices (which end up in right box). It might be better if the items could be moved between lists instead of listboxes, but select box, I guess, is good for selecting uponclick. When user is done, I need to post items in right box to php script. However, am having trouble figuring out how to capture all the items in the right list. There is no form in the script so can't get it from document.form. Items are not really selected, they just populate list and I want to get them all. Is there a variable that has the whole list? Script is lengthy so here are functions that do work. Essentially I need a way to write out list of elements in right box at end. Thanks for any suggestions.
function moveToRightOrLeft(side) {
var listLeft = document.getElementById('selectLeft');
var listRight = document.getElementById('selectRight');
if (side == 1) {
if (listLeft.options.length == 0) {
alert('You have already assigned all items to the category');
return false;
} else {
var selectedItem = listLeft.options.selectedIndex;
move(listRight, listLeft.options[selectedItem].value, listLeft.options[selectedItem].text);
listLeft.remove(selectedItem);
if (listLeft.options.length > 0) {
listLeft.options[0].selected = true;
}
}
} else if (side == 2) {
if (listRight.options.length == 0) {
alert('The list is empty');
return false;
} else {
var selectedItem = listRight.options.selectedIndex;
move(listLeft, listRight.options[selectedItem].value, listRight.options[selectedItem].text);
listRight.remove(selectedItem);
if (listRight.options.length > 0) {
listRight.options[0].selected = true;
}
}
}
}
function move(listBoxTo, optionValue, optionDisplayText) {
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
First, I think you have an error in your syntax. To get the value of the selected item of a select box, you would use something like:
var value = listLeft.options[listLeft.selectedIndex].value;
To write out all the options in a particular select box, you should be able to do something like this:
var options = document.getElementById('selectRight').options;
for (i=0; i<options.length(); i++)
document.write("value "+ i +" = "+ options[i].value);
I reworked your code a tiny bit and here is a complete working example:
<html>
<head>
<style type="text/css">
select
{
width:100px;
}
</style>
<script type="text/Javascript">
function moveToRightOrLeft(side)
{
if (side == 1)
{
var list1 = document.getElementById('selectLeft');
var list2 = document.getElementById('selectRight');
}
else
{
var list1 = document.getElementById('selectRight');
var list2 = document.getElementById('selectLeft');
}
if (list1.options.length == 0)
{
alert('The list is empty');
return false;
}
else
{
var selectedItem = list1.options[list1.selectedIndex];
move(list2, selectedItem.value, selectedItem.text);
list1.remove(list1.selectedIndex);
if (list1.options.length > 0)
list1.options[0].selected = true;
}
return true;
}
function move(listBoxTo, optionValue, optionDisplayText)
{
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
function showContents(listBoxID)
{
var options = document.getElementById(listBoxID).options;
for (var i = 0; i < options.length; i++)
alert("Option "+ options[i].value +" = "+ options[i].text);
}
</script>
</head>
<body>
<select id="selectLeft" multiple="multiple">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button onclick="moveToRightOrLeft(2)"><</button>
<button onclick="moveToRightOrLeft(1)">></button>
<select id="selectRight" multiple="multiple">
</select>
<button onclick="showContents('selectRight')">Show Contents</button>
</body>
</html>