Reputation: 243
I need to keep track of what option I have selected 1 thru 5. I can't use the value option as I use that to store the image. So I count the number of options. The code below works great in Firefox, but seems like the script doesn't run under Chrome or Safari. Have not tried IE or edge yet. Any Ideas please? Example at: http://rtpcservices.com/count_options.php
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<span>Click a option!</span>
<select id="selected_image" name="selected_image" onchange="
$('#imageToSwap').attr('src', this.options[this.selectedIndex].value);">
<?php
echo '
<option value="' .$shop_name_pdo . '/images/' . $p_image_1 . ' ">Image 1</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_2 . ' ">Image 2</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_3 . ' ">Image 3</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_4 . ' ">Image 4</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_5 . ' ">Image 5</option>
</select>
';
?>
<script>
$( "option" ).click(function() {
// `this` is the DOM element that was clicked
var index = $( "option" ).index( this );
$( "span" ).text( "Image Selected_option #" + (index+1));
document.getElementById("selected_option").value = index;
});
</script>
Upvotes: 0
Views: 73
Reputation: 78
Change your code to the following code try to change the following line
var index = $( "option" ).index( this );
to
var index = $( "option:selected" ).index( this );
Upvotes: 0
Reputation: 32354
Use a change event
$( "#selected_image" ).change(function() {
var index = $( "option:selected" ).index();
$( "span" ).text( "Image Selected_option #" + (index+1));
$("#selected_option").val(index);
});
$( "#selected_image" ).change(function() {
var index = $( "option:selected" ).index();
$( "span" ).text( "Image Selected_option #" + (index+1));
$("#selected_option").val(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selected_image" name="selected_image">
<option value="' .$shop_name_pdo . '/images/' . $p_image_1 . ' ">Image 1</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_2 . ' ">Image 2</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_3 . ' ">Image 3</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_4 . ' ">Image 4</option>
<option value="' .$shop_name_pdo . '/images/' . $p_image_5 . ' ">Image 5</option>
</select>
<span></span>
<input type="text" id="selected_option">
Upvotes: 2