[英]RadioButton JS doesn't work with input ids
通過JS調用時,輸入ID無效。 我需要的是對輸入字段進行更改,例如“隱藏和顯示”,將輸入屬性設置為“必需”,並通過單擊單選按鈕時通過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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.