Question

I have the following code which I have pieced together from posts on here, and its working so far...

<label>Number of Colours</label>
<select id="main-select">
    <option value="1">1 Colour</option>
    <option value="2">2 Colours</option>
    <option value="3">3 Colours</option>
    <option value="4">4 Colours</option>
</select>

<div class="colour-option" id="colour1">
<label>1st Colour</label>
<select>
    <option value="colour1">Colour One</option>
    <option value="colour2">Colour Two</option>
    <option value="colour3">Colour Three</option>
</select>
</div>

<div class="colour-option" id="colour2">
<label>2nd Colour</label>
<select>
    <option value="colour1">Colour One</option>
    <option value="colour2">Colour Two</option>
    <option value="colour3">Colour Three</option>
</select>
</div>

<div class="colour-option" id="colour3">
<label>3rd Colour</label>
<select>
    <option value="colour1">Colour One</option>
    <option value="colour2">Colour Two</option>
    <option value="colour3">Colour Three</option>
</select>
</div>

<div class="colour-option" id="colour4">
<label>4th Colour</label>
<select>
    <option value="colour1">Colour One</option>
    <option value="colour2">Colour Two</option>
    <option value="colour3">Colour Three</option>
</select>
</div>

Together with the following jQuery...

var showDiv = function (colour) {
$('.colour-option').hide();
$('.colour-option:lt(' + colour + ')').show();
};

$('#main-select').change(function () {
showDiv($(this).val());
}).change();

You can see it in action here: http://jsfiddle.net/UWUYN/5/ and thats exactly how I want it to work, however, my #main-select is generated for me, and as such the values cannot simply be, 1,2,3,4. They form part of a Shopify cart and the values my #main-select is outputting is "1 Ink Pad", "2 Ink Pads", "3 Ink Pads" & "4 Ink Pads". Is there a simple way to edit the JS to take this into account?

Était-ce utile?

La solution

You could just use parseInt(), if the format of the values are going to be like that:

showDiv(parseInt(this.value, 10));

This will get only the integer part from the value, e.g 1 from 1 Ink Pad.

jsFiddle here

Autres conseils

First, just a recommendation, IMO, adding and removing a class that determines hidden is better than using .hide and .show

That aside. You could use the selects selectedIndex or the options index property rather than it's value.

var showDiv = function (colour) {
  $('.colour-option').hide();
  $('.colour-option:lt(' + colour + ')').show();
};

$('#main-select').change(function () {
  showDiv($(this).prop('selectedIndex') + 1);
}).change();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top