AKIWEB
AKIWEB

Reputation: 19612

Generate dynamic check boxes values from the servlet response

I have values coming from database in a servlet response as id and name; and I am storing it in a Map key-value in a servlet.

I wanted to now create a JSP code which generates a checkboxes and show the dynamic list of values.

Servlet code

String sql = "SELECT customerid , c_name from customer";
ResultSet rs = s.executeQuery(sql);
Map<String, String> options = new LinkedHashMap<String, String>();

while (rs.next()) {
options.put(rs.getString("customerid"), rs.getString("c_name");
}

String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

JSP Code--

$(document).ready(function () {                           
    $('.btn-checkbox').click(function () {      
    $.get('dataservlet', function (responseJson) {
    var $input = $('#id1');
    var $type = 'checkbox';
        $.each(responseJson, function (key, value) {              
        $('$type').val(key).text(value).appendTo($input); 
    });
    });
});

//JQuery is not generating the right checkboxes, even when the response is in, need help in forming the correct JQuery.

HTML Code--

div id="id1"></div>

example-

I have a record coming as-

customerid c_name
5000       name1

and I needed a checkbox to get generated as:

<input type ="checkbox" id'5000"/>name1 

// so here key is id and value is name1

I needed a check-box with values in it as below image-

enter image description here

UPDATE

enter image description here

Upvotes: 0

Views: 1491

Answers (1)

Shaunak D
Shaunak D

Reputation: 20626

You are doing it totally wrong. Use the following lines. Demo Fiddle

var append = $('<input type="'+$type+'">'+value+'</input>').attr('id',key).val(value);

$($input).append('<br/>').append(append);
  • $type cannot be used as string - $('$type')
  • key is your ID - so you cannot use it using .val().
  • Why are you appending it to the input, you should insert the new checkboxes after input - .after().
  • And your forget to end $(document).ready() with });.
  • Use .change() and not .click() incase of inputs.

So your final JS :

$(document).ready(function () {                           
    $('.btn-checkbox').change(function () {      
        $.get('dataservlet', function (responseJson) {
            var $input = $('#id1');
            var $type = 'checkbox';
            $.each(responseJson, function (key, value) {              
               var append = $('<input type="'+$type+'">'+value+'</input>').attr('id',key).val(value);
               $($input).append('<br/>').append(append); 
            });
        });
    });
});

Upvotes: 1

Related Questions