Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the src of an img tag on radio select

Tags:

html

jquery

I have some HTML code as follows:

<div id="input-option227">
    <div class="radio">
        <label>
            <input type="radio" name="option[227]" value="17" />
            <img src="http://localhost/upload/image/cache/catalog/demo/canon_eos_5d_1-50x50.jpg" alt="black" class="img-thumbnail" />
            black
        </label>
    </div>
    <div class="radio">
        <label>
            <input type="radio" name="option[227]" value="18" />
            <img src="http://localhost/upload/image/cache/catalog/demo/apple_logo-50x50.jpg" alt="green" class="img-thumbnail" />
            green
        </label>
    </div>
</div>

I want to get the img src when I select the radio button means when the radio value is 17 then I want to alert:

http://localhost/upload/image/cache/catalog/demo/canon_eos_5d_1-50x50.jpg

and when the value is 18 then the alert should be:

http://localhost/upload/image/cache/catalog/demo/apple_logo-50x50.jpg

What I have done so far is:

$(document).ready(function() {
    $('input:radio[name="option[227]"]').change(function() {
        if ($(this).val() == '17') {
            alert('type A');
        }
        if ($(this).val() == '18') {
            alert('type B');
        }
    });
}); 

What should I do ?

like image 514
Rohitashv Singhal Avatar asked Dec 07 '25 01:12

Rohitashv Singhal


1 Answers

Please have a look at this code snippet. I used $.closest and $.find to locate img tag associated with radio button.

$(document).ready(function(){
    $('input:radio').change(function() {
        var closestLable = $(this).closest("label");
        var imgTag =  closestLable.find("img.img-thumbnail");
        var src = imgTag.attr("src");
        alert(src);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="input-option227">
                                <div class="radio">
                  <label>
                    <input type="radio" name="option[227]" value="17" />
                    <img src="http://localhost/upload/image/cache/catalog/demo/canon_eos_5d_1-50x50.jpg" alt="black" class="img-thumbnail" /> black                                      </label>
                </div>
                                <div class="radio">
                  <label>
                    <input type="radio" name="option[227]" value="18" />
                    <img src="http://localhost/upload/image/cache/catalog/demo/apple_logo-50x50.jpg" alt="green" class="img-thumbnail" /> green                                      </label>
                </div>
                              </div>
            </div>
like image 159
vijayP Avatar answered Dec 08 '25 15:12

vijayP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!