我需要从选择中获取先前的值(以防ajax失败->将旧值重新设置)
选择为:
<select class="form-control" onchange="setColor(this)">
<option value='12'>Red</option>
<option value='23'>Blue</option>
<option value='34'>Black</option>
</select>
此功能的选择:
function setColor(sel){
$.ajax({
url: set_color_url,
type: 'POST',
data: {id: sel.value},
success: function (response) {
if (!response.error) {
// the color it`s changed :)
} else {
// something went wrong
// change to the prev value
}
}
});
}
如果响应是错误的,我如何获取先前的值并将其改回?
*更新*
服务器的响应是错误为true或false的json:
['error' => true, 'msg' => 'error message' ]
反正...
每个图像都有一个选择(对于每个我要选择颜色的图像):
select元素在laravel刀片中生成:
@foreach($images as $image)
<select class="form-control" onchange="setColor(this, {{ $image->ImageID }})">
@foreach($product->colors as $color)
<option value={{ $color->ColorID }}>{{ $color->Name }}</option>
@endforeach
</select>
@endforeach
*更新2 *
我已经解决了这个问题。我将它从json响应中的后端(如果发生错误)发回旧值,然后在当前选择中设置旧值
if(typeof response.prev !== 'undefined' ){
sel.value = response.prev;
}
答案 0 :(得分:1)
<select id="selectId" class="form-control">
<option value='12'>Red</option>
<option value='23'>Blue</option>
<option value='34'>Black</option>
</select>
将先前的值存储在焦点事件上,并将更改事件链接到您的选择列表上,以在发生错误响应时恢复该值,如下所示。
(function () {
var previous;
$("#selectId").on('focus', function () {
// Store the current value on focus and on change
previous = this.value;
}).change(function () {
// your logic to call ajax
$.ajax({
url: set_color_url,
type: 'POST',
data: {
id: sel.value
},
success: function (response) {
if (response.error) {
// the color it`s changed
$("#selectId").val(previous);
} else {
// Make sure the previous value is updated on successful ajax
previous = this.value;
}
}
});
});
});
答案 1 :(得分:0)
在传递给ajax方法之前,请保留先前的值,如果成功,则仅将值设置为新颜色。
<select id="your_select" class="form-control" onchange="setColor(this)">
<option value='12'>Red</option>
<option value='23'>Blue</option>
<option value='34'>Black</option>
</select>
jQuery
var prValue = $('#your_select').val();
function setColor(sel){
prValue
$.ajax({
url: set_color_url,
type: 'POST',
data: {id: sel.value},
success: function (response) {
if (!response.error) {
// the color it`s changed :)
prValue = sel.value;
} else {
// something went wrong
// change to the prev value
// now you can get your previous value from this var `prValue`;
}
}
});
}
答案 2 :(得分:0)
对于下一个,您可以使用.next()或.child();对于上一个,您可以使用prev() https://www.w3schools.com/jquery/jquery_ref_traversing.asp-推荐重新学习