$(".chosen-select").on('change', function(evt, params) {
var options = $('#selectID').val();
var values = options.join();
console.log(values);
<form action="http://httpbin.org/post" method="post">
<select id="selectID" multiple class='chosen-select'></select>
</form>
So I'm trying to get the selected options from chosen jquery into a specific format to be used in a query ("NAME IN (" + values + ")";). But in order for me to do that I need the values of my variables to be in the format of 'option1','option2'. But when I do console.log(value): Im getting my output as 'option1, option2'.
Related
I am using select2 box for language selection. I am not able set selected values for edit language page
I tried to set manually all the values from array to select2
$(window).bind("load", function() {
$('#language').select2(); //key , value pair of language map
var value = $('#langList').val(); // hidden list of id "[3,1,7]" value
var result = value.substring(1, value.length-1);
var res = result.split(","); // array of ids
$('#language').val([res[0],res[1],res[2]]);
$('#language').trigger('change');
});
Wanted to set all the values to select2. Please find html code below:
<label for="language">Work Language:</label>
<input type='hidden' value="${languageList}" id="langList"/>
<select name="language" id="language" multiple="multiple">
<c:forEach items="${languageMap}" var="lang">
<option value="${lang.key}">${lang.value}</option>
</c:forEach>
</select>
I my form I have few dropdowns chained between them with AJAX.
This is how I a populating them
function getleaseterm() {
//get a reference to the select element
$select = $('#id_leaseterm');
//request the JSON data and parse into the select element
var l_id = ($("select[name='lease'] option:selected").attr('value'));
//var l_id = 13;
l_url = "/api/get_leaseterm/"+l_id+"/";
$.ajax({
url: l_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1">Select term </option>');
//iterate over the data and append a select option
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
}
And this is the control
<select class="select" id="id_leaseterm" name="leaseterm">
<option value="-1" selected="selected">-----</option>
</select>
It all works , I am changing values in my dropdowns and options of other dropdowns are updated.So I can select the relevant value.
The problem is when I Save the for - the form gets not the value that I have put there but the default value that was there before any manipulation of Ajax have been done.
Also when I do view source I see in the code is default value and not what was selected from what I have build with AJAX.(Even that on the screen I do see the correct values in the select options...)
My backend is Django .
My Django form formatted in following way.
class MassPaymentForm(forms.ModelForm):
leaseterm = forms.ModelChoiceField(queryset=LeaseTerm.objects.none()) # Need to populate this using jquery
lease= forms.ModelChoiceField(queryset=Lease.objects.none()) # Need to populate this using jquery
class Meta:
model = LeasePayment
fields = ['lease', 'leaseterm', 'payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description']
What could be the problem ? And any idea how to solve it?
I have figured out what was the problem
it is in my form file
If I keep the lease and leaseterm fields just in Meta class that it doesn't reset those fields on submit any more . And all my logic finally works as designed.
class MassPaymentForm(forms.ModelForm):
class Meta:
model = LeasePayment
fields = ['lease', 'leaseterm', 'payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description']
I used select2 for my input select and set multiple is true. In my case, I tried to get text array from multiple selected values using javascript function.
This is my javascript and html input :
<script type="text/javascript">
function getRoles(val) {
$('#role-cm_role_text').val('');
var data = $('#role-cm_role').select2('data')[0].text;
$('#role-cm_role_text').val(data);
$('#role-cm_role').on('select2:unselecting', function (e) {
$('#role-cm_role_text').val('');
});
}
</script>
<select id="role-cm_role" class="form-control" name="Role[CM_ROLE][]" multiple size="4" onchange="getRoles(this.value)" style="display:none">
<option value="INQUIRY">CM Inquiry</option>
<option value="SUPERVISOR">CM Supervisor</option>
<input type="hidden" id="role-cm_role_text" class="form-control" name="Role[CM_ROLE_TEXT]">
So if I try to select one value, the result of CM_ROLE_TEXT is same with CM_ROLE. But if I try to select multiple values, the resul of CM_ROLE_TEXT is just get a first value of CM_ROLE.
Result if try to select multiple values :
[CM_ROLE] => Array
(
[0] => INQUIRY
[1] => SUPERVISOR
)
[CM_ROLE_TEXT] => CM Inquiry // I need the result of CM_ROLE_TEXT is same with the result of CM_ROLE
Anyone can help me how to fix my issue? Thank you
From what i can see, the problem is with this line right here
var data = $('#role-cm_role').select2('data')[0].text;
As you are only selected the 1st [0] of the array only. So this is indeed the expected behaviour. So to get all the results text in the array, you can perhaps do something like this
var data = $('#role-cm_role').select2('data').map(function(elem){
return elem.text
});
then you will have an array of all the strings selected. Read about map function here : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Here is a live example : https://jsbin.com/qujocujuko/edit?html,js,output
I have INPUT fields on my form which I want to collect the data input from them and store them in an ARRAY to then feed into a SELECT OPTION This is what I have so far, when it is used in the form it doesnt pick up the value from the INPUT boxes and the SELECT shows 2 empty rows, but has an ID against those rows as when I ouput the SELECT into another INPUT further on in my form it will show either 0 or 1.
How can I get the value input from the INPUT into the SELECT, also how can I then show the SELECTED option afterwards?
var MySelectOptions = [document.getElementById("inpbox1").value, document.getElementById("inpbox2").value];
$.each(MySelectOptions, function(key, value) {
$('#theselectbox').append($("<option/>", {
value: key,
text: value
}));
});
this is how I output from the SELECT, I would normally use the second example, but I don't know how to get the SELECTED Option within the code above
$(function() {
$("#theselectbox").change(function(){
var CustomerName = document.getElementById("theselectbox").value;
$('#customername').val(CustomerName);
});
});
How I normally get the SELECTED Option
$(function() {
$("#theselectbox").change(function(){
var CustomerName = $('option:selected', this).attr('theselectoption');
$('#customername').val(CustomerName);
});
});
You can append a new option with a value to select box as:
$('#theselectbox').append('<option value="'+inputValue+'">'+inputValue+'</option>');
And, you can show the selected option by using its value as:
$('#theselectbox').val(inputValue);
// Here you have the list of inputs, from which you will get values
// I will use classes, you can use ids
var inputs = ["input1", "input2"];
// The select to which you will paste the values
var sselect = $(".select-class");
for(var i = 0; i < inputs.length; i++){
var e = $("." + inputs[i]);
sselect.append("<option>"+ e.val() +"</option>");
}
// Now you can just put value to select
sselect.val("selected_value");
How select value from input
<input type="text" class="js-svalue" placeholder="Select value">
Now js
var input = $(".js-svalue");
input.on("change", function(){
sselect.val(input.val());
});
I'm using JavaScript to get the selected value of a drop list in MVC 4 but have an issue I think is caused by the HTMLHelper.
CONTROLLER - to populate droplist
private string PopulateStandard(object selectedValue = null)
{
var query = db.Database
.SqlQuery<StandardModel>(
"SELECT * FROM [DBO].[GetStandards] ('" +
User.Identity.Name + "', '" + DateTime.UtcNow + "')")
.ToList();
ViewBag.Standard = new SelectList(query, "Standard", "Standard", selectedValue);
try { return query[0].Standard; }
catch { return ""; }
}
VIEW
The view has this section for the drop list. Please note the inclusion of "All". I think this is the problem. That puts a first row atop the drop list saying "All" with a null value. I want that. So far so good (so what)
#Html.DisplayNameFor(m => m.Standard)
#Html.DropDownList("Standard", "All")
JAVASCRIPT
It's a long story, but I have other code that requires me to get the value of the drop list using JavaScript, so I'm doing it like this:
var e = document.getElementById("Standard");
var sStandard = e.options[e.selectedIndex].value;
PROBLEM
If no value was chosen, then I should get the first row, which would be "All" for text or "" for value. Instead, I'm getting the second row, which is the first one with data as populated from the database.
Is the HTML helper causing me to not get the first row? Or is my JavaScript off?
EDIT - to show ViewSource on drop list
These are the first few lines of the rendered list
<select id="Standard" name="Standard"><option value="">All</option>
<option value="2S">2S</option>
<option value="Aero">Aero</option>
#Html.DropDownList("Standard", "All")
here "All" is option label. so you do not get this as value.