tipsy / j2html

Java to HTML generator. Enjoy typesafe HTML generation.
https://j2html.com/
Apache License 2.0
765 stars 136 forks source link

Please consider adding onclick #147

Closed afarber closed 4 years ago

afarber commented 4 years ago

Hello,

I have started using j2html 1.4.0 few days ago for a servlet and the API is really nice - nothing like the other APIs I have reviewed for the purpose of creating HTML code in a Java servlet.

However while I have noticed the advice in the issue #137 I do not understand how to apply it to my case: I fetch a long list from a database and then create an input button for each record:

    try (Connection db = DriverManager.getConnection(System.getenv(DATABASE_URL))) {
        try (PreparedStatement st = db.prepareStatement(SQL_LIST_PUZZLES)) {
            ResultSet rs = st.executeQuery();
            while (rs.next()) {
                // fetch the record here and set some vars
                sb.append(String.format(
                        "<P><INPUT TYPE=\"button\" VALUE=\"%d\" ONCLICK=\"toggleMid(this.value)\">\n" +
                        "<A TARGET=\"_blank\" HREF=\"/ws/puzzle2?mid=%d\">mid %d</A> score %d\n" +
                        "<A TARGET=\"_blank\" HREF=\"https://%s/game-%d\">game %d</A></P>\n" +
                        "<P><IMG SRC=\"/ws/puzzle2?mid=%d&secret=%s\" ID=\"img-%d\" STYLE=\"border: 4px solid %s;\"></P><HR>\n", 
                        mid,
                        mid, mid, score,
                        System.getenv(DOMAIN), gid, gid,
                        mid, secret, mid, (isPuzzle ? "#393" : "#FFF")
                ));
            }

The resulting list I display in jQuery UI Accordion:

image

My problem is that each input element has an ONCLICK="toggleMid(this.value)" attribute

I cannot assign it from an external/inline JavaScript code, do I?

Thanks Alex

tipsy commented 4 years ago

I cannot assign it from an external/inline JavaScript code, do I?

It's possible, but you have to take a small detour. You could create

<div class="parent">
  <div data-myprop="1">Test</div>
  <div data-myprop="2">Tast</div>
</div>

And since you're using jQuery:

$(".parent").on("click", "[data-myprop]", function (event) {
    alert($(this).data("myprop"));
});

This way you only have 1 listener too (instead of 1 for each element).

Since your case is an input field, you could add class to it (ex, "my-input"), and just do:

$(".my-input").on("click", function (event) {
    alert($(this).val());
});
afarber commented 4 years ago

Thanks, I get your point. For my case I have solved it with

jQuery(document).ready(function($) {

    $('input[type="button"]').click(function(){ 
        toggleMid(this.value);
    });

    $('#puzzles').accordion({
        header: 'h3'
    });
});