【发布时间】:2011-08-24 22:49:29
【问题描述】:
我在一个表单中有一堆选择字段。选择字段中的某些选项有价格。价格始终采用<option>text (+£9.99)</option> 格式,但显然价格可能会有所不同。如果其中一个选项被更改,我希望从选项中获取所有价格。不过,我只想要更改时选择的选项的价格。
使用 JQuery .change() 方法很好,但我很难理解如何使用 .match 方法从选项中返回数值以及如何仅获取选定的选项。我认为正则表达式是'/\(\+£([0-9\.]+)\)/'。
$("select").live('change',function () {
var price = 0;
$("select option:selected").live('each',function () {
price += $(this).text().match('/\(\+£([0-9\.]+)\)/');
});
alert (price);
})
我正在使用 live,因为表单是通过 ajax 加载的,具体取决于页面上的另一个表单。
任何帮助将不胜感激
谢谢
卢克
编辑:我尝试过 $(this).val().match 而不是 .text 方法。
编辑 2:我无法更改选项的值,因为它对应于数据库中选项的 id。 (参考下面丹尼斯的回答)
更新: 为了在 symfony 中使用下面的正确答案,我必须添加一个自定义小部件:
class myWidgetFormSelect extends sfWidgetFormSelect {
/**
* Returns an array of option tags for the given choices
*
* @param string $value The selected value
* @param array $choices An array of choices and attributes array key "content" denotes text
* to be entered in option, all other keys become attributes
*
* @return array An array of option tags
*/
protected function getOptionsForSelect($value, $choices) {
$mainAttributes = $this->attributes;
$this->attributes = array();
if (!is_array($value)) {
$value = array($value);
}
$value = array_map('strval', array_values($value));
$value_set = array_flip($value);
$options = array();
foreach ($choices as $key => $option) {
$attributes = array('value' => self::escapeOnce($key));
if (!is_array($option))
$content = $option;
else {
foreach ($option as $name => $val) {
if ($name == 'content')
$content = $val;
else
$attributes[$name] = $val;
}
}
if (isset($value_set[strval($key)])) {
$attributes['selected'] = 'selected';
}
$options[] = $this->renderContentTag('option', self::escapeOnce(isset($content) ? $content : ''), $attributes);
}
$this->attributes = $mainAttributes;
return $options;
}
}
这个类允许选择数组是一个数组,并且使用如下调用具有多个属性:
new myWidgetFormSelect(array(
'choices' => array(
'1' /* <- the id of the option */ => array(
'content' => 'text (+£9.99)',
'data-price' => '9.99'
)
)
))
上面将创建一个带有选项的选择字段:
<option value="1" data-price="9.99">text (+£9.99)</option>
我希望这对遇到相同问题的人有所帮助。
【问题讨论】: