我正在从数据库中生成问题,用户将在下拉菜单中选择答案。当用户选择某个选项时,建议将被推送到触发JavaScript的on-change事件的数组。当用户完成所有问题后,我将把数组作为行从存储所有建议的表单发送到数据库。
当我尝试发送建议时,建议第一次被推送,但是当用户更改答案时,阵列会再次发送重复消息
<form action="">
@foreach ($questions as $question)
{{-- <p>{{$question->id}}){{$question->english}}</p> <br> --}}
<div class="form-group">
<label>{{$question->id}}) {{$question->english}}</label>
<select id="{{$question->id}}" onchange="sendSuggestion()" class="form-control" id>
<option value="yes">Yes</option>
<option value="no">No</option>
<option value="regularly">Regularly</option>
<option value="sometimes">Sometimes</option>
</select>
</div>
@endforeach
</form>
_fixture.Inject(new ControllerContext());
当用户选择ID为1和2的问题时,我希望输出“您需要学习更多”。
答案 0 :(得分:1)
使用以下命令更新您的javascript
函数:
function sendSuggestion() {
if (document.getElementById("1").value == "no" && document.getElementById("2").value == "no" ){
if (suggestions.indexOf("you need to study more") == -1){
suggestions.push("you need to study more");
}
}
if (document.getElementById("1").value == "yes" && document.getElementById("2").value == "yes" ){
var index = suggestions.indexOf("you need to study more");
if (index > -1) {
suggestions.splice(index, 1);
}
}
}
这将在您的数组中提供不同的建议,而不重复。
答案 1 :(得分:0)
如果您不需要存储多个建议,则可以在每次函数调用时将数组设置为空。
var suggestions=[];
function sendSuggestion() {
// here will work
suggestions = [];
if (document.getElementById("1").value == "no" && document.getElementById("2").value == "no") {
// or if you only want to set to empty if the conditional passes you can do it here
suggestions = [];
suggestions.push("you need to study more");
}
}
如果需要或要填充阵列,可以检查特定项目。无需在条件数组中重新初始化数组,而是运行此命令
let index = suggestions.indexOf("you need to study more");
// negative one is returned if the item is not found
// if it's found we'll remove it from the array
if (index > -1) suggestions.splice(index, 1);
文档//
Array.splice()-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Array.indexOf()-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf