Search code examples
jqueryselected

jQuery .change selected value preselected


I want to update a cookie (via update.php) and reload the site by transferring the new data (id, value). Value 1 is preselected and using jQuery sets str = 1, not the selected option value e.g. 6.

    $( ".a2d" ).change(function() {
       var prodId = this.id;
       var e = document.getElementById(prodId);
       var str = e.options[e.selectedIndex].value;
       var url = "../update.php?id=" + prodId + "&updateNewValue=" + str;
       $(location).attr('href',url);
    });

HTML:

<select class="a2d" id="2" name="2">
   <option value="0">0</option>
   <option value="1" selected="">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
</select>

By using

var str = $('#' + prodId).options[this.selectedIndex].val();

It seems to work better (as it gets the correct selected value), but an error in firebug says:

Uncaught TypeError: Cannot read property '6' of undefined


Solution

  • $('#' + prodId)
    

    This is a jquery object, not javascript object hence use it like :

    document.getElementById(prodId).options[this.selectedIndex].value;