[英]How do I split a value using the split function from javascript to split checking only the first and last occurence
[英]Using split, but can only get the first [0] value
我將多個值存儲在一個select選項中,並嘗試通過拆分值來分別獲取所有值。 拆分似乎可以正常工作,因為我可以獲得第一個[0]值,但是此后我沒有任何值。 它以未定義的形式發回警報。 下面的代碼。 謝謝。
function roi_calc(e) {
var merchant_option = $(e).prev('td').prev('td').prev('td').find('select').val();
if (merchant_option!='Merchant') {
var value_input = $(e).prev('td').prev('td').find('input').val();
if ((value_input!='') && (value_input!='Value')) {
var price_input = $(e).prev('td').find('input').val();
if ((price_input!='') && (price_input!='Price')) {
alert ('Merchant value = '+merchant_option);
//var price_arr = new Array();//tried setting array first, but same results
var price_arr = price_input.split(',',3);
//alert (price_arr);//alerts '1'
alert (price_arr[0]);//working - alerts '1'
alert (price_arr[1]);//not working - undefined
alert (price_arr[2]);//not working - undefined
}
else {alert ('Price must be entered.');}
}
else {alert ('Value must be entered.');}
}
else {alert ('Merchant must be selected');}
//alert (row_option);
}
的HTML
<table style="width: 600px;">
<tr>
<td>
<select>
<option>Merchant</option>
<option value="1,2,3,4">1</option>
<option value="5,6,7,8">2</option>
</select>
</td>
<td><input value="Value"></td>
<td><input value="Price"></td>
<td onclick="roi_calc(this);"> R.O.I </td>
</tr>
</table>
在jsfiddle上http://jsfiddle.net/upywN/
找到答案。 我這是愚蠢的錯誤。
我當時正在分割price_input,但是需要分割商人_選項愚蠢的錯誤很抱歉浪費大家的時間。
這通常是無效的HTML
<option value="1,2,3,4">1</option>
查看選項的屬性
相反,您應該像這樣使用multiple select
<select multiple="multiple">
更新:您正在捕獲“選定值”(即“ 1”而不是“ 1,2,3,4”)表格
<option value="1,2,3,4">1</option>
但是您必須拆分“文本”部分(即“ 1,2,3,4”)。
您可以使用Javascript來抓取選項的“文本”部分,如下所示:
var list = document.getElementById('list'); // 'list' is the id of select element
var text = list.options[list.selectedIndex].text;
//And now use your split
var price_arr = text.split(',',3);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.