forms select2 POST is empty - javascript

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.

Related

Getting selected values from multiselect in Laravel with multiple-select jquery plugin

I am using wenzhixin/multiple-select as it has select all option. I'm trying to get selected items ticked that were selected while creating the post.
This is what i have done but it doesn't work.
{{ Form::label('tags', 'Tags:') }}
<select name="tags[]" multiple="multiple" id="tags">
#foreach($tags as $tag)
<option value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
</select>
<script>
$("#tags").multipleSelect({
placeholder: "Tags please"
});
$('#tags').multipleSelect().val({!!json_encode($post->tags()->getRelatedIds() )!!}).trigger('change');
</script>
I would be thakful if anyone can help me.
At the end of the day, it's just an HTML select element. Given the name of tags[], this will submit within the form and be accessible through a controller as $request->get('tags') or if using the helper, then request()->get('tags');
Furthermore, you can pass the selected items to the next page in this way:
public function myFunctionToHandleTheForm()
{
$tags = App\Tag::all(); //for example, no idea what you use
$selectedTags = request()->get('tags');
return view('my.view', compact('selectedTags', 'tags');
}
Now, $tags will be a numerically ordered array (ascending) containing the ID's that were submitted from your form. You can set the defaults that were checked just like this:
{{ Form::label('tags', 'Tags:') }}
<select name="tags[]" multiple="multiple" id="tags">
#foreach($tags as $tag)
<option value="{{$tag->id}}" {{ in_array($tag->id, $selectedTags) ? 'selected="selected"' : null }}>{{$tag->name}}</option>
#endforeach
</select>
In the above, we're checking if the tag id is in the list of selected tag id's, and if so, we're setting the selected attribute. Your plugin will understand this and translate it correctly.

How to submit textbox value instead of "Other" to database

The following html code is part of a form, which sends the information to a java servlet and updates sql database. It is a dropdown menu. When the user selects "Other", javascript makes a textbox appear so that the user can specify more detail. However, when user presses submit button, in the database, it simply says "Other" instead of what the user entered in the text box. Help is appreciated, thanks!
<script type="text/javascript">
function showfield(name){
if (name == 'Other')
document.getElementById('div1').innerHTML = 'Please Specify: <input type="text" name="other" />';
else
document.getElementById('div1').innerHTML = '';
}
</script>
<select id="description" name="description" onchange="showfield(this.options[this.selectedIndex].value)" required>
<option disabled selected value> ---Select--- </option>
<option value="Accommodation">Accommodation</option>
<option value="Travel">Travel</option>
<option value="Meal Allowanced">Meal Allowances</option>
<option value="Flat Rate">Flat Rate Expenses</option>
<option value="Other">Other</option>
</select>
<div id="div1"></div>
I think the field you're checking on the server is "description" which is the name of your select. Which is indeed set to "Other" (this is the value of the selected option).
I would have written it a bit differently but with the current code you need to name the input with some other name and check that one on your server, or change the selected option value.
Example change for client code:
<select id="description" name="description" required>
<option disabled selected value> ---Select--- </option>
<option value="Accommodation">Accommodation</option>
<option value="Travel">Travel</option>
<option value="Meal Allowanced">Meal Allowances</option>
<option value="Flat Rate">Flat Rate Expenses</option>
<option value="Other">Other</option>
</select>
<div id="div1">
Please Specify: <input type="text" name="otherDescription" />
</div>
<script>
document.querySelector('#description').addEventListener('change', function (evt) {
var inputWrapper = document.getElementById('div1'),
input = inputWrapper.querySelector('input);
if (evt.target.value == 'Other') {
document.getElementById('div1').style.display = '';
} else {
document.getElementById('div1').style.display = 'none';
input.value = '';
}
});
</script>
The you need to check 'otherDescription' on the server.
Hope it helps
Assuming that all of this markup is contained within a <form> element that will be submitted to the server, you should be able to simply check to see if the value posted for description is "Other" and then read the posted value for other.
The code will vary depending on your server-side implementation.

Populating HTML Select dropdown from a database in Meteor

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);
}
});

Database value cannot get it to the Dropdownlist jQuery

In my database there's a column, name is Sequence & it consist of numbers(int). In my application's edit function I need to show that selected number in my jQuery dropdown list.
In my AJAX call I sent ProductId and get the specific row.
Html Control
<select class="form-control" id="drpsequence"></select>
My jQuery dropdown
$("#drpsequence option:selected").append($("<option></option>").val(msg._prodlng[0].Sequence).text(msg._prodlng[0].Sequence));
In the above code msg._prodlng[0].Sequence comes as selected number
I'm not sure what you are trying to do but it looks like you are adding an <option> tag into another <option> tag which is most likely not what you want.
If the returned value already exists as a selected option:
$("#drpsequence").val(msg._prodlng[0].Sequence).prop('selected', true);
Or, if you need to add an option:
var opt = $("<option>")
.val(msg._prodlng[0].Sequence)
.text(msg._prodlng[0].Sequence);
$("#drpsequence").append(opt);
Snippet example:
// foo --> select
$('#foo').val('baz').prop('selected', true);
$('#bim').click(function(){
$('#foo').append('<option id="boop" value="boop">boop</option>'); //<-- or loaded value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="foo">
<option>-- select --</option>
<option id="bar" value="bar">bar</option>
<option id="baz" value="baz">baz</option>
</select>
<button id="bim">Add an option</button>
You need to do one of following.
Either find that option and make that selected = true like this.
$("#sel option").each(function(i) {
if ($(this).val() == "Orange") $(this).attr("selected", "true");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</select>
Or if that option is not found then add and make that selected = true.
Like the one, which you had in your question.

How to add 1 select field onclick per click

I want to add a select field multiple times depending on the number of clicks the user makes. A toggle or show/hide function will only work for 1 select field.
How would I be able to do that?
e.g: 1 click = add 1 select field
<select name='' id='' class="">
<option value='en-us'>USA</option>
<option value='de-de'>Germany</option>
<option value='en-in'>India</option>
<option value='en-gb'>United Kingdom</option>
<option value='en-au'>Australia</option>
</select> <br>
<button id='add-countries'>add more countries</button>
I have prepared a sample html for this: http://jsfiddle.net/stan255/Wh274/
Something like this should do the trick. jQuery is used here for simplicity, but is not required.
<div id="template">
<select name='' id='' class="">
...
</select>
</div>
<button id='add-countries'>add more countries</button>
var $template = $('#template');
$('#add-countries').on('click', function () {
$(this).before($template.clone());
});
Here's an updated fiddle: http://jsfiddle.net/Wh274/3/.
Note that this does not account for assigning unique names to each <select> so you will need to add that logic or account for it on the server side.
if you could javascript (jQuery)
<script>
$(function(){
$('button#add-countries').click(function(){
newName = prompt('Please input new name');
newAttr = prompt('Please input new short name');
newItem = '<option value="'+newAttr+'">'+newName+'</option>';
$('select').append(newItem);
});
})
</script>
OR
<script>
$(function(){
$('button#add-countries').click(function(){
alert($('select option:selected').val())
});
})
</script>

Categories

Resources