lundi 7 juin 2021

How to get checked selected values in the table?

I have a problem with the checkbox function in the table. I need to follow the check is true, then the selected company value will be alert.

For example for my coding in the below picture, I want the result to be if I have ticked the first row and the fifth row, then the alert message is shown Alfreds Futterkiste,Laughing Bacchus Winecellars

output1

Below is my sample coding, hope someone can guide me on how to solve this problem. Thanks.

function show_value() {
  var checkbox_state = []
  var company_name = []
  //use each loop
  $("[name=checkbox_val]").each(function() {
    checkbox_state.push($(this).is(":checked"))
    company_name.push($(this).closest("tr").find("[name=company_name]").val()) //push value in array

  })
  var check_value = checkbox_state.toString();
  
  if(check_value == true){
       alert (company_name.toString());
  }
  

}
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table>
  <tr>
    <th>Checkbox</th>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td><input type="checkbox" name="checkbox_val" value="0" />&nbsp;</td>
    <td><input type="text" name="company_name" value="Alfreds Futterkiste" /></td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="checkbox_val" value="0" />&nbsp;</td>
    <td><input type="text" name="company_name" value="Centro comercial Moctezuma" /></td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="checkbox_val" value="0" />&nbsp;</td>
    <td><input type="text" name="company_name" value="Ernst Handel" /></td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="checkbox_val" name="checkbox_val" value="0" />&nbsp;</td>
    <td><input type="text" id="company_name" name="company_name" value="Island Trading" /></td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="checkbox_val" value="0" />&nbsp;</td>
    <td><input type="text" name="company_name" value="Laughing Bacchus Winecellars" /></td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
</table>
<button type="button" id="updateBtn_5" class="btn btn-sm btn-primary" onclick="show_value()">Show selected company value</button>



Aucun commentaire:

Enregistrer un commentaire