Get generic input field checked with jQuery

Asked

Viewed 154 times

0

I’m having a hard time getting the value of checkboxes marked through jQuery after a Ubmit. It turns out that the input checkbox fields are generated dynamically by a database query, and I’m not knowing how to take them in a generic way. Example of PHP code:

 foreach($items as $i){
   echo "<input type='checkbox' id='termo'>".$i['nome']."<br/>";
 }

Jquery

$("#buttonSubmit").on('click', function(event){
  event.preventDefault();
  $('#termo').get(0);
});

How to get checkbox marked from multiple input fields with the same id?

  • normally javascript takes only one element per id, if you want it to perform an action with multiple inputs it should give the same class not the same id.

  • Wouldn’t it be easier to get the "name" of the checkbox? Id usually tends to be unique by html element.

1 answer

1


First repeat id’s is already wrong. There are numerous ways to select checkboxes. The most common is by a class. The code below returns a nodelist with all checkbox with class .nomes:

$("#buttonSubmit").on('click', function(event){
  event.preventDefault();
  console.log($('input.nomes'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="nomes" type='checkbox' value='nome1'>Nome 1<br/>
<input class="nomes" type='checkbox' value='nome2'>Nome 2<br/>
<input class="nomes" type='checkbox' value='nome3'>Nome 3<br/>
<button id="buttonSubmit">OK</button>

The code below returns only checboxes checked:

$("#buttonSubmit").on('click', function(event){
  event.preventDefault();
  console.log($('input.nomes:checked'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="nomes" type='checkbox' value='nome1' checked>Nome 1<br/>
<input class="nomes" type='checkbox' value='nome2'>Nome 2<br/>
<input class="nomes" type='checkbox' value='nome3'>Nome 3<br/>
<button id="buttonSubmit">OK</button>

  • Thank you Sam, you’ve helped a lot...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.