2017-01-02 83 views
0

我有一個複選框,其上有一個圖像替換。我想要做的是點擊複選框並獲取圖像的src屬性值並將其放置在textarea中。如何在複選框單擊後獲取src屬性值?

HTML

<div class="thumbnail"> 
    <input type="checkbox" name="thing_5" value="valuable" id="thing_5"> 
    <label for="thing_5"> 
    <img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/a/ac/U.S._Marines_in_Operation_Allen_Brook_(Vietnam_War)_001.jpg"> 
    </label> 
</div> 
<textarea id='txtarea'></textarea> 

jQuery的

var tempValue = ''; 
$('.thumbnail :checkbox').change(function() { 
    tempValue += $(this).nextAll("img").attr("src"); 
    $('textarea').html(tempValue);   
}); 

CSS

textarea{width:100%;height:200px;} 
input[type=checkbox] { 
    display: none; 
} 

input[type=checkbox] + label { 
    background: #999; 
    display: inline-block; 
    padding: 0; 
} 

input[type=checkbox]:checked + label { 
    border: 10px solid grey; 
    padding: 0; 
} 

此刻我得到在textarea之內的3210。

的jsfiddle

http://jsfiddle.net/vWFQQ/33/

+0

像這樣:http://jsfiddle.net/vWFQQ/39/ –

回答

3

.nextAll()不會工作,因爲,它是<label>內。您需要使用.next().find()

tempValue += $(this).next("label").find("img").attr("src"); 

片段

$(document).ready(function() { 
 
    var tempValue = ''; 
 
    $('.thumbnail :checkbox').change(function() { 
 
    tempValue += $(this).next("label").find("img").attr("src"); 
 
    $('textarea').html(tempValue); 
 
    }); 
 
});
textarea { 
 
    width: 100%; 
 
    height: 200px; 
 
} 
 

 
input[type=checkbox] { 
 
    display: none; 
 
} 
 

 
input[type=checkbox] + label { 
 
    background: #999; 
 
    display: inline-block; 
 
    padding: 0; 
 
} 
 

 
input[type=checkbox]:checked + label { 
 
    border: 10px solid grey; 
 
    padding: 0; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="thumbnail"> 
 
    <input type="checkbox" name="thing_5" value="valuable" id="thing_5"> 
 
    <label for="thing_5"> 
 
    <img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/a/ac/U.S._Marines_in_Operation_Allen_Brook_(Vietnam_War)_001.jpg"> 
 
    </label> 
 
</div> 
 
<textarea id='txtarea'></textarea>

+0

爲什麼downvote?有什麼理由? –

+0

嘿謝謝,我會在一分鐘內接受它。無論如何,我可以在textarea中添加/刪除選中的項目嗎?如果我有更多圖像/複選框,例如http://jsfiddle.net/vWFQQ/40/ –

+0

@ rob.m,該怎麼辦?您可能需要重做整個循環。這是最好的方法。你想要一個不同的解決方案嗎? –