HenryW
HenryW

Reputation: 3761

append extra text to select options

After investigating several methods to manipulate select menu options and cant get my head around the correct way , i try it here.

I have the following fiddle representing partial working code:

jsFiddle

Currently if re-select an option, it duplicates the text, but beside that unwanted effect , i actual want all options directly replaced.

The default code i use:

//START Get the stockdata

$stock_array = array();
$products_stock_query=tep_db_query("SELECT *
                                  FROM " . TABLE_PRODUCTS_STOCK . " 
                                  WHERE products_id=" . (int)$HTTP_GET_VARS['products_id'] ." 
                                  ORDER BY products_stock_attributes");

while($products_stock_values=tep_db_fetch_array($products_stock_query)) {
$str = $products_stock_values['products_stock_attributes'];
$str = substr( $str, ( $pos = strpos( $str, '-' ) ) === false ? 0 : $pos + 1 );
echo '<div class="stockdata" valuestock="'.$products_stock_values['products_stock_quantity'].'" valueid="'.$str.'"></div>';
}
?>

<script>

$('option').each(function () {
    $(this).data('txt', $(this).text());

});
$('select').change(function () {
var str = "";
$( "select option:selected" ).each(function() {
 str += this.text;
    $('option', this).each(function () {
        $(this).text($(this).data('txt'));
    });
    });
    var myCheck = $("body").find("div[valueid=" + $(this).find('option:selected').attr('value') + "]").attr("valuestock");
    if (myCheck === '0'){
    //do nothing
    }else{
   // $(this).find('option:selected').text($(this).find('option:selected').attr('value'));
    $(this).find('option:selected').text(str + ' (' +  $("body").find("div[valueid=" + $(this).find('option:selected').attr('value') + "]").attr("valuestock")+') <?php echo IN_STOCK_ATT; ?>');
}
}).trigger( "change" );

</script>

Upvotes: 0

Views: 190

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

Could be what you are looking for:

DEMO

$('select').find('option').each(function () {
    var numInStock = $("body").find("div[valueid=" + this.value + "]").attr("valuestock");
    if (numInStock) {
        $(this).text($(this).text() + '(' + numInStock + ') In Stock');
    } else {
        $(this).text($(this).text() + ' - Out of Stock');
    }
});

Upvotes: 1

Related Questions