我正在开发一个产品比较器,其中用户必须 Select 只有4个产品的宇宙中的两个产品,例如.
在这种情况下,用户将在这个世界中 Select 具有4个产品的两个产品,并且这些 Select 的产品的信息将出现在列中(列1和列2).
我试着在这里研究一些类似的问题,但不幸的是,我没有找到正确的方法:
- Get two values from select option at once个
- Select and Radio options to show div个
- Two radio buttons are selecting at once个
我的问题是:我如何才能只 Select 两个单选选项,始终只限制两个选项?另外,如何显示列1内所选选项和列2内第二个所选产品的单选数值?
以下是我使用的代码:
HTML structure that display 4 products with their respective radio buttons:个
<h2 class="mb-3">Produtos</h2>
<div class="row justify-content-center">
<div class="col-2">
<img src="https://assets.adidas.com/images/h_840,f_auto,q_auto,fl_lossy,c_fill,g_auto/cde9362a09ba4dd38c9ead6600ac074e_9366/Tenis_Duramo_SL_2.0_Preto_GW8336_01_standard.jpg" width="100px"/>
<input class="form-check-input radio" type="radio" name="produto1" id="1" value="Tênis preto">
<label class="form-check-label" for="1"></label>
</div>
<div class="col-2">
<img src="https://assets.adidas.com/images/h_840,f_auto,q_auto,fl_lossy,c_fill,g_auto/7ed0855435194229a525aad6009a0497_9366/Tenis_Superstar_Branco_EG4958_01_standard.jpg" width="100px"/>
<input class="form-check-input radio" type="radio" name="produto2" id="2" value="Tênis branco">
<label class="form-check-label" for="2"></label>
</div>
<div class="col-2">
<img src="https://assets.adidas.com/images/h_840,f_auto,q_auto,fl_lossy,c_fill,g_auto/9326e8db8d8e4e509e42ad26010cf693_9366/Tenis_adidas_4DFWD_Pulse_Preto_Q46451_01_standard.jpg" width="100px"/>
<input class="form-check-input radio" type="radio" name="produto3" id="3" value="Tênis verde">
<label class="form-check-label" for="3"></label>
</div>
<div class="col-2">
<img src="https://assets.adidas.com/images/h_840,f_auto,q_auto,fl_lossy,c_fill,g_auto/7a80a0e74201457eb1e5adcb00ff92f8_9366/Tenis_Dropset_Trainer_Azul_GZ2941_01_standard.jpg" width="100px"/>
<input class="form-check-input radio" type="radio" name="produto4" id="4" value="Tênis azul">
<label class="form-check-label" for="4"></label>
</div>
</div>
<div id="coluna1"></div>
<div id="coluna2"></div>
下面的jQuery代码获取所选项目的值,并在各自的列中显示它们的信息.这些编码不允许 Select 两个以上的产品:
$('.radio').change(function(){
var shoes = $(this).val();
var count = $("input[type='radio']:checked").length;
if(count > 2){
alert("you just have to select only two shoes.");
$(this).prop('checked', false);
return false;
}
$('#column1').text(shoes);
$('#column2').text(shoes);
//
});
在这种情况下,我如何改进我的代码以达到正确的结果?作为一个实际例子,我起草了一份关于JSFIDLE:https://jsfiddle.net/kg51Lvzx/的草案