Populating HTML Select dropdown from a database in Meteor - javascript

I've not been able to find the correct answer on this so seeing if the stackOverflow crew can help. I know it seems like a common thing, but this example is a little different from what I've found whilst searching.
I have a meteor template that has a select dropdown in it with the relevant part as such:
{{#each phoneNumber}}
<li>
<input id="{{this._id}}" type="text" name="phoneNumberItem" placeholder="Phone number here" value="{{number}}">
<select id="{{this._id}}" name="type">
<!-- go through collection and see which is selected there, mark it as selected here so they match -->
<option selected="{{selectedOrNot}}" name="selection">Work</option>
<option selected="{{selectedOrNot}}" name="selection">Home</option>
<option selected="{{selectedOrNot}}" name="selection">Mobile</option>
<option selected="{{selectedOrNot}}" name="selection">Office</option>
<option selected="{{selectedOrNot}}" name="selection">Fax</option>
<option selected="{{selectedOrNot}}" name="selection">Other</option>
</select>
<input id="{{this._id}}" type="button" class="remove" value="X">
</li>
{{/each}}
The complete code for the helper that selectedOrNot is in is shown as such:
Template.addPhoneNumber.helpers({
//the full list of phone numbers in the collection, so we can loop through them in the template and draw them into the form
'phoneNumber': function() {
return newOrgPhoneNumbers.find();
},
//let's us choose which of the dropdown items are selected
'selectedOrNot': function(event){
var collectionType = newOrgPhoneNumbers.findOne(); //get the type from the collection (EG: Home, Mobile, Fax, etc)
var typeFormName = $('[name="selection"]').val(); //get the data from the form (EG: Home, Mobile, Fax, etc)
//When drawing the select dropdown, see if there's a match and return selected if so
if(collectionType.type === typeFormName){
console.log ('selected!');
return 'selected';
}
}
});
What I'm trying to do:
I have data stored in a collection called newOrgPhoneNumbers.
This data includes a "type" that has either "Home", "Mobile", "Work", etc in it.
When I draw the select dropdown in the template, I want the selected to be chosen for the option that matches the "type" in the newOrgPhoneNumbers collection. Note that there are multiple select dropdowns, one for each item in the data collection. So there may be say, 6 phone numbers in the form, each with its own ID taken from the collection it's drawn from.
For the purposes of this example, the collection data has "Home" as the "type", so I want it to draw with Home being selected in the select dropdown.
Now I can see what's wrong here. The typeFormName is taking the VALUE of the selector dropdown, which is always "Work" by default.
How can I rework this to make a match in my If condition and return a "selected" when I get a match? I think I need to retrieve a value from the template that matches the value in the collection but the selector dropdown doesn't have such a value (as it's always "work" when drawn).
I've spent about 5 hours today on this with various logic attempts so it's time to ask. Any help is greatly appreciated. Rob

Instead of this
//let's us choose which of the dropdown items are selected
'selectedOrNot': function(event){
var collectionType = newOrgPhoneNumbers.findOne(); //get the type from the collection (EG: Home, Mobile, Fax, etc)
var typeFormName = $('[name="selection"]').val(); //get the data from the form (EG: Home, Mobile, Fax, etc)
//When drawing the select dropdown, see if there's a match and return selected if so
if(collectionType.type === typeFormName){
console.log ('selected!');
return 'selected';
}
}
try this
//let's us choose which of the dropdown items are selected
'selectedOrNot': function(event){
var typeFormName = $('[name="selection"]').val(); //get the data from the form (EG: Home, Mobile, Fax, etc)
//When drawing the select dropdown, see if there's a match and return selected if so
if(this.type === typeFormName){
console.log ('selected!');
return 'selected';
}
}
make sure you're getting correct values for both by console.log
EDIT
try following code
{{#each phoneNumber}}
<li>
<input id="{{this._id}}" type="text" name="phoneNumberItem" placeholder="Phone number here" value="{{number}}">
<select id="{{this._id}}" name="type">
<!-- go through collection and see which is selected there, mark it as selected here so they match -->
<option value="Work">Work</option>
<option value="Home">Home</option>
<option value="Mobile">Mobile</option>
<option value="Office">Office</option>
<option value="Fax">Fax</option>
<option value="Other">Other</option>
</select>
{{setDropdownValue}}
<input id="{{this._id}}" type="button" class="remove" value="X">
</li>
{{/each}}
in the helpers
setDropdownValue: function(){
$("#"+this._id).val(this.type);
}

Huge thanks to #Sasikanth. This is what he's helped me with and it's provided in full below to help others / future reference.
Meteor Template:
{{#each phoneNumber}}
<li>
<input id="{{this._id}}" type="text" name="phoneNumberItem" placeholder="Phone number here" value="{{number}}">
<select id="sel_{{this._id}}" name="type">
<!-- go through collection and see which is selected there, mark it as selected here so they match -->
<option value="Work">Work</option>
<option value="Home">Home</option>
<option value="Mobile">Mobile</option>
<option value="Office">Office</option>
<option value="Fax">Fax</option>
<option value="Other">Other</option>
</select>
{{setDropdownValue}}
<input id="{{this._id}}" type="button" class="remove" value="X">
</li>
{{/each}}
Meteor Helper:
Template.addPhoneNumber.helpers({
//the full list of phone numbers in the collection, so we can loop through them in the template and draw them into the form
'phoneNumber': function() {
return newOrgPhoneNumbers.find();
},
//This will take the value of the database item's "type" field and send it back to the select html element.
//It's using the sel_ prefix to separate it from the other items with the same id in the template so they don't receive the data by accident.
'setDropdownValue': function(){
$("#sel_"+this._id).val(this.type);
}
});

Related

Using two different SELECT elements depending on input value, but only second one in page posts correctly

I have an inventory form which I have been asked to improve. The user counts product and enters the new count into the form. Then, depending on whether the input is positive or negative, a select box appears with the list of reasons for the discrepancy. The UI is working perfectly, but the reason code will only pass for whichever select element is listed last.
Basically this works to ensure the user is entering negatives correctly so my default is to have the SELECT element for the negative reason second since it will be the one to work. I would appreciate any suggestions for a better approach.
$(document).ready(function () {
if ($("#invAmt").val()=='') {
$("#plus").hide();
$("#minus").hide();
}
//return false;
$(document).on('change', '#invAmt', function() {
if ($("#invAmt").val()>='1') {
$("#plus").show();
$("#minus").hide();
} else {
$("#plus").hide();
$("#minus").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="invDec">Enter Amount of Units to Adjust (+/-): </label>
<input name="invAmt" id="invAmt" style="width:50px" >
</div>
<label for="title">Reason for Adjustment:</label>
<div class="plus">
<select class="custom-select custom-select-md" name="reason" id="plus" style="width:370px">
<option value="">--- Select Reason ---</option>
<option value="30">Returned Product</option>
<option value="50">Other (explain in notes)</option></select>
</div>
<div class="minus">
<select class="custom-select custom-select-md" name="reason" id="minus" style="width:370px">
<option value="">--- Select Reason ---</option>
<option value="70">Recount (lost)</option>
<option value="75">Dumped / Died)</option>
<option value="90">Diseased / Pest</option>
<option value="65">Overgrown</option>
<option value="95">Overstock</option>
<option value="98">Loaned Out</option>
<option value="100">Other (explain in notes)</option></select>
</div>
if you want to select multiple options from your drop downs you need to add the "multiple" attribute to your two select statements. Like this:
<select class="custom-select custom-select-md" multiple name="reason" id="plus" style="width:370px">
also, you need to add a submit button.
If you are trying to get just one option for + and one option for - you need to use different names for each of your select boxes. If they are both name='reason' the last one will overwrite the first one. Try:
name='negReason'
name='posReason'

forms select2 POST is empty

I'm seeking guidance to get me going in the right direction. My professor is at a loss. I'm having issues with the POST in my form for the select2 multiple fields. I have a Yes/No flag, that determines which select 2 select option to show.
The javascript below works great for the show/hide.
$(document).ready(function () {
$('#option').change(function () {
$this = $(this)
$('.select_box').each(function () {
$select = $('select', this);
if ($select.data('id') == $this.val()) {
$(this).show();
$select.show().select2();
} else {
$(this).hide();
$('select', this).hide();
}
});
});
});
My form has a Yes/No/NA option, which dictates what select 2 box to show using the javascript above.
<select name ="option" class="form-control " id="option">
<option value="1"> Yes</option>
<option value="0"> No</option>
<option value="2"> N/A</option>
</select>
My form POST is handled with the general POST option as shown below:
<form action = "{% url 'final' %}" form method = "POST">
Inside my form I have the .select_box div class. The select 2 option gives the correct fields and populates the multi-select correctly.
<div id = "div_yesselect" class="select_box">
<script src= "{% static '/accounts/option_select2.js' %}" type="text/javascript"></script>
<select data-placeholder="Please select your course(s)?" data-id="1" class="js-example-basic-multiple" multiple="multiple" id = "id_courseselect" value = "{{course.id}}" style="width: 1110px" >
{% for course in courses%}
<option value="{{course.name}}" name = "courseid" >{{course.name}}</option>
{% endfor %}
</select>
The POST goes through when the user hits the Submit Button. I can verify all the fields in my form except for the select2 option when a user selects multiple options, or a single option.
<button class="btn btn-primary " type="submit">Submit</button>
In my final view when trying to request the POST on the select2 name it returns an empty set, but everything else in the form returns the correct value. Why doesn't the select2 option post correctly?
courselist = request.POST.getlist('courseid')
Form POST in Django depends on name attributes. When you request courseid, it's going to look for an element with name attribute equal to courseid, meaning:
courselist = request.POST.getlist('courseid')
needs a matching element, for example
<select name="courseid" multiple>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
You need to add name attribute to your select element and it should work.

Angular 2: Two select Boxex "Exchange" Data

I´d like to build 2 select fields. in the first I want to display all my members (objects in my database):
<select multiple size="15" name="members" id="members">
<option *ngFor="let member of members" [value]="member.$key">
{{member.lastName}} {{member.firstName}}
</option>
</select>
In the second I want to display all members of the current team (selected from url param id)
<select size="15" name="assignedMembers" id="assignedMembers">
<option *ngFor="let assignedPlayer of team.assignedPlayers"[value]="assignedPlayer.$key">
{{assignedPlayer.lastName}} {{assignedPlayer.firstName}}
</option>
</select>`
How can I change now the values from the first to the second list and vice versa to be able to save the assignedMembers later?

Sending both the value and key of an option box as parameters?

I want to send both the value and key of the option box when I submit a form. I feel like this should be pretty simple, but I'm unsure how to do it. Below is a snippet from my form to demonstrate what I'm referencing:
<form name='form' onSubmit="return checkForm();" action="../servlet/AccountRequest">
<select name="type1">
<option value="1">Option A</option>
<option value="2">Option B</option>
</select>
<br/><input type="button" id="Submit" onclick="checkForm(this.form)" value="Request" />
<input type="reset" value="Cancel"/>
</form>
​
In a normal scenario, if I selected "Option A" in the drop-down box, I would want to send the value, or "1". However, I want to actually send the value AND key of the selection, in this case both "1" and "Option A".
In my case, I call a checkForm() JavaScript function that validates form input (there are other fields, like First Name, Last Name, Email Address, and Password), which then forwards the parameters to a Java class (AccountRequest). I'm sure there is a way to store the key as a variable when the "Request" button is clicked, I just don't know how.
Any help would be much appreciated!
You could play with a jSON representation of your data:
<select name="type1">
<option value="{'1':'Option A'}">Option A</option>
<option value="{'2':'Option B'}">Option B</option>
</select>
It might not be the approach you were expecting, but you could send the key/value pair as your value and parse it when you receive it server-side.
<select name="type1">
<option value="1,Option A">Option A</option>
<option value="2,Option B">Option B</option>
</select>
In HTML, this is impossible: the data contributed by a select element is defined to be the value attribute of the selected option, when present (otherwise the content of the selected option element).
In JavaScript, it would be pretty easy, once you have decided how the content (“key” in your description) should be passed. At the simplest, you could append the content to the value attribute, with some separator between the strings; then you would have to parse that server-side, but that would be simple too.
However, it is part of the very idea of option elements that the content is the visible string in the user interface, understandable to the user, and the value attribute is the machine-readable easily processable data. In good design, they are kept as separate, not combined; the server should only need the data from the value attribute; otherwise there is a design flaw that should be fixed.
You could add this code to get the text of your selected <option> tag in your checkform function:
var select = document.getElementsByName("type1")[0]; // get select element - simpler if it has an ID because you can use the getElementById method
var options = select.getElementsByTagName("option"); // get all option tags within the select
for (i = 0; i < options.length; i++) { // iterate through all option tags
if (options[i].value == select.value){ // if this option is selected
var key = options[i].innerHTML; // store key of selected option here
}
}
DEMO, which tells you the key that's selected
Use a compound value, then parse it out on the server:
<option value="1_A">Option A</option>
you can send the value with an input type hidden
1.-choose the default value:
<input type="hidden" id="theValue" name="type1Value" value="Option A"/>
2.-add onChange function to your select, which changes previous hidden value
<select id="type1" name="type1" onChange="updateValue()">
<option value="1">Option A</option>
<option value="2">Option B</option>
</select>
assuming you are using jQuery:
function updateValue(){
var value= $('#type1').find(":selected").text();
$('#theValue').val(value);
}
so the value of the select will be sent in type1Value variable, EASY!!
using React js
I want to get two values from the option at the same time
so, I use the Split method
var string = "0,1";
var array = string.split(",");
alert(array[0]);
I create a sting on option
const getKioskSelectedUsageType=(e)=>{
let sl = e.target.value
let array = sl.split(",")
console.log("check :- ",array[1] )
}
<select
id=""
className="form-control"
value={kioskSelect}
aria-label="kioskSelect"
name="kioskSelect"
title="kioskSelect"
onChange={(e) => getKioskSelectedUsageType(e)}
style={{ color: "#495057" }}
>
<option value="">Select Kiosk</option>
{kioskConfiData.map((item, i) => {
return (
<React.Fragment key={i}>
<option value={`${item.kioskid},${item.language}`}>
{item.location}
</option>
</React.Fragment>
);
})}
</select>

select and input copied into one input for posting

First off sorry for a re-post, I voted to delete my old post because I'm asking for help on the code now, not just which way is the better route. Any my code has changed several times
On my page there is a drop down to select a country, dynamically loaded from a db. Once the user selects a country two things can happen. 1) If they select Canada or the US a second drop-down appears and the user can select a region. 2) If the user selects any other country it creates an input box so that the user can type the region instead. This all works fine.
Now there is a third input which takes the province/state value so it can be posted. There are only two of us who will use this form so I'm not worried about JavaScript being turned off in the browser.
My issue is that when the user first selects the Canada/US and a region, nothing is filled into the third input unless they change the country selection. However, if they select a country other than Canada/US and have to type the region, it works as expected.
Here is an example of the issue: http://jsfiddle.net/owalsh/BQXZA/3/
If anyone can tell me why I'd appreciate it, thanks
Working here: http://jsfiddle.net/5A4v4/11/
HTML:
<form id="customer_bill_add_post" name="customer_bill_add_post">
<select id="country" name="country">
<option value="0">Select a country</option>
<option value="CA">Canada</option>
<option value="US">United States</option>
<option value="OT">Other</option>
</select>
<select id="province_select" name="province_select">
<option value="0">Select a Province</option>
<option value="AB">Alberta</option>
<option value="AL">Alabama</option>
</select>
<input type="text" id="province_input" name="province_input">
<input type="text" id="province" name="province" />
</form>
Jquery: code (there was some extra change event binding going on) you can prettify it.
$(function(){
//initially hide the textbox
$("#province_input").hide();
$("#province_select").hide();
$('#country').change(function() {
if($(this).find('option:selected').val() == "CA"){
$("#province_select").show();
$("#province_input").hide();
} else if($(this).find('option:selected').val() == "US"){
$("#province_select").show();
$("#province_input").hide();
} else {
$("#province_input").show();
$("#province_select").hide();
}
});
$('#country, #province_select, #province_input').bind("change", function() {
if($('#country').find('option:selected').val() == "CA"){
document.customer_bill_add_post.province.value = document.customer_bill_add_post.province_select.value;
} else if($('#country').find('option:selected').val() == "US"){
document.customer_bill_add_post.province.value = document.customer_bill_add_post.province_select.value;
} else {
//alert('foo');
document.customer_bill_add_post.province.value = document.customer_bill_add_post.province_input.value;
}
});
});
Cheers,

Categories

Resources