Javascript Ruby on Rails

How to create a dependent dropdown in Ruby on Rails

How to create a dependent dropdown in Ruby on Rails?

In the form as is

<%=, Project.all.collect {|p| [,]},  {prompt: "Select"}, {class: 'form-control'}) %>
<%=, Tasks.all.collect {|t| [,]}, {}, {class: 'form-control'}) %>

and those fields generated HTML is

<select class="form-control" name="hour[project_id]" id="hour_project_id">
    <option value="">Select</option>
    <option value="1">Real Estate</option>
    <option value="2">Time Sheet App</option>

<select class="form-control" name="hour[task_id]" id="hour_task_id" disabled="">
    <option value="3">Developer</option>
    <option value="4">Design</option>
    <option value="6">Backend</option>

that’s it in the form, now JS, Ajax & controller

The JS / Ajax is

$("#hour_task_id").prop("disabled", true); // second dropdown is disable while first dropdown is empty
  	var project = $(this).val();
  	if(project == ''){
  		$("#hour_task_id").prop("disabled", true);
  		$("#hour_task_id").prop("disabled", false);
	    url: "/tasks",
	    method: "GET",  
	    dataType: "json",
	    data: {project: project},
	    error: function (xhr, status, error) {
	      	console.error('AJAX Error: ' + status + error);
	    success: function (response) {
	      	var tasks = response["tasks"];

	      	$("#hour_task_id").append('<option>Select Task</option>');
	      	for(var i = 0; i < tasks.length; i++){
	      		$("#hour_task_id").append('<option value="' + tasks[i]["id"] + '">' +tasks[i]["name"] + '</option>');

and in the controller into action

if params[:project].present?
    @tasks = Project.find(params[:project]).tasks
    @tasks = Task.all
if request.xhr?
    respond_to do |format|
        format.json {
            render json: {tasks: @tasks}

That’s it

Fool Dev

I didn't get trained by the school system like other kids, and when I did concentrate on learning, my mind was cluttered and locked by the programming of the system. © Huey Newton