Jonas Dulay Jonas Dulay - 7 months ago 24
PHP Question

Change Image and description using select

Good morning guys, I am in rush right now. I need help from you guys.

I will proceed to my problem. I want to change my image and description based on the selected value in my field. I have done it but the problem is that I can only use the .val() for description and image.

I'm in the test stage right now, later after I've done the jQuery
I will get the values from the database
Here is my Javascript:

<script>
var base_url = "<?php echo base_url();?>";
$(document).ready(function() {
$("#field_6").change(function() {
$('#description').html($(this).val());
$('#image').attr("src", base_url + "img/" + $(this).val());
}).change();
});
</script>


Here is my HTML code:

<select class="form-control" id="field_6" name="field_6">
<option value="1.jpg">Online Portal for FGC</option>
<option value="2.png">Restaurant Management for Wit Cafe</option>
<option value="3.jpg">Hotel Reservation for TWIECO</option>
</select>
<img src="<?php echo base_url()?>img/1.jpg" id="image" class="img-responsive" style="height:300px;width:100%;" name="myImage" /><br>
<label class="form_field">Title Description: <span id="description"></span>?</label>


The output right now is like this:

I got the image

and then ex.(1.jpg)

My problem is that it will not be good if both image name and description will be the same for example the image name will be The Online portal for FGC.jpg
and the description will be like that too.

Anyone here can help me please. Thank you in advance

Answer

Here, was tired of talking in comments. your change is on the select box, so you can't get the data attributes of the options without finding them, needed to add that 'find option selected' section.

<script>
var base_url = "test.com/";
$(document).ready(function() {
    $("#field_6").change(function() {
        $('#description').html($(this).find('option:selected').attr('data-description'));
        $('#image').attr("src", base_url + "img/" + $(this).find('option:selected').attr('data-img'));
    });
});
</script>

<select class="form-control" id="field_6" name="field_6">
   <option data-description="my description" data-img="test.com/image.jpg" value="1.jpg">Online Portal for FGC</option>  
   <option data-description="my description2" data-img="test.com/image2.jpg" value="2.png">Restaurant Management for Wit Cafe</option>  
   <option data-description="my description3" data-img="test.com/image3.jpg" value="3.jpg">Hotel Reservation for TWIECO</option>  
</select>
<img src="test.com/img/1.jpg" id="image" class="img-responsive" style="height:300px;width:100%;" name="myImage" /><br>
<label class="form_field">Title Description:  <span id="description"></span>?</label>