jQuery - 检查div中是否有单选按钮

时间:2017-11-10 09:57:44

标签: javascript jquery html

我想检查一下div是否有收音机,文件,复选框。我只是在Html中完成我的标记。我对此没有任何想法。

<div id="div1">

  <input type="radio" name="rd1"> Male
  <input type="radio" name="rd1"> Female

</div> 

<br/>

<div id="div2">

  <input type="file" name="file1">
  <input type="file" name="file2">

</div>

6 个答案:

答案 0 :(得分:2)

您可以使用:has() selector

if ($('div:has(:radio)').length > 0) {
    //code for radio button
}
if ($('.div:has(:file)').length > 0) {
    //code for file
}
if ($('.div:has(:checkbox)').length > 0) {
    //code for checkbox
}

答案 1 :(得分:2)

使用has()方法和:radio :checkbox选择器,您不需要任何if()语句,请查看:

$('div:has(:radio,[type=file],:checkbox)').html("This div has these inputs")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">

  <input type="radio" name="rd1"> Male
  <input type="radio" name="rd1"> Female

</div> 

<br/>

<div id="div2">

  <input type="file" name="file1">
  <input type="file" name="file2">

</div>
<br>
<div id="div3">
   Other inputs div
  <input type="text" name="i1" value="test"><br>
  <input type="number" name="i2" value="12">

</div>

答案 2 :(得分:1)

if ($('div').find('input[type="radio"], input[type="checkbox"], input[type="file"]').length > 0) {...}

答案 3 :(得分:1)

无线电检查
    if($('#div1').find(':radio').length > 0){...

文件检查

if($('#div2').find(':file').length > 0){...

&#13;
&#13;
if($('#div1').find(':radio').length > 0){
 console.log('div1 has radio');
}
if($('#div2').find(':file').length > 0){
 console.log('div2 has file');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div1">
  <input type="radio" name="rd1"> Male
  <input type="radio" name="rd1"> Femal
</div> 
<br/>
<div id="div2">
  <input type="file" name="file1">
  <input type="file" name="file2">
</div>
&#13;
&#13;
&#13;

答案 4 :(得分:1)

只需检查div是否有任何输入后代

&#13;
&#13;
parseList{ it.getOrDefault("name", "unkown_user") }
&#13;
$("div").each( function() {
  var divWithInputExists = $(this).find("input").length > 0;
  console.log("Does this div has inputs -> " , divWithInputExists)
})
&#13;
&#13;
&#13;

答案 5 :(得分:1)

You can do it one of the following ways

Using id selector

if($('#divID :radio').length)
{
   //
}
Using class selector

if($('.div-class :radio').length)
{
   //
}
Using tag name selector

if($('div :radio').length)
{
   //
}*emphasized text*
相关问题