Drop-down quantity menu in a shopping cart - javascript

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']; ?>

Related

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

Disable Selected options between similar dropdowns

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!

set selected value of <select> into what I choose lat time before submitting the form

Here's the process I want to realize:
1.on index page, select one option from the list of items;
2.submit form,directing to the index page ;
3.select label showing the default value which equals what I chose in step 1.
e.g.
<html>
<select>
<option value="1">1<option/>
<option value="2">2<option/>
<option value="3">3<option/>
</select>
</html>
On index page if I chose 1 ,and submit it and the page is submitted to itself(the index page).Now,on the index page, <option value="1">1<option/> is selected by default.
I don't know which correct direction I should go and I haven't found any solutions from the Internet yet.Anybody has any ideas??
Thanks a lot!
Using PHP function and javascript onchange:
<html>
<?php
if (isset($_POST["myselect"])) {
$myselect = $_POST["myselect"];
}
else {
$myselect = 1;
}
function isselected(A,B) {
if ($A == $B){
return "selected";
}
else{
return false;
}
}
?>
<form action="index.php" method="post">
<select name="myselect" onchange="this.form.submit();">
<option value="1" <?php echo isselected(1,$myselect) ?> >1<option/>
<option value="2" <?php echo isselected(2,$myselect) ?> >2<option/>
<option value="3" <?php echo isselected(3,$myselect) ?> >3<option/>
</select>
</form>
</html>
1st : Name attribute is must for form elements .otherwise element value would not passed to server.
2nd : Check the post value and add the selected attribute for that option like below .
<select name="select1">
<option value="">Select</option>
<option value="1" <?php echo (isset($_POST['select1']) && $_POST['select1']==1 )? 'selected':''; ?>>1</option>
<option value="2" <?php echo (isset($_POST['select1']) && $_POST['select1']==2 )? 'selected':''; ?>>2</option>
<option value="3" <?php echo (isset($_POST['select1']) && $_POST['select1']==3 )? 'selected':''; ?>>3</option>
</select>
coudn't understand your question quite well but..If you want to select any other value by default, once the page comes back to the index page, you will have to send the selected value back to the index page.
<html>
<select>
<option value="1">1<option/>
<option value="2" selected="selected">2<option/>
<option value="3">3<option/>
</select>
</html>
The above would select option 2, so you just have to set it accordingly.

Update/Edit a form, so that it loads with selected option-values of SELECT from sql table

Here, I have already submitted my form values in sql table, with a multiple select, where I serialized selected values of <options> & inserted in SQL column : fldR.
Now, I am trying to UPDATE this form info, and trying to load this form.php, with fetched values from SQL table. I want to populate the MULTIPLE select, with fetched - selected option values.
PHP:
$data = mysqli_fetch_object($result);
$selected_values = unserialize($data->fldR);
Now what to do ?
HTML / PHP:
<select name="rtype[]" id="rtype" class="myselect" multiple="multiple" style="height:6em">
<option value="hr">H1</option>
<option value="fr">F1</option>
<option value="rnr">R1</option>
</select>
Any creative ideas how this can be done?
We can use in_array() to check if the value is in array or not, if yes execute certain code.
in_array() can accepts two arguments, first argument is the value you need to check and second parameter is array to be checked.
Now update your PHP/HTML code as below to select the values in SELECT box by default from databases. Like this,
<select name="rtype[]" id="rtype" class="myselect" multiple="multiple" style="height:6em">
<option value="hr" <?php if(in_array('hr',$selected_values)) { ?> selected="selected" <?php } ?>>H1</option>
<option value="fr" <?php if(in_array('fr',$selected_values)) { ?> selected="selected" <?php } ?>>F1</option>
<option value="rnr" <?php if(in_array('rnr',$selected_values)) { ?> selected="selected" <?php } ?>>R1</option>
</select>
http://php.net/manual/en/function.in-array.php

to change selected value in combobox2 based on php variable as id of combobox1(need to do inside a loop)

I am working with a code in php. I planned to change a combobox2 selected value based on value selected in combobox1, but i need to do this inside a loop. that is, these two combo boxes are inside a loop that need to execute three times. so, totally six combo boxes will be displayed. I dont know how to explain my question exactly, but i am sure while looking my code what i worked will explain you clearly.
my code what i have tried is not giving me the output i want.
briefly, consider 3 rows of combo boxes, i need to change the combobox2 value in first row based on selection of combobox1 in that row and so on.
Here is the code what i tried.
<?php
for($i=1;$i<=3;$i++) {
echo <<< EOT //combobox1
<td><select name="$i" id=$i onChange="change1()">
<option selected="true" value="" style="display:none;">--Select--</option>
<option value="S">S</option>
<option value="A">A</option>
<option value="U">U</option>
</select></td>
EOT;
$ia=$i."a";
echo <<< EOT //combobox2
<td><select name="$ia" id=$ia>
<option selected="true" value="" style="display:none;">--Select--</option>
<option value="PASS">PASS</option>
<option value="RA">RA</option>
<option value="AB">AB</option>
</select></td></tr>
EOT;
?>
<script type=text/javascript>
function change1(){
if (document.getElementById(<?php $i ?>).value !="U") {
document.getElementById(<?php $ia?>).value="PASS";
}
else{
document.getElementById(<?php $ia?>).value="";
}
}
</script>
<?php }?>
actually i am not getting any error ... i assigned $i as id to combobox1 that is 1 for first row, 2 for second row and 3 for third row comboboxes.. but i tried printing like alert(<?php echo $i ?>); inside function change1 but it displays only '3' all the time ,that is last assigned value.. that was the problem

Categories