2017-02-19 91 views
0

這是我的選擇選項: -是否可以在Javascript的選擇選項上附加項目數量?

<select id="listboxstock" size="5" class="form-control"> 
 
    <option>Carrot - 3</option> 
 
    <option>Cucumber - 2</option> 
 
</select>

我要追加項目的數量,如果同樣的產品加入。 對於例如:

如果我再添加1個胡蘿蔔,選項應該從改變: -

<option>Carrot - 3</option> to be <option>Carrot - 4</option> 

我可以使用JavaScript的呢?如果沒有,我該怎麼做?

+0

你如何添加項目? –

+0

對於第一個問題,是的,你可以做到這一點,第二個是廣泛的,沒有顯示你到目前爲止已經嘗試過什麼 – Icepickle

+0

谷歌'''選擇的JavaScript更改選項文本' –

回答

1

給你

$("#addOption").on("click", function(e){ 
 
    var newOption = $("#optionText").val(); 
 
    var options = {}; 
 
    var index = 0; 
 
    $("#listboxstock option").each(function() { 
 
     debugger; 
 
     var valueComponents = $(this).val().split(" - "); 
 
     if (valueComponents[0] == newOption) { 
 
     var number = parseInt(valueComponents[1]); 
 
     number++; 
 
     $(this).val(valueComponents[0] + " - " + number); 
 
     } 
 
     options["option" + index] = $(this).val(); 
 
     index++; 
 
    }); 
 
    var $el = $("#listboxstock"); 
 
    $el.find('option') 
 
     .remove() 
 
     .end(); 
 
    //console.log($el); 
 
    $.each(options, function(key,value) { 
 
     $el.append($("<option>" + value + "</option>")); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="listboxstock" size="5" class="form-control"> 
 
    <option>Carrot - 3</option> 
 
    <option>Cucumber - 2</option> 
 
</select> 
 
<input type="text" placeholder="Type the name of the item to add" id="optionText" /> 
 
<button id="addOption">Add Option</button>

+0

這正是我想要的...非常感謝這麼多老兄: ) –

0

所以你可以使用大量的內置函數來做到這一點。個人而言,我會用分裂和parseInt函數創建下面的代碼:

<html> 
<body> 
<select size="5"> 
<option onclick="myFucntion()" id="item">Carrot - 3</option> 
<option>Cucumber - 2</option> 
</select> 
<script> 
function myFucntion(){ 
    var str=document.getElementById("item").innerHTML; 
    str=str.split(" "); 
    res=parseInt(str[2]); 
    res++; 
    document.getElementById("item").innerHTML="Carrot - "+res; 
} 
</script> 
</body> 
</html> 

我不知道我理解你想要做什麼,但我相信你想要這個。

1

你可以在所選option元件的textContent使用replace,使用正則表達式來提取數部分,然後使用replace的回調函數,以注入所述更新數。

這裏是一個演示:

function adjustCount(diff) { 
 
    var sel = document.getElementById('listboxstock'); 
 
    if (sel.selectedIndex < 0) return; // nothing selected 
 
    var opt = sel.options[sel.selectedIndex]; 
 
    opt.textContent = opt.textContent.replace(/\d+/, function (m) { 
 
     return Math.max(0, +m + diff); // adjust, but not below 0 
 
    }); 
 
} 
 

 
document.getElementById('inc').addEventListener('click', adjustCount.bind(null, 1)); 
 
document.getElementById('dec').addEventListener('click', adjustCount.bind(null, -1));
<select id="listboxstock" size="5" class="form-control"> 
 
    <option>Carrot - 3</option> 
 
    <option>Cucumber - 2</option> 
 
</select> 
 
<br> 
 
<button id="inc">Add</button> 
 
<button id="dec">Remove</button>