se_puede_dev
se_puede_dev

Reputation: 595

How can I cycle through HTML select <option> values on click?

In a calendar app, I have a simple select that has option tag with values 0-11 for the corresponding months. I can cycle through the months one-way (from Dec to Jan), but I can't get it to work going the other way. It only shows Feb and Dec.

Here's a jsfiddle showing what I've already done.

Here's the HTML:

<select id="MonthName" class="form-control">
    <option value="0">January</option>
    <option value="1">February</option>
    <option value="2">March</option>
    <option value="3">April</option>
    <option value="4">May</option>
    <!-- etc, through 11 -->
</select>

<!-- 'Buttons' -->
<span class="chevron chevronLeft floatLeft">◀</span>
<span class="theMonth">Month</span>
<span class="chevron chevronRight floatRight">▶</span>

Here's the jQuery:

$('.chevron').on('click', function() {
  // This if works perfectly, and will reset to 11 once the selectedMonth is 0
  if ($(this).hasClass('chevronLeft')) {
    var selectedMonth = $('#MonthName').val();
    (selectedMonth != 0) 
      ? $('#MonthName').val(selectedMonth - 1).trigger('change')
      : $('#MonthName').val(11).trigger('change');
  }

  else {
    // This doesn't work, I tried declaring the variable locally, 
    // different less/greater than expressions, but nothing works
    var selectedMonth = $('#MonthName').val();
    (selectedMonth !== 11)
      ? $('#MonthName').val(selectedMonth + 1).trigger('change')
      : $('#MonthName').val(0).trigger('change');
  }
});

$('#MonthName').on('change', function() {
   var monthText = 
    $('#MonthName option:selected').text();
    $('.theMonth').text(monthText);
});

Upvotes: 0

Views: 1000

Answers (3)

Tilt
Tilt

Reputation: 677

Please note that Feb and Dec correspond to 1 and 11, so you are not adding numeric values but concatenating strings.

For your reference, here's a question may suit your problem: How to make an addition instead of a concatenation

As a side note, when I was attending the primary school my teacher used to say:

"You cannot add apples and pears."

Well, in javascript you can, because it is weakly typed.

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33880

That's because you are concatenating an int to and a string.

Doing for example '1' + 1 will equal 11 and not 2. Parse your value before the addition :

$('#MonthName').val(parseInt(selectedMonth) + 1)

Fiddle : http://jsfiddle.net/mtJRn/21/

Upvotes: 0

Barmar
Barmar

Reputation: 782489

Change:

var selectedMonth = $('#MonthName').val();

to:

var selectedMonth = parseInt($('#MonthName').val(), 10);

selectedMonth + 1 was doing string concatenation instead of integer addition because selectedMonth was a string.

FIDDLE

I also suggest you specify the width of theMonth -- it's difficult clicking on the right arrow because it keeps moving as the month changes.

Upvotes: 2

Related Questions