Disable Selected options between similar dropdowns - javascript

I have a set of drop down menus (HTML selects) which are populated with the same values from a mysql query. I would like that, as soon as I choose one option from a drop down, that option can't be selected in none of the rest (or appear disabled). Basically, this is what I have:
<form name="test" method="post" action="confirmSelection.php">
<select name="color1" id="color1">
<?php
$sql = "SELECT *
FROM colors
ORDER BY name";
$res = mysql_query($sql);
while( $row = mysql_fetch_array( $res ) )
{
?>
<option value="<?php echo ($row["id"]) ?>"> <?php echo( $row["name"] )?></option>
<?php
}
?>
</select>
<select name="color2" id="color2">
<?php
$sql = "SELECT *
FROM colors
ORDER BY name";
$res = mysql_query($sql);
while( $row = mysql_fetch_array( $res ) )
{
?>
<option value="<?php echo ($row["id"]) ?>"> <?php echo( $row["name"] )?></option>
<?php
}
?>
</select>
<select name="color3" id="color3">
<?php
$sql = "SELECT *
FROM colors
ORDER BY name";
$res = mysql_query($sql);
while( $row = mysql_fetch_array( $res ) )
{
?>
<option value="<?php echo ($row["id"]) ?>"> <?php echo( $row["name"] )?></option>
<?php
}
?>
</select>
Any idea? I guess it must be simple but I don't really know how to look for it (it was really hard for me to find a proper title for this consult...).
Thanks a lot in advance.
EDIT:
ajax code:
function showData(dataType)
{
var capa=document.getElementById("content");
var ajax=nuevoAjax();
capa.innerHTML="";
ajax.open("POST", "test.php", true);
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.send("d="+dataType);
ajax.onreadystatechange=function()
{
if (ajax.readyState==4)
{
capa.innerHTML=ajax.responseText;
}
}
}
In test.php is where I have the 4, 5 and 6 selectors in the same way I explained the 3. I also have this:
....
$dataType=$_POST['d'];
if($dataType=='1')
{
//4 selectors
}elseif($dataType == '2')
{
//5 selectors
}elseif($dataType == '3')
{
//6 selectors
}
The div is updating properly and showing the correct layout (4,5 or 6 selects) but the code you gave me is not working. I´ve tried including the javascript in test.php and in landscape.php. No luck :(.

Leave the PHP aside for this. You'll have a pure HTML page, once the PHP has done its thing, right? So the javascript simply has to interact with the DOM itself, as normal.
First, I wanted to store selected options for all the select elements, in an array. Doing this allows me to select an option in the first and the second color selectors, and have them BOTH disabled in the third.
Then, simply iterate over all the connected selects (I've connected them via a matching class), and within that iterate over all the selected options, and disable them as appropriate.
Sounds simple, but it was a bit of a challenge. More of a challenge (but not much more) might be to allow multi-selects.
Hope it helps, let me know if it needs a change.
// This array will be used to store the current selection of
// each connected select. They are connected by a class attr.
var selectedOption = new Array($(".colorSelector").length);
/*******
* Any time any select is changed, we update the selectedOption
* array to include the new selection. Note that the array is
* the same length as the number of selects, and that we're
* setting the value to the position in that array that relates
* to the position of the element itself. By this, I mean that
* selectedOption[0] contains the value of select[0],
* selectedOption[4] contains the value of select[4],
* and so on.
*******/
$("body").on("change",".colorSelector", function() {
// First, get the value of the selected option.
selectedOption[$(this).index()] = $(this).val();
/***
* Now, we iterate over every connected select element.
* we want to disable all values that are selected in
* all other connected selects -- those values we've stored
* in the selectedOption array. As long as the value is
* not blank, or the default '...', or the current element,
* we disable that option.
***/
$(".colorSelector").each(function() {
// First, re-enable all options.
$(this).children("option").removeAttr("disabled");
// Iterate over the selectedOption list
for (i = 0; i < selectedOption.length; i++) {
if (selectedOption[i] != "" && selectedOption[i] != "..." && i != $(this).index()) {
// Disable any option that isn't default, or
// ignore if the current selectedOption points to
// this select.
$(this).children("option[value='" + selectedOption[i] + "']").attr("disabled", "disabled");
}
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="color1" id="color1" class="colorSelector">
<option>...</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="indigo">Indigo</option>
<option value="violet">Violet</option>
</select>
<select name="color2" id="color0" class="colorSelector">
<option>...</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="indigo">Indigo</option>
<option value="violet">Violet</option>
</select>
<select name="color3" id="color3" class="colorSelector">
<option>...</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="indigo">Indigo</option>
<option value="violet">Violet</option>
</select>
Also, this is up as a fiddle, just in case.
EDIT: You mention that this doesn't work when the select is populated by AJAX. You're exactly right, it didn't work as written. The reason is, when an element is loaded after the page has loaded, it doesn't automatically connect to the page's current listeners. Instead, I've changed where the listener is attached in the above code. Instead of listening like $(".colorSelector").on("change"...), I've changed it to $("body").on("change", ".colorSelector", function(){...}); -- note that the listener now gets attached to the body. Doing this causes any element with the .colorSelector class to trigger, whether it was there initially or added later. Hope this helps!

Related

how to add a link on single option in select tag

hello I am trying to create a category select dropdown which consists of some data coming from database I have created a page named addcategory.php and I am trying to add a in the select tag something like "add new category" I tried several methods like onchange function in javascript but it gets applied to the whole select menu I only want to add a link to the last option of the select tag below I am attaching the code which I am using.
<select class="w-100" id="categoryselect" name="selectcat" required>
<option value="" disabled selected>Select Category</option>
<?php
$sql="SELECT * FROM categories";
$result=mysqli_query($conn, $sql);
while($row=mysqli_fetch_array($result))
{
echo '<option value="'.$row["cat_id"].'">'.$row["name"].'</option>';
}
?>
<option value="categories" onClick="window.location = 'addcategory.php'">Add New Category</option>
</select>
Bind the event handler to select tag instead of bind the event into options tag.
The onchange event occurs when the value of an element has been changed.
<select class="w-100" id="categoryselect" name="selectcat" onChange="if(this.value=='categories') window.location='addcategories.php'">
<option value="" disabled selected>Select Category</option>
<?php
$sql="SELECT * FROM categories";
$result=mysqli_query($conn, $sql);
while($row=mysqli_fetch_array($result))
{
echo '<option value="'.$row["cat_id"].'">'.$row["name"].'</option>';
}
?>
<option value="categories">Add New Category</option>
</select>

Drop-down quantity menu in a shopping cart

UPDATE: In case anyone is reading this please ignore the fragment when I talk about the "dynamic max quantity" as it doesn't make any sense. I am actually not adding new quantity but updating it with a new number chosen from the drop-down menu, so instead of $i <= $dynamic_max it should be $i = 50, therefore this code: $static_max = 50;
$dynamic_max = $static_max - $value['item_quantity']; is obsolete. It is not directly relevant to the problem I had and solution given but it makes the code clearer.
END OF THE UPDATE
On the page where a product is listed you chose the quantity using a drop-down menu.
You click "Add to basket" and the product is sent to the next page (basket.php) where you are again given an option to change the quantity using a drop-down menu.
My problem is that when you click the drop-down menu you see the currently chosen amount at the very top of the list of numbers and then the range of numbers by which you can update the quantity.
The range of numbers by which you update the quantity is dynamic, meaning that it depends on the quantity chosen at the first step. The overall available quantity is 50, so when you chose 40, on the next page (basket.php) you will see the range between 0 and 10 only (where 0 is used as "remove") with the currently chosen number on top of the list.
I do not want the currently chosen quantity of product be shown on top of the drop-down menu, I just want the range of available numbers by which you update the quantity.
Can I do it in PHP or do I need to manipulate the DOM with JavaScript?
I'm posting here my code without other parts of the table in which added products are displayed (name of the product, the total etc.), it's only <select> tags.
What I have for now is two blocks of <option> tags, one is for the currently chosen quantity and the other is rendered with a for loop to display the range of possible numbers by which you amend the quantity.
I have been trying to use only one block of <option> tags and an ' if ' statement but have run several times into infinite loops, so for now the below is the only "working" version.
<select>
<?php
// Quantity added to the basket:
if (isset($value['item_quantity'])) {
?>
<option value="<?php echo $value['item_quantity']; ?>"><?php echo $value['item_quantity']; ?></option>
<?php
}
?>
<?php
// Quantity option minus what has been already added to the basket:
$static_max = 50;
$dynamic_max = $static_max - $value['item_quantity'];
for ($i = 0; $i <= $dynamic_max; $i++) {
?>
<option value="<?php echo $i; ?>"><?php echo $i ;?></option>
You can simply hide that option from select box when ever the select-box gets open and again when it is close show the default value .
Demo Code :
<select>
<!--hidden first option -->
<option value="10" selected="selected" hidden>10</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Using jquery :
$(document).ready(function() {
//getting first optino
var first = $('#myselect').find('option').first();
//when activated
$('#myselect').on('focus', function(e) {
first.hide(); //hide the first option
}).on('blur', function(e) {
//if value select is equal show the first option
if ($(this).val() == first.val()) {
//showing the same
first.show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myselect">
<option value="10" selected="selected">10</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Thanks for your help, Swati, much appreciated. No JavaScript necessary, though, just plain HTML. All I had to do was what you had done: add the global attribute "hidden" to the "option" tag:
<option value="<?php echo $value['item_quantity']; ?>" hidden><?php echo $value['item_quantity']; ?>

Change content based on a drop down selection from a mysql database

I have a form of drop down boxes populated with values from a mysql database (Computer Part Models). My goal is to produce the rest of the values (The part's specs) from the database below each drop down box based on the value that was selected.
Essentially what I think I think I need is some sort of div refresh for each time a new item has been selected.
I have tried different functions triggered by 'onchange' within the select tag but nothing has come up working.
Let me know if anymore code would be needed for context.
HTML & PHP for one drop down
<form id="parts">
<fieldset>
<legend>Choose your parts</legend>
Any parts marked with * are required<br/><br/>
<label for="CPU">CPU*</label><br/>
<?php
$cresult = $mysqli->query("SELECT * FROM pCpu ORDER BY cModel asc");
?>
<select id="CPU" name="CPU">
<option value="" disabled selected>Select your Part</option>
<?php
while ($rows = $cresult->fetch_assoc()) {
$cmodel = $rows['cModel'];
echo "<option value='$cmodel'>$cmodel</option>";
$cid = $rows['ID'];
}
?>
</select>
<br/>
<?php
$res = $mysqli->query("SELECT cSocket FROM pCpu WHERE ID = '$cid'");
while($rows = $res->fetch_assoc()) {
$csocket = $rows['cSocket'];
echo "CPU Socket: $csocket<br/>";
}
?>
<br/><br/>
What would be the best way of tackling this?
Thanks in advance!
There's two parts in this answer :
First if you want to update a part of your page with change event on the select
function myUpdateFunc()
{
var mySelected = $("#CPU").find("option:selected").val();
$('#divResults').html ('selected value :' + mySelected)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="parts">
<fieldset>
<legend>Choose your parts</legend>
Any parts marked with * are required<br/><br/>
<label for="CPU">CPU*</label><br/>
<select id="CPU" name="CPU" onchange="myUpdateFunc()">
<option value="" disabled selected>Select your Part</option>
<option value="1">value 1</option>
<option value="2">value 2</option>
</select>
<br/>
<div id="divResults"/>
<br/><br/>
Next :
If you want to query a database you can check many tutorials on this. I can help you with this as well

Using one onchange event for multiple dropdow list which are listed among each other

I have created a dynamic dropdown list and the first <select name="club" id="club"> dropdown list will show the results of the mysql query below.
The second <select name="player" id="player"> will be filled by the result of the query which is used in the ajax.php based on the id of the selection in the first
I will use this principal to select a player from a club.
For the selection of one club and player this is working fine, but how can I extend this small piece of code to use this for selecting for example 10 players.
So in this case I have created 10 select boxes among each other which I would prefer to use this small piece of code instead of copying this code 10 times.
$strQueryClubs = "SELECT ec.id, ec.name
FROM club ec, season ss
WHERE ec.season_id = ss.id
AND ss.status = 1 /* Active season*/
ORDER BY ec.name asc";
$resultQueryClubs = mysql_query ($strQueryClubs);
$numQueryClubs = mysql_numrows ($resultQueryClubs);
$arrQueryClubs = $objDB->fetch_array($strQueryClubs);
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#club').on('change',function(){
var clubID = $(this).val();
if(clubID){
$.ajax({
type:'POST',
url:'ajax.php',
data:'id='+clubID,
success:function(html){
$('#player').html(html);
}
});
}else{
$('#player').html('<option value="">First select a club</option>');
}
});
});
</script>
<!-- language: lang-html -->
<select name="club" id="club">
<option value="" disabled="disabled">Select club</option>
<?php
if ($numQueryClubs > 0)
{
for ($i=0;$i<$numQueryClubs;$i++)
{
echo "<option value=".$arrQueryClubs[$i]['id'].">".$arrQueryClubs[$i]['name']."</option>";
}
}
else
{
echo '<option value="">Club is not available</option>';
}
?>
</select>
<select name="player" id="player">
<option value="" disabled="disabled">Select player</option>
</select>
<select name="club" id="club">
<option value="" disabled="disabled">Select club</option>
<?php
if ($numQueryClubs > 0)
{
for ($i=0;$i<$numQueryClubs;$i++)
{
echo "<option value=".$arrQueryClubs[$i]['id'].">".$arrQueryClubs[$i]['name']."</option>";
}
}
else
{
echo '<option value="">Club is not available</option>';
}
?>
</select>
<select name="player" id="player">
<option value="" disabled="disabled">Select player</option>
</select>
As Rasclatt mention in comment,listen event for class not id
As your requeriment of selecting 11 players, don't use 11 dropdowns.
I will suggest use multiple select by multiple property in select or any other plugins to avoid select perticular player twice.
Otherwise you need to refresh follwing dropdown to remove previously selected player

No option in a dynamic dependant drop-down list after form submission

So, I have a form which includes two drop-down lists: id="dd-1" & id="dd-2".
The id="dd-2" options created from the database based on the id="dd-1" selection; I am using the onChange=getChildOf(this.value) in id="dd-1" to do that.
When the user selects an option in id="dd-1" I run an ajax function which passes the value of id="dd-1" to another PHP page where it runs a MySqli query and then updates the id="dd-2".
Up to here, everything is fine.
What I need is:
Remember the user selection in id="dd-1". DONE
Get the id="dd-2" options based on the submitted value of the id="dd-1". not done
After the form submission the id="dd-2" shows no options at all. So, I have to change the selection in id="dd-1" again so the ajax getChildOf(val) function gets fired!
So, I need your help please in getting #2 done.
FYI:
The id="dd-1" select drop-down list looks smothing like:
<select id="dd-1" name="dd-1" onChange="getChildOf(this.value)">
<option value="1" <?php if(isset($_POST['dd-1'])&&$_POST['dd-1']=='1'){echo 'selected';}?> >Option 1</option>
<option value="2" <?php if(isset($_POST['dd-1'])&&$_POST['dd-1']=='2'){echo 'selected';}?> >Option 2</option>
<option value="3" <?php if(isset($_POST['dd-1'])&&$_POST['dd-1']=='3'){echo 'selected';}?> >Option 3</option>
</select>
The id="dd-2" select drop-down list looks smothing like:
<select id="dd-2" name="dd-2"></select>
The ajax function:
function getChildOf(val)
{
$.ajax({
type:"POST",
url:"get_dd2_options.php",
data: 'parentid='+val,
success: function(data){
$("#dd-2").html(data);
}
});
}
The get_dd2_options.php page looks smothing like:
<html>
<option value="-1">Please Select</option>
<?php
include_once('config.php');
// list all children
$q = mysqli_query($link, "SELECT * FROM table WHERE id = '".$_POST['parentid']."'");
while($r = mysqli_fetch_assoc($q))
{
$id = $r['id'];
$name = $r['name'];
?> <option value="<?=$id;?>" <?php if(isset($_POST['dd-2'])&&$_POST['dd-2']==$id){echo 'selected';}?> ><?=$name;?></option> <?php
}
?>
You have two options, I don't know which would be best since I'm not looking at the full code base.
Option 1: After post when you check for dd1 to be set you add another check for dd2 in php.
<?php
if (isset($_POST['dd-1']) {
/* populate dd-2 based on dd-1 value*/
}
?>
Option 2: Add the logic to populate dd2 to page load.

Categories