Using JQuery to populate select options (form fields)

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Using JQuery to populate select options (form fields)

andrew.nevins2
Hi,

I'm trying to get JQuery to grab 'data-quantity' attributes from my option tags and display their values from 1 to that value (integer), in each option.

E.g

<option data-quantity="20">Hair style 1</option>

I want to output <option>1</option><option>2</option> ... </option>20</option>. These will represent my quantity of that item, for an e-commerce basket module.

I want the quantity options to output on-click of the option (e.g Hair Style 1).

Here's my HTML code:

  <form method="post" action="/basket.html" >
    <input type="hidden" name="pid" value="1200" />
    <input type="hidden" name="action" value="add" id="action" />
    <label for="quantity">Quantity</label>
    <select id="quantity" name="quan">

     <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>

      <p><label for="prodopt" style="clear: both">Choose</label>

      <select name="optionid" id="prodopt" style="width: auto">
        <option data-quantity="10" value="1147">test - test, test (+ £1.00)</option><option data-quantity="5" value="1149">test2 -  </option>
      </select></p>

    <div class="bottom">
      <input type="submit" class="actionbtn" value="Buy now" />
    </div>
  </form>

Here's my Javascript / Jquery:

$(document).ready(function(){
  setupDynamicOptionQuantities();
});

function setupDynamicOptionQuantities(){

  $('#prodopt').select(function(e) {

//to test if is getting in here
console.log(6/2)
 
    //need to loop for each option, to grab the data quantity
    var quantity = $('option').data('quantity').value();
   
    i = 1;
    //trying to loop through quantities, from 1 to the number set in the data-quantity value
    for (i = 1; i <= quantity; i++){
      //adding option tags
      $('select.#quantity').add('<option class="quantity" value="'+i+'"></option>');
      //adding values within the options
      $('option.quantity').append(i);
    }
  });

}