How to show all parent and child values in one select dropdown in javascript

北城以北 提交于 2021-01-28 11:44:58

问题


Hi guys i have topic table where i am storing all topics along with sub topics..and subtopic id i am storing in parent_id column.

Here is my db structure:

i am getting all topics in dropdown like this. But i would like to show my subtopics list like this

fractions 
fractions>introductions to fractions
fractions>Fractions as division

So far i have create childTopics functions in my model:

public function childTopics()
{
    return $this->hasMany(Topic::class, 'parent_id');
}

And i used in my create function in controller like this:

 $topics = Topic::with('childTopics')->parent()->get(['id', 'name']);
   

Here is my ajax call where i am showing all my topics in one place.

function getSubjectsTopics(subject_id)
{
    if(subject_id) {
        loading_show();
    axios.get("/master/topic/get-topic-by-subject-id/" + subject_id)
        .then(function(response) {
            var optionHtml = '<option value="0">Parent</option>';
            if(response.data.status) {
                $.each(response.data.subject_topics, function(i,v) {
                    optionHtml += `<option value="${v.id}">${v.name}</option>`;
                 });
            }

            $("#ddl_topic_type").html(optionHtml).attr('disabled', false).select2();
            loading_hide();
        })
        .catch(function(error) {
            loading_hide();
            console.log(error);
            Swal.fire({
                type: 'error',
                title: 'Oops...',
                text: 'Something went wrong!'
            })
        })
    } else {
        $("#ddl_topic_type").attr('disabled', true);
    }
}

In this ajax call itself i would like to show my subtopics with parent topic name itself.

Can anyone help me how can i show it. Thanks in advance.

Edit: Here is my response output

Here is functions to get topics based on subject:

public function getTopicsBySubjectID($subject_id)
{
    $topics = Topic::where("subject_id", $subject_id)->get(['id', 'name']);

    return response()->json(['status' => 'success', 'subject_topics' => $topics], 200);
}

回答1:


You can use optGroup to group your sub option in a group where optGroup will have the name of the subject name .Your current ajax response show all subject_topics together so if the first value fractions is subject name you can put condition inside each loop to check if i(position) is 0 then append optgroup.

Demo code :

var response = {
  'data': {
    'status': 'success',
    'subject_topics': [{
      'id': 0,
      'name': 'fractions'
    }, {
      'id': 1,
      'name': 'fractions of booksss of subject'
    }, {
      'id': 2,
      'name': 'fractions of sub'
    }]

  }
};
var optionHtml = '<option>Select....</option>';
if (response.data.status) {
  $.each(response.data.subject_topics, function(i, v) {
    if (i == 0) {
      optionHtml += `<optGroup label="${v.name}">` //considering 1st id is subject name
    } else {
      optionHtml += `<option value="${v.id}">${v.name}</option>`;
    }
  });
  optionHtml += `<optGroup>` //close optgroup
}

$("#ddl_topic_type").html(optionHtml).attr('disabled', false).select2();

//or
var response = {
  'data': {
    'status': 'success',
    'subject': 'somesubjectname', //return subject name as well
    'subject_topics': [{
      'id': 0,
      'name': 'fractions'
    }, {
      'id': 1,
      'name': 'fractions of booksss of subject'
    }, {
      'id': 2,
      'name': 'fractions of sub'
    }]

  }
};
var optionHtml1 = '<option>Select....</option>';

if (response.data.status) {
  //append subject name
  optionHtml1 += `<optGroup label="${response.data.subject}">`
  $.each(response.data.subject_topics, function(i, v) {
    optionHtml1 += `<option value="${v.id}">${v.name}</option>`;
  });
  //subject name ..
  optionHtml1 += `<optGroup>`
}

$("#ddl_topic_type1").html(optionHtml1).attr('disabled', false).select2();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css">
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>
<select id="ddl_topic_type"></select>
<select id="ddl_topic_type1"></select>


来源:https://stackoverflow.com/questions/65335424/how-to-show-all-parent-and-child-values-in-one-select-dropdown-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!