2017-02-19 94 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>