单选按钮 JS 不适用于输入 ID



通过JS调用时的输入id不起作用。我需要的是对输入字段进行更改,例如hide&显示,将输入属性设置为"必需",并删除属性"必需"通过单击单选按钮时在JS中调用的id。我确实放了一个来源引用的"div",编辑了一些并提出了这个。我在这里有我的问题的完整代码,所以我可以理解我的问题。

CSS&头部JS:

<style type="text/css">
.box{
padding: 20px;
display: none;
margin-top: 20px;
border: 1px solid #000;
}
.red{ background: #ff0000; }
</style>
<script type="text/javascript">     
$(document).ready(function(){
$('input[type="radio"]').click(function(){
if($(this).attr("value")=='red'){
$(".box").hide();
$(".red").show();
$('input[type="text"]').hide();
$('input[type="submit"]').hide();
}
if($(this).attr("value")=='rd1'){
var show1 = getElementById('showthis1');
var show2 = getElementById('showthis2');
$('input[type="text"]' + show1).show();
$('input[type="text"]' + show1).attr("required","required");
$('input[type="text"]' + show2).hide();
$('input[type="text"]' + show2).removeAttr("required"); 
$('input[type="submit"]').show();
}
if($(this).attr("value")=='rd2'){
var show1 = getElementById('showthis1');
var show2 = getElementById('showthis2');
$('input[type="text"]' + show1).hide();
$('input[type="text"]' + show1).removeAttr("required");
$('input[type="text"]' + show2).show();
$('input[type="text"]' + show2).attr("required","required"); 
$('input[type="submit"]').show();
}
});
});
</script>

机身:

<from action="">
<label><input type="radio" name = 'selecthere' value="red"> red</label>
<label><input type="radio" name = 'selecthere' value="rd1"> rad1</label>
<label><input type="radio" name = 'selecthere' value="rd2"> rad2</label>
<div class="red box">You have selected <strong>red radio button</strong> so i am here</div> 
<input type="text" name="here1"  id="showthis1"  required/>
<input type="text" name="here2"  id="showthis2" required/>        
<input type="submit" id="showthis" value="Click"/>
</form>

我需要重建这个吗?我真的需要帮助。任何帮助都可能为我在页面开发领域增加更多的想法。提前谢谢。

1.-必须使用document.getElementById

2.-要优化代码,请使用switch

3.-当你通过ID获取元素,然后将它们传递给JQuery时,你只需使用以下方法即可传递它们:

$("#showthis1").hide();
$("#showthis1").removeAttr("required");

而不是

var show1 = document.getElementById('showthis1');
var show2 = document.getElementById('showthis2');
$('input[type="text"]' + show1).show();
$('input[type="text"]' + show1).attr("required","required");

JSFIDDLE演示