当选择其他下拉列表的其他选项时,禁用下拉列表选项(选择)

时间:2018-04-27 17:15:22

标签: javascript jquery html

鉴于两个<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-XXXXXXXXX-1'); </script> 下拉列表具有相同的选项和值,我想在另一个下拉列表中禁用在一个下拉列表中选择的值。

这是我的HTML代码:

<select>

所以,当我在发件人中选择A(1),它在Receiver中被禁用,因此用户无法选择该表单中的同一个人(因为它没有意义)。

1 个答案:

答案 0 :(得分:0)

使用jQuery,您可以在任何表单(独立)更改时调用函数,然后允许启用除在另一个<span>Sender:</span> <select required name="Sender"> <option selected disabled value="Select one">Select one</option> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> <option value="4">D</option> <option value="5">E</option> </select> <span>Receiver:</span> <select required name="Receiver"> <option selected disabled value="Select one">Select one</option> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> <option value="4">D</option> <option value="5">E</option> </select> 下拉列表中选择的选项之外的所有选项。请记住,我们还必须重新启用以前禁用的选项。

<select>
// When the user selects an option in "Sender" dropdown selection, this function disables in the "Receiver" dropdown selection the person selected in the other dropdown
	$('[name="Sender"]').change(function () { 
		console.log("Sender changed to value "+this.value+"!");
		$('[name="Receiver"]>option').removeAttr("disabled");
		$('[name="Receiver"]>option[value="Select one"]').attr("disabled","disabled");
		$('[name="Receiver"]>option[value="'+this.value+'"]').attr("disabled","disabled");
	});

// When the user selects an option in "Receiver" dropdown selection, this function disables in the "Sender" dropdown selection the person selected in the other dropdown
	$('[name="Receiver"]').change(function () { 
		console.log("Receiver changed to value "+this.value+"!");
		$('[name="Sender"]>option').removeAttr("disabled");
		$('[name="Sender"]>option[value="Select one"]').attr("disabled","disabled");
		$('[name="Sender"]>option[value="'+this.value+'"]').attr("disabled","disabled");
	});