更改无线电时更新选择相同的值

时间:2018-06-07 10:55:23

标签: javascript

我有一个无线电输入和一个选择,两者都有相同的值。当选择收音机时,我要更新选择,以便选择具有相同的活动选项,当我更改选择时我想要收音机改变。

$(".change").change(function() {
	var selected = $(this).val();
	$(".change").val(selected);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="radio" id="yes" value="yes" checked  class="change"/>
<label for="yes">Yes</label>
<input type="radio" name="radio" id="no" value="no" class="change" />
<label for="yes">No</label>

<select name="application_type" class="change">
	<option value="yes" selected>Yes</option>
	<option value="no">No</option>
</select>

2 个答案:

答案 0 :(得分:2)

检查代码段,这可能对您现在有所帮助:D

 var selected;
jQuery(".change").on('change', function() {
  if(this.type == 'radio') {
  	selected = jQuery(this).attr('id');

    jQuery(".change[name=application_type]").val(selected);
  }else{
    
    selected = jQuery(this).val();
    jQuery('.change[type=radio][value='+selected+']').prop('checked', true);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input type="radio" name="radio" id="yes" value="yes" checked  class="change"/>
<label for="yes">Yes</label>
<input type="radio" name="radio" id="no" value="no" class="change" />
<label for="yes">No</label>

<select name="application_type" class="change">
	<option value="yes">Yes</option>
	<option value="no">No</option>
</select>

答案 1 :(得分:2)

&#13;
&#13;
$(".change").on("change",function(){
  console.log($(this).val(),$(this).attr("type"));
  if($(this).attr("type")=="radio"){
    $("select.change").val($(this).val());
  }if(typeof $(this).attr("type")=="undefined"){
    $("#"+$(this).val()).prop("checked","checked");
  }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="radio" id="yes" value="yes" checked  class="change"/>
<label for="yes">Yes</label>
<input type="radio" name="radio" id="no" value="no" class="change" />
<label for="yes">No</label>

<select name="application_type" class="change">
	<option value="yes" selected>Yes</option>
	<option value="no">No</option>
</select>
&#13;
&#13;
&#13;

你做错了,如上所述是一个正确的解决方案。因为你正在改变无线电的价值不起作用。