Rails - Dynamic Select - Collection Select

前端 未结 2 1364
再見小時候
再見小時候 2020-12-07 23:52

I\'ve been trying to get some dynamic select functionality working, but despite many different tutorial i\'ve yet to get it to work. For ease of reading, i\'ve brought the c

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 00:30

    Vanilla JS Option

    This can be achieved with vanilla javascript only. Make sure that there is a route at companies/[id]/contacts.json which returns correct data.

    const select = document.querySelector('#company_id');
    select.addEventListener('change',function(e) {
      axios.get(`/companies/${e.target.value}/contacts.json`)
        .then((res) => {
          let contactSelect = document.querySelector('#contact_id')
          contactSelect.innerHTML = ''
          res.data.map((model, i) => {
            contactSelect.options[i] = new Option(model.name, model.id);
          })
        })
    });
    

提交回复
热议问题