JQuery - change select list based on other select list

Hi,
I have some shop items that are sometimes available in different options.

Is there a way to alter the drop down list  of shop_qty depending on the value selected from the second list.

For example if a customer selects 8kg option I want them to be able order between 1-18 of them.
If they select the 6kg weight I don't want them to be able to order any quantities as it is out of stock.
Perhaps I could somehow hide the add to cart button?  

<html>
<head>
</head>
<body>

<div class="productdiv_grid">
<div class="shopItemName">Font LinePlus</div>

   
<div class="item_buttons_div_grid">
<div class="curvedbox">Price $44.00</div>
<div class="curvedbox">
         QTY&nbsp;&nbsp;
      <select class="shop_qty" name="qty_grid4" id="qty_grid4" onChange="setValue(this.value);">
		<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>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
      </select>
</div>
		  
<div class="curvedbox styled-select" >Weight</br>
          <select name="spec1_grid4" id="spec1_grid4" onChange="setValue(this.value);">
			<option value="5kg">5kg (Stock:10)</option>
            <option value="6kg">6kg (Stock:0)</option>
            <option value="8kg">8kg (Stock:18)</option>
         </select>
    </div>

<div class="addtocart_div" >
<input class="button green" name="additem" id="addtocart_grid762" value="Add to Cart" type="button" onClick="javascript:AddItem('762',document.getElementById('qty_grid4').value,document.getElementById('spec1_grid4').value,document.getElementById('spec2_grid4').value,'Y')">
</div>


</div>
 
</div>

</body>

Open in new window

sabecsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vishal PatilSoftware EngineerCommented:
Hello Sabecs,

Please try using following code :
<!DOCTYPE html />
<html>
<head>
    <title></title>
    <script type="text/javascript">
        function setValue(txt) {
            debugger;
            var tsttxt = txt.options[txt.selectedIndex].text.split(':')[1].split(')')[0];
            if (tsttxt === "0") {
                var addcartbtn = document.getElementById("addtocart_grid762");
                addcartbtn.style.display = "none";
            }
            else {
                document.getElementById("addtocart_grid762").style.display = "block";
            }

            var selectBox = document.getElementById("qty_grid4");
            while (selectBox.firstChild)
                selectBox.removeChild(selectBox.firstChild)
            for (var i = tsttxt; i >= 1; --i) {
                var option = document.createElement('option');
                option.text = option.value = i;
                selectBox.add(option, 0);
            }
        }
    </script>
</head>
<body> 

<div class="productdiv_grid">
<div class="shopItemName">Font LinePlus</div>

   
<div class="item_buttons_div_grid">
<div class="curvedbox">Price $44.00</div>
<div class="curvedbox">
         QTY&nbsp;&nbsp;
      <select class="shop_qty" name="qty_grid4" id="qty_grid4"> <!-- onChange="setValue(this.value);"-->
		<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>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
      </select>
</div>
		  
<div class="curvedbox styled-select" >Weight</br>
          <select name="spec1_grid4" id="spec1_grid4" onchange="setValue(this);">
			<option value="5kg">5kg (Stock:10)</option>
            <option value="6kg">6kg (Stock:0)</option>
            <option value="8kg">8kg (Stock:18)</option>
         </select>
    </div>

<div class="addtocart_div" >
<input class="button green" name="additem" id="addtocart_grid762" value="Add to Cart" type="button" onClick="javascript:AddItem('762',document.getElementById('qty_grid4').value,document.getElementById('spec1_grid4').value,document.getElementById('spec2_grid4').value,'Y')">
</div>


</div>
 
</div>

</body>
</html>

Open in new window

0
Julian HansenCommented:
You can add the following to your <head></head
The code below hides / shows the add to cart button but you can do whatever you need in the code section depending on your requirements.
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(function() {
  // Bind to the change event on the spec_grid select
  $('#spec1_grid4').change(function() {
    // Add code to do what you need to based on
    // the value in this grid
    // This sample just shows / hides the
    // add to cart button but you can change
    // as needed.
    if ($(this).val() == "6kg") {
      $('#addtocart_grid762').hide();
    }
    else {
      $('#addtocart_grid762').hide();
    }
  });
});
</script>

Open in new window

0
sabecsAuthor Commented:
Thanks for your help, much appreciated.

I need it to work for multiple items on a page, so I can't hard code thinks like addtocart_grid762 & qty_grid4 as these will change.

Can we somehow specify next and previous div to alter?

<!DOCTYPE html />
<html>
<head>
    <title></title>
    <script type="text/javascript">
        function setValue(txt) {
            debugger;
            var tsttxt = txt.options[txt.selectedIndex].text.split(':')[1].split(')')[0];
			
			alert(tsttxt);
			
            if (tsttxt == "0") {
                var addcartbtn = document.getElementById("addtocart_grid762");
                addcartbtn.style.display = "none";
            }
            else {
                addcartbtn.style.display = "block";
            }

            var selectBox = document.getElementById("qty_grid4");
            while (selectBox.firstChild)
                selectBox.removeChild(selectBox.firstChild)
            for (var i = tsttxt; i >= 1; --i) {
                var option = document.createElement('option');
                option.text = option.value = i;
                selectBox.add(option, 0);
            }
        }
    </script>
    
<style type="text/css">

.productdiv_grid{
	float: left;
	width: 233px;
	height:auto;
	min-height:425px;
	background-color: #f3f3f3;
    text-align:center;
	margin-right:3px;
	margin-top:3px;
margin-left:7px;
}

.curvedbox{
	position:relative;
	z-index:400;
	font-size: 12px !important;
	font-weight: bold !important;
	padding: 7px 12px; 
	height:auto;
	min-height:20px;
	cursor:pointer;
	line-height:20px;
	display:inline-block; 
        width:130px;
        margin:5px auto;
	border-radius: 5px;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	text-decoration:none !important;
	text-shadow: 1px 1px 0px #ffe8b2;
	color: green !important;
	border: 1px solid #ccc;
		-moz-box-shadow:
		0px 1px 1px rgba(000,000,000,0.1),
		inset 0px 1px 1px rgba(255,255,255,0.7);
	-webkit-box-shadow:
		0px 1px 1px rgba(000,000,000,0.1),
		inset 0px 1px 1px rgba(255,255,255,0.7);
	behavior:url(/styles/PIE.htc);	
}

.curvedbox select {
	color:red;
	font-weight:normal;
	border: none;
	text-transform: capitalize;
} 

</style>    
    
</head>
<body> 

<div class="productdiv_grid">
<div class="shopItemName">Font LinePlus</div>

   
<div class="item_buttons_div_grid">
<div class="curvedbox">Price $44.00</div>
<div class="curvedbox">
         QTY&nbsp;&nbsp;
      <select class="shop_qty" name="qty_grid4" id="qty_grid4"> <!-- onChange="setValue(this.value);"-->
		<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>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
      </select>
</div>
		  
<div class="curvedbox styled-select" >Weight</br>
          <select name="spec1_grid4" id="spec1_grid4" onchange="setValue(this);">
			<option value="5kg">5kg (Stock:10)</option>
            <option value="6kg">6kg (Stock:0)</option>
            <option value="8kg">8kg (Stock:18)</option>
         </select>
    </div>

<div class="addtocart_div" >
<input class="button green" name="additem" id="addtocart_grid762" value="Add to Cart" type="button" onClick="javascript:AddItem('762',document.getElementById('qty_grid4').value,document.getElementById('spec1_grid4').value,document.getElementById('spec2_grid4').value,'Y')">
</div>


</div><!-- end of item_buttons_div_grid -->
 
</div><!-- end of productdiv_grid -->


<div class="productdiv_grid">
<div class="shopItemName">Blue Dress</div>

   
<div class="item_buttons_div_grid">
<div class="curvedbox">Price $56.00</div>
<div class="curvedbox">
         QTY&nbsp;&nbsp;
      <select class="shop_qty" name="qty_grid5" id="qty_grid5"> <!-- onChange="setValue(this.value);"-->
		<option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>
</div>
		  
<div class="curvedbox styled-select" >Size</br>
          <select name="spec1_grid5" id="spec1_grid5" onchange="setValue(this);">
			<option value="12">12 (Stock:4)</option>
            <option value="14">14 (Stock:4)</option>
            <option value="16">16 (Stock:0)</option>
         </select>
    </div>

<div class="addtocart_div" >
<input class="button green" name="additem" id="addtocart_grid763" value="Add to Cart" type="button" onClick="javascript:AddItem('763',document.getElementById('qty_grid5').value,document.getElementById('spec1_grid5').value,document.getElementById('spec2_grid5').value,'Y')">
</div>


</div><!-- end of item_buttons_div_grid -->
 
</div><!-- end of productdiv_grid -->

<div class="productdiv_grid">
<div class="shopItemName">Sports Drink</div>

   
<div class="item_buttons_div_grid">
<div class="curvedbox">Price $6.00</div>
<div class="curvedbox">
         QTY&nbsp;&nbsp;
      <select class="shop_qty" name="qty_grid6" id="qty_grid6"> <!-- onChange="setValue(this.value);"-->
		<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>
        <option value="6">6</option>
      </select>
</div>
		  
<div class="curvedbox styled-select" >Flavour</br>
          <select name="spec1_grid6" id="spec1_grid6" onchange="setValue(this);">
			<option value="Lemon">Lemon (Stock:6)</option>
            <option value="Cranberry">Cranberry (Stock:24)</option>
            <option value="Lime">Lime (Stock:9)</option>
            <option value="Pineapple ">Pineapple  (Stock:9)</option>
         </select>
    </div>

<div class="addtocart_div" >
<input class="button green" name="additem" id="addtocart_grid878" value="Add to Cart" type="button" onClick="javascript:AddItem('878',document.getElementById('qty_grid6').value,document.getElementById('spec1_grid6').value,document.getElementById('spec2_grid6').value,'Y')">
</div>


</div><!-- end of item_buttons_div_grid -->
 
</div><!-- end of productdiv_grid -->


</body>
</html>

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Julian HansenCommented:
Can we somehow specify next and previous div to alter?

Can you explain what you mean?

To pick up the change event on a select is pretty straightforward as my previous post shows. What you need to decide is how you are going to identify those select boxes. If you want a generic solution then the answer is to give the select's a class name and bind the event to the class. You can then use a parent container (for the two selects) as a means to find the matching quantity drop down. I can provide sample code on how to do this - but need clarification on exactly what it is you are trying to achieve.

I am not clear on your requirements though - if you want to disable the form for 6Kg quantities then why not simply exclude that from the list of options? Or make it so the quantity box shows 0 or Out of Stock.
0
sabecsAuthor Commented:
Thanks Julian, I am more interested in changing the select list for the Qty with the number available than hiding the "Add to Cart" Button.  

Basically, if someone selects an option that is out of stock, they cannot select a quantity to order.
But is they select an option that has say 5 in stock, then the Qty select list will display 1 to 5 only.

I hope that makes sense?
0
Julian HansenCommented:
That is slightly different from what you asked in the original question. It sounds like you want to modify the quantity drop down based on items in stock.

Can you not just do an ajax call back to the server on the product select change and populate the quantity box accordingly.

You could also do this with a javascript array - that stores product and quantity - you can then use that to modify the quantity drop down.

Is there a reason you want to display items that are not in stock - can you not just leave them out of the list when you render the page.

Let us know which of the above solutions is a best fit for what you want to do.
0
sabecsAuthor Commented:
Thanks Julian,
I will probably disable the option of selecting items that aren't in stock, but I would still like to display it in the list so that customers know that we would most likely stock these items in the future.

isn't their a way to re-populate the select list of the previous div using jQuery previous or sibling?

<div class="curvedbox">
         QTY&nbsp;&nbsp;
      <select class="shop_qty" name="qty_grid4" id="qty_grid4"> <!-- onChange="setValue(this.value);"-->
            <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>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
      </select>
</div>
             
<div class="curvedbox styled-select" >Weight</br>
          <select name="spec1_grid4" id="spec1_grid4" onchange="setValue(this);">
                  <option value="5kg">5kg (Stock:10)</option>
            <option value="6kg">6kg (Stock:0)</option>
            <option value="8kg">8kg (Stock:18)</option>
         </select>
    </div>
0
sabecsAuthor Commented:
If  code below obtains the stock count from any item selected
var tsttxt = txt.options[txt.selectedIndex].text.split(':')[1].split(')')[0];

Can't we somehow also get the number from the id "spec1_grid4" which is 4 and then repopulate   "qty_grid4" ? with stock count?
0
Julian HansenCommented:
Of course you can re-populate - there are a number of different ways of doing this

1. Ajax call on select change for the product - call back to the server and receive a stock level
2. When you load the page put meta data into the page to indicate stock levels for each item and adjust the select items accordingly on product change

Probably the two most common approaches. Personally I think the AJAX method is better because if you have multiple users on your site stock levels could change after a page is loaded. With AJAX you get an up-to-date count of what the stock levels are.

Let me know which method you prefer.
0
sabecsAuthor Commented:
Thanks Julian, I  would prefer option 2 as already have the stock levels information on the page?

Also, the stock levels will not change until payment has been confirmed for the order which may be a manual process depending on  payment type.
0
Julian HansenCommented:
Here is some sample code that demonstrates the concept
<!doctype html>
<html>
<head>
<title>Test</title>
<style type="text/css">
</style>
</head>
<body>
<div class="productdiv_grid">
  <div class="shopItemName">Font LinePlus</div>
  <div class="item_buttons_div_grid">
    <div class="curvedbox">Price $44.00</div>
    <div class="curvedbox">QTY&nbsp;&nbsp;
      <select class="shop_qty" name="qty_grid4" id="qty_grid4" onChange="setValue(this.value);">
      </select>
    </div>
    <div class="curvedbox styled-select" >Weight</br>
      <select class="shop_product" name="spec1_grid4" id="spec1_grid4" data-quantity-id="qty_grid4">
        <option value="5kg" data-quantity="10">5kg (Stock:10)</option>
        <option value="6kg" data-quantity="0">6kg (Stock:0)</option>
        <option value="8kg" data-quantity="18">8kg (Stock:18)</option>
      </select>
    </div>
    <div class="addtocart_div" >
      <input class="button green" name="additem" id="addtocart_grid762" value="Add to Cart" type="button">
    </div>
  </div>
  <div class="item_buttons_div_grid">
    <div class="curvedbox">Price $55.00</div>
    <div class="curvedbox">QTY&nbsp;&nbsp;
      <select class="shop_qty" name="qty_grid4" id="qty_grid5" onChange="setValue(this.value);">
      </select>
    </div>
    <div class="curvedbox styled-select" >Weight</br>
      <select class="shop_product" name="spec1_grid4" id="spec1_grid5" data-quantity-id="qty_grid5">
        <option value="5kg" data-quantity="0">15kg (Stock:0)</option>
        <option value="6kg" data-quantity="1">16kg (Stock:1)</option>
        <option value="8kg" data-quantity="6">18kg (Stock:6)</option>
      </select>
    </div>
    <div class="addtocart_div" >
      <input class="button green" name="additem" id="addtocart_grid763" value="Add to Cart" type="button">
    </div>
  </div>
</div>  
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
// FUNCTION USED TO SET STATE OF <select> QUANTITY AND
// ADD TO CART BUTTON
// TAKES A jQuery <select> OBJECT AND A SELECTED <option> 
// AS PARAMETERS
function setOptionList(obj, selected)
{
  // GET THE META DATA QUANTITY AVAILABLE FOR THIS ITEM
  var quantity = selected.data('quantity');

  // GET THE META DATA FOR THE id OF THE QUANTITY <select>
  var quantity_id = '#' + obj.data('quantity-id');

  // CLEAR THE QUANTITY <select>
  $(quantity_id).html('');

  // IF WE HAVE STOCK THEN ENABLE THE ADD TO CART <input> 
  // AND ADD THE QUANTITY <option>'s TO THE QUANTITY <select> 
  if (quantity > 0) {
    // ENABLE ADD TO  CART
    obj.closest('.item_buttons_div_grid').find('.addtocart_div input').prop('disabled',false);
    // ADD <option>'s TO <select>
    for(i = 1; i<= quantity; i++) {
      $(quantity_id).append($('<option/>').val(i).html(i));
    }
  }
  else {
    // DISABLE ADD TO CART
    obj.closest('.item_buttons_div_grid').find('.addtocart_div input').prop('disabled',true);
    // ADD 'Out Of Stock' <option> TO QUANTITY <select>
    $(quantity_id).append($('<option/>').val(0).html('Out of Stock'));
  }
}

$(function() {
  // INITIALISE PRODUCT QUANTITY BOXES 
  $('.shop_product').each(function() {
    // FOR EACH PRODUCT <select> FOUND
    // GET THE SELECTED <option> OR THE FIRST <option>
    var selected = $(this).find('option:selected') || 'none';
    if (selected == 'none') {
      selected = $('option:first-child', $(this));
    }

    // SET THE OPTION LIST ON LOAD
    setOptionList($(this), selected);
  });

  // BIND TO THE CHANGE EVENT ON PRODUCT <select>  
  $('.shop_product').change(function() {
    // FIND THE SELECTED <option>
    var selected = $(this).find('option:selected');

    // CALL setOptionList WITH QUANTITY <select>
    // AND SELECTED PRODUCT <option>
    setOptionList($(this), selected);
  });
});
</script>
</body>
</html>

Open in new window


Sample link here http://www.marcorpsa.com/ee/t726.html
Note I am using the HTML5 data attribute in the <option> and <select> elements.
In the <option> data-quantity stores the stock level for the corresponding product item
For the <select> data-quantity-id refers to the id of the corresponding quantity drop down. For the latter it is possible to find the quantity <select> using a similar approach to the method used to find the add to cart button. It is just easier this way.

The data attribute values are obtained using the jQuery .data() function
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sabecsAuthor Commented:
Thanks Julian, that is fantastic and exactly what I needed. Your help is very much appreciated.
0
Julian HansenCommented:
You are welcome - thanks for the points.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.