Search code examples
grailsgroovy

How can I pass HTML table data from a view to controller in grails?


I'm quite new in grails. I'm creating an SMS send module for my project. Here I'm getting some contact number from the user and displaying it inside a dynamically created 'TD' value. Now I want to pass this 'TD' values as a list to my controller.

def controller(){ 

def var = params.name

}

won't work here as it's not a field value.


Solution

  • Get all table td into array comma separated contact numbers.

    Both ways added in the below code. First, where the contact number is last column. And the second, where all td value have class name.

    // First way
    
    var contactNumbers= []
    $("#example tbody tr").each(function() {
      contactNumbers.push($(this).find("td:last-child").html());
    });
    console.log("If Contact number column is on last"+contactNumbers.join())
    
    
    // Second way
    
    var contactNumbers1= []
    $(".cnTd").each(function(i){
        contactNumbers1.push($(this).text())
    })
    console.log("Contact numbers by class"+contactNumbers1.join())
    <head>
      <title>Bootstrap Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
    </head>
    <body>
    
    <div class="container">
              
      <table class="table" id="example">
        <thead>
          <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Email</th>
            <th>Contact Number</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>John</td>
            <td>Doe</td>
            <td>[email protected]</td>
            <td class="cnTd">5675677567</td>
          </tr>
          <tr>
            <td>Mary</td>
            <td>Moe</td>
            <td>[email protected]</td>
            <td>90987786756</td>
          </tr>
          <tr>
            <td>July</td>
            <td>Dooley</td>
            <td>[email protected]</td>
            <td>3455657457</td>
          </tr>
        </tbody>
      </table>
    </div>

    Now you you send the collected values to controller using hidden form value or by sending ajax request or by query params. At contoller side simply use split(',') or tokenize(',') method to get list of numbers.

    Hope this will helps you.