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>
Related
I am trying to make a text box that when you type in it, it pulls up suggestions underneath that come from a recordset. For some reason when you type in the field, I only get the first letter. It think it has to do with the json_encode part. When I changed the array to be just text: "Brainpop","Google", etc. it worked fine. Any thoughts? This is the coding I based it off of:
https://www.w3schools.com/howto/howto_js_autocomplete.asp
<script type="application/javascript">
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}</script>
<script>
//now put it into the javascript
var software_list = <?php echo json_encode($types2, JSON_UNESCAPED_SLASHES), "\n"; ?>;
</script>
<?php
$query1 = "SELECT software_name from software";
$result = mysqli_query($sdpc_i, $query1);
$types = array();
while ($row = $result->fetch_assoc()) {
$types[] = '"'.$row['software_name'].'"';
}
$types2 = implode(",",$types);
?>
<div class="autocomplete"><input type="text" name="software_name" id="myInput" class="form-control col-md-8" value="" required></div><script>
autocomplete(document.getElementById("myInput"), software_list);
</script>
</div>
Can anyone tell me what's wrong and how to fix this bit of code...
I am trying to bring up a message and not go to the next page, if the #send_country box has either nothing in it or says "Send From..." (as its the placeholder).
This is the bit of code I am having issues with:
if (country == '0' || country == "Send From...") {
error = 1;
jQuery('.msg').text("Please Select A Country.");
}
I think I have an issue with the OR function as it works without the || country == "Send From...".
<script>
jQuery(document).ready(function(){
jQuery('.submit').click(function() {
var error = 0;
var country = jQuery('#send_country').val();
var countrys = jQuery('#delv_country').val();
var idsa = jQuery('.size').val();
if (country == '0' || country == "Send From...") {
error = 1;
jQuery('.msg').text("Select A Country.");
}
if (countrys == '0') {
error = 1;
jQuery('.msg').text("Select A Country.");
}
if (error) {
return false;
} else {
return true;
}
});
});
</script>
if the #send_country box has either nothing in it or says "Send From..." (as its the placeholder).
The placeholder attribute is different than the value, you couldn't get the placeholder using .val(); instead you should use .prop('placeholder') :
var country_placeholder = jQuery('#send_country').prop('placeholder');
So the condition will be :
if (country == '0' || country_placeholder == "Send From...") {
But like this the condition will always return true since the placeholder will not change if you're filling the field, so i suggest just to check if the value is empty or '0' :
if (country == '0' || country == "") {
Hope this helps.
jQuery('.submit').click(function() {
var error = 0;
var country = jQuery('#send_country option:selected').val();
if (country == '') {
error = 1;
jQuery('.msg').text("Select A Country.");
}
if (error) {
console.log('EROOR');
} else {
console.log('SUBMIT');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select type="text" id='send_country'>
<option value="" disabled selected>Send From...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<button class='submit'>Submit</button>
</form>
<span class='msg'></span>
I have an HTML dropdown list which i'm populating from a database. My question is how can i retrieve the value of a selected item from this dropdown list using AJAX?
My javascript:
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "/display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
The dropdown list in display-product.php:
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">';
while($row1 = $result->fetch_assoc()){
echo '<option value="' . $row1['id'] . '">' . $row1['category'] . '</option>';
}
echo '</select>';
?>
</div>
The div to display the selected item:
<div class="product_directory" id="div1"></div>
I'm not very conversant with AJAX. I tried to access the "str" variable passed to the getData function in my PHP script using "$string = $_GET['q']" but still didn't work. Thanks in advance for the help.
UPDATE: i was able the figure out the source of the problem: I have two functions that populate the select lists from the database. When a user selects an option from the first dropdown(with id="categoriesSelect"), the second one(id = "subcatsSelect") is automatically populated. Here is the code for both functions:
<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>
The code works fine if i manually put in the select list . But using these two functions to pull from the database, nothing is displayed. I call the loadCategories() function like this
<body onload = "loadCategories()">.
The other select box is very similar to this one.
I don't know the specific issue but i know it's coming either from loadCategories() or updateSubCats().
It seems your code is retrieving the value on the select. But it fails on your function.
I tried using that open function Here. But, in my side it didn't work using an slash (/). So, try to remove that and try it.
...
xhr.open("GET", "display-product.php?q="+str, true);
...
EDIT: full working code...
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="div1"></div>
... on display-product.php
echo $_GET['q'];
Try this for the edited part of your question.
And this other to make it work together.
Hope this helps.
You can use a this possible solution with JQuery:
Add the attribute "id" in option tag in php code and remove onChange function:
echo "<select id='mySelect' title='Select one' name='selectcat'>";
Add Jquery File JQuery 1.9.1 and add the javascript HTML tag
Put before close tag body:
$(document).ready( function() {
$('#mySelect').change(function(){
var $selectedOption = $(this).find('option:selected');
var selectedLabel = $selectedOption.text();
var selectedValue = $selectedOption.val();
alert(selectedValue + ' - ' + selectedLabel);
$('.product_directory').html(selectedValue + ' - ' + selectedLabel);
$.ajax({
type:"POST",
url:"display-product.php",
data:selectedValue OR selectedLabel,
success:function(response){
alert('Succes send');
}
})
return false;
});
});
Read in php:
echo $_POST['selectedValue'];
or
echo $_POST['selectedLabel'];
I am terribly failing with an ajax/jquery piece of code I am trying to learn in order to solve a predicament I have.
Below is my ajax:
$('#sessionsDrop').change( function(){
var search_val = $(this).val();
$.post("addstudentsession.php",
{studenttextarea : search_val},
function(data){
if (data.length>0){
$("#studentselect").html(data);
}
});
At the moment I am keeping getting a blank page everytime I load my addstudentsession.php script. This is the only script I am working on so I am not sure if I am suppose to link the ajax to itself. But below is what I am trying to do:
I have a drop down menu below:
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='20'>EWYGC - 10-01-2013 - 09:00</option>
<option value='22'>WDFRK - 11-01-2013 - 10:05</option>
<option value='23'>XJJVS - 12-01-2013 - 10:00</option>
<option value='21'>YANLO - 11-01-2013 - 09:00</option>
<option value='24'>YTMVB - 12-01-2013 - 03:00</option>
</select> </p>
Below I have a Multiple Select box where it displays a list of students that is taking the select assessment from the drop down menu above:
$studentactive = 1;
$currentstudentqry = "
SELECT
ss.SessionId, st.StudentId, st.StudentAlias, st.StudentForename, st.StudentSurname
FROM
Student_Session ss
INNER JOIN
Student st ON ss.StudentId = st.StudentId
WHERE
(ss.SessionId = ? and st.Active = ?)
ORDER BY st.StudentAlias
";
$currentstudentstmt=$mysqli->prepare($currentassessmentqry);
// You only need to call bind_param once
$currentstudentstmt->bind_param("ii",$sessionsdrop, $stuentactive);
// get result and assign variables (prefix with db)
$currentstudentstmt->execute();
$currentstudentstmt->bind_result($dbSessionId,$dbStudentId,$dbStudentAlias,$dbStudentForename.$dbStudentSurname);
$currentstudentstmt->store_result();
$studentnum = $currentstudentstmt->num_rows();
$studentSELECT = '<select name="studenttextarea" id="studentselect" size="6">'.PHP_EOL;
if($studentnum == 0){
$studentSELECT .= "<option disabled='disabled' class='red' value=''>No Students currently in this Assessment</option>";
}else{
while ( $currentstudentstmt->fetch() ) {
$studentSELECT .= sprintf("<option disabled='disabled' value='%s'>%s - %s s</option>", $dbStudentId, $dbStudentAlias, $dbStudentForename, $dbStudentSurname) . PHP_EOL;
}
}
$studentSELECT .= '</select>';
But I have a little problem, I need a way to be able to display the list of students in the select box when the user has selected an option from the drop down menu. The problem with the php code is that the page has to be submitted to find its results.
So that is why I am trying to use ajax to solve this but what am I doing badly wrong?
Try using ajax call as following,
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
XMLHttpRequestObject = false;
}
}
}
$('#sessionsDrop').change( function(){
var search_val = $(this).val();
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST", "addstudentsession.php", true);
XMLHttpRequestObject.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
}
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4
&& XMLHttpRequestObject.status == 200) {
y = XMLHttpRequestObject.responseText;
$("#studentselect").html(y);
}
};
};
XMLHttpRequestObject.send("studenttextarea=" + search_val);
I have a table that includes the taxonomic name of a species. So there are separate columns for each species, domain, kingdom, phylum, etc. I am using a select boxes for each of these classifications, and what I need to happen is when the first one (Domain) is selected, the database is queried to get all the kingdomes where domain is the value of the previous select.
Here's what I have for my PHP in 'search.php':
<select name="domain" id="domain">
<option value="standard">-- Domain --</option>
<?php while($row = mysql_fetch_array($get_domains, MYSQL_NUM))
{
echo "<option value='$row[0]'>$row[0]</option>";
} ?>
</select>
<select name="kingdom" id="kingdom" >
<option value="standard">-- Kingdom --</option>
<?php
$result = array();
$domain = $_POST['domain'];
$get_kingdoms = mysql_query("SELECT DISTINCT sci_kingdom FROM tbl_lifedata WHERE sci_domain = $domain");
while($row = mysql_fetch_array($get_kingdoms, MYSQL_NUM))
{
$result[] = array(
'name' => $row[0]
);
}
echo json_encode($result);
?>
</select>
And this is what I have in my jquery:
$('#domain').change(function() {
$domain = $('#domain option:selected').val();
if ($domain == 'standard') {
$('#kingdom').attr('disabled', 'disabled');
$('.btn-cover').text('Select a Domain:');
} else {
$('#kingdom').removeAttr('disabled', 'disabled');
$('.btn-cover').text('Select a Kingdom:');
}
});
$('#kingdom').change(function() {
$kingdom = $('#kingdom option:selected').val();
if ($kingdom == 'standard') {
$('#domain').removeAttr('disabled', 'disabled');
$('#phylum').attr('disabled', 'disabled');
$('.btn-cover').text('Select a Kingdom:');
} else {
$('#domain').attr('disabled', 'disabled');
$('#phylum').removeAttr('disabled', 'disabled');
$('.btn-cover').text('Select a Phylum:');
$.post("search.php", {
'domain': option
}, function(data) {
var sel = $("#kingdom");
sel.empty();
for (var i = 0; i < data.length; i++) {
sel.append('<option>' + data[i].name + '</option>');
}
}, "json");
}
});
I'm having the most trouble understanding how the .post() function works. I know exactly what I want to do, just not exactly how to do.
My goal:
- obtain the value of the domain select box when it is changed
- use that value in the mysql query to get the relevant kingdoms
- execute the query using jquery and then populate the kingdom select box
Thanks!