Reputation: 281
I have a collection_select
which allows a customer to select another customer. I also have a button which, when clicked, should trigger a javascript function that finds the string value of the customer selected, and adds it to a list on the page.
HTML:
<%= f.collection_select :id,
Customer.where(business_id: current_customer.business_id),
:id,
:full_name,
{ prompt: 'Select' },
{ id: "colleage-select", onChange: "renderColCal(this)" } %>
<button id="click-me" type="button">
<img src="https://cdn4.iconfinder.com/data/icons/basic-ui-elements/700/07_plus-128.png" alt="Add to Event" style="width: 50px"/>
</button>
<div>
<p>Meeting Participants:</p>
<ol id ="list">
</ol>
</div>
Javascript:
$(function (){
$("#click-me").click(function (e){
e.preventDefault();
var List = document.getElementById('list');
var name = document.getElementById('colleague-select').textContent; //this should get whatever name is currently in the collection_select
var entry = document.createElement("li");
entry.appendChild(document.createTextNode(name));
List.appendChild(entry);
return false;
});
});
However, this is not appending anything to my list. This function is successful when I make a test text node, i.e. entry.appendChild(document.createTextNode("test"));
so I know it's a problem with how I'm finding the customer name from the collection_select. What is the correct way to do this? Thanks
Upvotes: 1
Views: 424
Reputation: 1716
Why using vanilla javascript
when you already have jQuery
added to your project.
I would rewrite your javascript
code this way:
$(function (){
$("#click-me").click(function (e){
var list = $("#list") ;
var name = $("#colleague-select option:selected").text() ;
var entry = "<li>" + name + "</li>" ;
list.append(entry);
return false;
});
});
Upvotes: 2