我有一个选择字段,其内容根据另一个选择字段而变化。禁用我的脚本,我的选择发布正常,并插入我的数据库。但是,当我使用javascript搞乱select字段时,我的发布值默认为默认值(“1”)。我也在运行chzn(http://harvesthq.github.io/chosen/)但是问题仍然存在,即使它被禁用了。这是我的JS:
$(function() {
var $dropdown = $("#type");
var $for = $("#for");
$for.clone().attr('id', 'for2' ).insertAfter($for).hide();
$for2 = $('#for2');
function getType() {
$type = $dropdown.val();
return $type;
}
function checkType($type) {
if ($type == 1) {
$for.find('.skin').remove();
$for2.find('.champion').clone().appendTo($for).trigger("liszt:updated");
} else if ($type == 2) {
$for.find('.champion').remove();
$for2.find('.skin').clone().appendTo($for).trigger("liszt:updated");
}
}
getType();
checkType($type);
$dropdown.change(function() {
getType();
checkType($type);
});
});
导致此问题的原因是什么?谢谢你看:))
编辑 正在运行alert($for.find($("option:selected")).text());
会返回我选择的选项。我真的不明白为什么没有发布。
edit2 我可以通过附加(隐藏)文本字段并在我的选择更改时设置它的值来使其工作,当然更新我的控制器以使用“为价值”:
$('<input/>').attr({ type: 'text', id: 'for-value', name: 'for-value' }).insertAfter($for).hide();
$forValue = $('#for-value');
$for.change(function() {
$forVal = $for.val();
$forValue.val($forVal);
});
但这太丑了......为什么我不能按常规方式工作呢?我错过了什么吗?
的 EDIT3 的 根据要求,HTML:
<form action="insert" method="POST">
...
<label for="type">type</label>
<select id="type" name="type">
<option value="1">Champion</option>
<option value="2">Skin</option>
</select>
<label for="for">For</label>
<select id="for" name="for">
@foreach ($skins as $skin)
<option class="skin" value="{{ $skin->id }}">{{ $skin->name }}</option>
@endforeach
@foreach ($champions as $champion)
<option class="champion" value="{{ $champion->id }}">{{ $champion->name }}</option>
@endforeach
</select>
...
<button>Insert</button>
</form>
edit4 更糟糕的是,正如Stano所建议的那样,当克隆使其有效时,它会包含一个名称,如果我在链中移除属性,它甚至可以工作:
$for.clone().attr('id', 'for2').insertAfter($for).hide(); //doesn't work.
$for.clone().attr({ id: 'for2', name: 'for2' }).insertAfter($for).hide(); //works
$for.clone().attr({ id: 'for2', name: 'for2' }).removeAttr('name')
.insertAfter($for).hide(); //works even if I remove the attribute
答案 0 :(得分:1)
克隆该对象也会使用name
,并且发布将采用HTML中引用的最后name
,这是第一个select
的副本。这就是它总是返回1的原因。
在链计数器中删除或重命名name
属性,如下所示:
$for.clone().attr('id', 'for2').removeAttr('name').insertAfter($for).hide();