2016-05-14 58 views
0

如何爲以下代碼設置和更新幫助文本的值?基於下拉選擇的jQuery更新幫助文本

的HTML代碼:

<select class="form-control" id="product-id" name="product-id"> 
    <option value="2">Beauty Products</option> 
    <option value="6">Health Products</option> 
    <option value="7">Gaming Products</option> 
</select> 
<p class="text-info" id="help-text">Total images: 5000/Used in last project: 2000</p> 

而且JSON數據從該值需要進行設置:

<script> 
    var keyCount = 
    [{"id":"2","name":"Beauty Products","img_count":"5000","img_used":"2000"}, 
    {"id":"6","name":"Health Products","img_count":"7000","img_used":"4001-7000"}, 
    {"id":"7","name":"Gaming Products","img_count":"9500","key_used":"0"}] 
</script> 
+0

,你能否告訴我們,到目前爲止,你做了什麼? –

回答

0

可以使用grep()法像它後面做。

var keyCount = 
 
    [{ "id": "2", "name": "Beauty Products", "img_count": "5000", "img_used": "2000" }, 
 
    { "id": "6", "name": "Health Products", "img_count": "7000", "img_used": "4001-7000" }, 
 
    { "id": "7", "name": "Gaming Products", "img_count": "9500", "key_used": "0" }] 
 

 
$('#product-id').change(function() { 
 
    var val = this.value; 
 
    var obj = $.grep(keyCount, function (item, index) { 
 
     return item.id == val; 
 
    })[0]; 
 
     
 
    $('#help-text').text('Total images: ' + obj.img_count + '/Used in last project: ' + obj.img_used); 
 
}).change(); //auto execute when page load
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select class="form-control" id="product-id" name="product-id"> 
 
    <option value="2">Beauty Products</option> 
 
    <option value="6">Health Products</option> 
 
    <option value="7">Gaming Products</option> 
 
</select> 
 
<p class="text-info" id="help-text"></p>