Vietnam Archive Vietnam Archive - 2 months ago 20
Javascript Question

How to cause a click event?

The form has a button on it that when clicked provides a dropdown of some various types. How can I cause a click event on any of these types when the form is ready?

This is what I tried, but doesn't work.

<script>
$( document ).ready(function() {
document.getElementsByClassName("advanced-search-add-text-row").click();
});
</script>

<div class="btn-group">
<a class="btn btn-success dropdown-toggle advanced-search-add-row-dropdown" data-toggle="dropdown" href="#">
<span class="glyphicon glyphicon-plus glyphicon-white"></span>
<span class="caret"></span>
</a>
<ul class="dropdown-menu pull-right">
<li><%= link_to I18n.t("advanced_search.type.text"), "javascript:void(0)", :class => "advanced-search-add-row advanced-search-add-text-row", "data-type" => "text" %></li>
<li><%= link_to I18n.t("advanced_search.type.date"), "javascript:void(0)", :class => "advanced-search-add-row advanced-search-add-date-row", "data-type" => "date" %></li>
<li><%= link_to I18n.t("advanced_search.type.boolean"), "javascript:void(0)", :class => "advanced-search-add-row advanced-search-add-bool-row", "data-type" => "boolean" %></li>
<li><%= link_to I18n.t("advanced_search.type.controlled_value"), "javascript:void(0)", :class => "advanced-search-add-row advanced-search-add-enum-row", "data-type" => "enum" %></li>
</ul>
</div>


The javascript for creating the row:

$advancedSearchContainer.on("click", ".advanced-search-add-row", function(event) {
event.stopPropagation();
event.preventDefault();

var index = $("input[id^='v']", $advancedSearchRowContainer).length;

var adding_as_first_row = false;
if (index == 0) {
adding_as_first_row = true;
}

while ($(":input[name='f"+index+"']", $advancedSearchContainer).length > 0) {
index += 1;
}

addAdvancedSearchRow(index, $(this).data("type"), adding_as_first_row, {});

// hide the drop down menu after clicking an option
$(this).closest(".dropdown-menu").siblings(".advanced-search-add-row-dropdown").trigger("click");
});

Answer

getElementsByClassName returns HTMLCollection.

So change the line:

document.getElementsByClassName("advanced-search-add-text-row").click();

to:

document.getElementsByClassName("advanced-search-add-text-row")[0].click();

Instead, using jQuery you can write:

$(".advanced-search-add-text-row").trigger('click');