简体   繁体   中英

Convert javascript to jquery on event handling

I have the following code:

    input.setOnkeypress("if (event.keyCode == 13) 
                {
                document.getElementById('search_report_form:search_button').onclick(); 
                return true;
                }");

And this is the function:

final class GroupsSelector extends BaseRenderablePanel<GroupsSelector> {
        private GroupsSelector group(LabourInputReportCriteria.Level level) {
            HtmlSelectBooleanCheckbox box = new HtmlSelectBooleanCheckbox();
            boolean isSelected = selections.isGroupSelected(level);
            box.setSelected(isSelected);
            // box.setDisabled(isDaySelectedOnFirst(level));
            box.setId("groupBy" + level.getClass().getSimpleName());
            box.setOnclick("submit()");
            box.addValueChangeListener(u.addExpressionValueChangeListener("#{reportSearchCriteriaModel.groupBy}"));
            HtmlOutputText labelComponent = new HtmlOutputText();

            labelComponent.setValue(getGroupSelectionValue(level));
            tr().td();
            html(box);
            html("&nbsp;");
            html(labelComponent);
            endTd().endTr();
            return this;
        }

First off, you don't need to change it to jQuery if it's working. Adding jQuery to your page doesn't mean the DOM stops working. And if it's not working, changing your DOM code to equivalent jQuery code won't make it start working.

But the jQuery equivalent of

document.getElementById('search_report_form:search_button').onclick();

is

$('#search_report_form\\3a search_button').click();

or more readably;

$('[id="search_report_form:search_button"]').click();

The tricky bit here is that you have a colon ( : ) in the id , so we can't just do #search_report_form:search_button to look it up, because the colon looks like it's the beginning of a pseudo-class. So we have to escape it. In CSS selectors, you escape it by replacing it with a backslash followed by its hex equivalent. The character code for : in hex is 3A, so \\3a . To write a backslash in a string literal, you have to write two of them (the first escapes the second). You need the space after it to terminate it, hence '#search_report_form\\\\3a search_button' .

The second form uses an attribute selector instead, since we can put the ID in quotes, and don't have to worry about the colon.

If you want to convert your first few lines to JQuery then Try this

$('input').on('keypress', function(event){
    if (event.keyCode == 13) {
       $('[id="search_report_form:search_button"]').click(); //.submit();
       return true;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM