In jquery, only the first group of radio buttons is selected

I am creating a system in which a user can create a form. Therefore, I do not know the name of the radio button. The user can create as many different switches as he likes. If the script is running, I want to check the first radio buttons from the view. However, the jquery I made chose only the first one. Someone has an answer:

<div class="formElement">
Eieren<br>
<p class="white"><input type="radio" name="eieren" class="formEl">ja</p>
<p class="white"><input type="radio" name="eieren" class="formEl">nee</p>
<p class="white"><input type="radio" name="eieren" class="formEl">soms</p>
</div>

<div class="formElement">
Peren<br>
<p class="white"><input type="radio" name="peren" class="formEl">ja</p>
<p class="white"><input type="radio" name="peren" class="formEl">nee</p>
<p class="white"><input type="radio" name="peren" class="formEl">soms</p>
</div>

<script>
$(".formElement p:eq(0) :radio").attr("checked", "checked");
</script>

result

+4
source share
2 answers

.find(), p ( $(".formElement")) , find(). :

$(".formElement")
	.find("p:eq(0)")//returns first p element that match selector
	.find(":radio")//returns first radio element that match previous selector
	.prop("checked", true);//set check to true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="formElement">
  Eieren
  <br>
  <p class="white">
    <input type="radio" name="eieren" class="formEl">ja</p>
  <p class="white">
    <input type="radio" name="eieren" class="formEl">nee</p>
  <p class="white">
    <input type="radio" name="eieren" class="formEl">soms</p>
</div>

<div class="formElement">
  Peren
  <br>
  <p class="white">
    <input type="radio" name="peren" class="formEl">ja</p>
  <p class="white">
    <input type="radio" name="peren" class="formEl">nee</p>
  <p class="white">
    <input type="radio" name="peren" class="formEl">soms</p>
</div>

:

: eq()

+4

:first-of-type -, .

$(".formElement p:first-of-type  :radio").prop("checked", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="formElement">
    Eieren<br>
    <p class="white"><input type="radio" name="eieren" class="formEl">ja</p>
    <p class="white"><input type="radio" name="eieren" class="formEl">nee</p>
    <p class="white"><input type="radio" name="eieren" class="formEl">soms</p>
</div>

<div class="formElement">
    Peren<br>
    <p class="white"><input type="radio" name="peren" class="formEl">ja</p>
    <p class="white"><input type="radio" name="peren" class="formEl">nee</p>
    <p class="white"><input type="radio" name="peren" class="formEl">soms</p>
</div>
+2

All Articles