【发布时间】:2020-03-19 17:50:54
【问题描述】:
如果标签的相应下拉列表已更改值(在同一行中),我想更改标签。这是html页面。
每个下拉菜单和标签都有不同的 ID。例如,如果有 4 个下拉菜单,那么它们的 id 将是 dropdown1、dropdown2、dropdown 3、dropdown 4。与 label 相同。但我的问题是我不知道如何将这两个元素对应或链接在一起,例如:下拉列表 1 应该连接到标签 1,这意味着只要 select1 下拉列表发生更改,label1 就会更改(通过显示 dropdown1 的当前选择选项)。
这是我的 HTML 的 sn-p 源代码:
<td>
<select class="form-control" id = "bookingTypeDropDown{{$counter1}}"> <!-- Assigning of unique ids based on iteration number -->
@foreach($booking_types as $booking_type)
<option value = "{{$booking_type->book_type_price}}">
{{$booking_type->book_type_name}}
</option>
@endforeach
</select>
</td>
@foreach($depart_destination_country as $destination)
<td>
<input type="radio"
name="departure_flight_id"
value="{{$flight->flight_id}}" required>
<label id = "calculatedFare{{$counter1}}">price here</label> <!-- Assigning of unique ids based on iteration number -->
<input type="hidden" name="total_departure_fare" value="#" required>
</td>
@endforeach
下图是上面提供的sn-p源码的html:
源码(负责select改变时label的改变):
<script type = "application/javascript">
window.onload = function() {
var numItems = $('.form-control').length; //Counts the number of <select> by class
var dropdowns =[];
var labels = [];
for(var i=0; i<numItems; i++) //Iteration for getting all <select> and <labels> and storing them in their respective arrays
{
dropdowns[i] = document.getElementById("bookingTypeDropDown" + i);
labels[i] = document.getElementById("calculatedFare" + i);
}
var currentElement;
for(var d=0; d<dropdowns.length; d++)
{
var price;
$(dropdowns[d]).change(function (){ //if dropdown object changed option
var price = $(this).val(); //getting of option's value
currentElement = d; //getting of array index where change was detected
console.log(price); //printing only
console.log(currentElement); //printing of what index does the changed occured
});
$(labels[currentElement]).text("PHP " + price); //
}
}
我的 javascript 代码中的问题是它总是打印最后一个索引或迭代号(在这种情况下为 4),但打印的值是正确的。例如,如果我单击第一个下拉菜单,它会打印正确的值而不是正确的索引(打印索引 4 而不是索引 1)。价值没有问题。
我想要的是正确检测已更改元素的选项,一旦检测到它应该更改其相应的标签。
场景示例:
选择1 = 标签1
Select2 = 标签2
Select3 = 标签3
....
如何将选择与标签协调?
【问题讨论】:
-
"如何将两个元素对应或链接在一起" - 给它们相同的数据-(例如“pair”)属性+值,然后在
select更改,它是:$("[data-pair='" + $(this).data("pair") + "']").text($(this).val())
标签: javascript jquery html laravel