2017-06-14 108 views
0

经过很长时间的搜索后,我仍然无法找到解决我的问题。从单选按钮获取值select 2

<label class='radio radio-inline'> 
      <input type='radio' name='roomtype' value ='1' required @if($row['roomtype'] == '1') checked="checked" @endif > Single Room </label> 
      <label class='radio radio-inline'> 
      <input type='radio' name='roomtype' value ='2' required @if($row['roomtype'] == '2') checked="checked" @endif > Double Room </label> 
      <label class='radio radio-inline'> 
      <input type='radio' name='roomtype' value ='3' required @if($row['roomtype'] == '3') checked="checked" @endif > Triple Room </label> 

我想将单选按钮的值传递给select2元素。

$(".select2").select2({ width:"100%", maximumSelectionLength:3 }); 

对于maximumSelectionLength值,而不是3我想从单选按钮传递值..所以我来此解决方案,但它没有工作

$(".select2").select2({ width:"100%", maximumSelectionLength: $('input[name=roomtype]:checked') }); 

赞赏任何帮助。感谢

编辑: 我的形式是在模式..不幸的是,这些解决方案并没有为我工作..

+0

你很近。 '$('input [name = roomtype]:checked')。attr('value')'可能有帮助。 – 31piy

+0

不幸的是没有工作..窗体是模态。这可能是为什么?不知道 – stoneshak

+0

你应该展示一些你的代码 - 或者更好地尝试为你的问题创建一个[最小的,完整的和可见的例子](https://stackoverflow.com/help/mcve)。 – gus27

回答

0

您可以使用change回调的roomtype单选按钮。在回调函数中,您可以通过this.value获得单选按钮的值。所以你所需要的是将maximumSelectionLength设置为this.value

事情是这样的:

$(document).ready(function() { 
 
    $('input[type=radio][name=roomtype]').change(function() { 
 
     alert(this.value); 
 
     // $(".select2").select2({ width:"100%", maximumSelectionLength: this.value }); // uncomment this 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label class='radio radio-inline'> 
 
    <input type='radio' name='roomtype' value ='1' checked="checked"> Single Room </label> 
 
<label class='radio radio-inline'> 
 
    <input type='radio' name='roomtype' value ='2'> Double Room </label> 
 
<label class='radio radio-inline'> 
 
    <input type='radio' name='roomtype' value ='3'> Triple Room </label>

0

另一种方法可以简单地使用Laraval刀片设置maximumSelectionLength(我以为你在你的代码中使用Laravel刀片从@if指令) 。

$(".select2").select2({ 
    width:"100%", 
    maximumSelectionLength: {{ $row['roomtype'] }} 
});