Get selected item value from select2 dynamically created item in code behind - javascript

I'm using bootstrap select2 control with dynamic item creation
function pageLoad(sender, args) {
$('select').select2({
tags: true
});
$("#btn-add-state").on("click", function() {
var newStateVal = $("#new-state").val();
// Set the value, creating a new option if necessary
if ($('select').find("option[value='" + newStateVal + "']").length) {
$('select').val(newStateVal).trigger("change");
} else {
// Create the DOM option that is pre-selected by default
var newState = new Option(newStateVal, newStateVal, true, true);
// Append it to the select
$('select').append(newState).trigger('change');
}
});
}
I tried this get value but it always returns null!
cmd.Parameters.AddWithValue("#company", txt_car_company.Value);
I also tried to set the value in an ASP hidden field but it also returned null
<select id="txt_car_company" runat="server" class="select-single select2-hidden-accessible" data-live-search="true" data-select2-id="txt_car_company" aria-hidden="true" required="required">
<option value="Audi">Audi</option>
</select>
<asp:HiddenField ID="hcarcompany" runat="server" />
<script>
$('#txt_car_company').on('change', function () {
$('#<%=hcarcompany.ClientID%>').val($(this).val());
}
</script>

Related

Get id and a field value in EasyAutocomplete plugin

Using easyAutocomplete plugin, I autocomplete an input field and take the selected value and display them on a dropdown .
What I want to do, is have a hidden field that would have the id of the value.
My JSON File returns something like this :
{ "name": "Emily"
"id" : 1
"jobData": [
{
"id":1
"loc":"AL"
},
{
"id":2
"loc":"BG"
}
]
Once I select Emily from my users, my dropdown gets filled with Locations of her job.
How do I also save the Id of the location in a hidden field so that I can send it to my controller?
This is my JS function:
function AutoCompleteS() {
$("#basics").keyup(function(e) {
this.query = e.target.value;
var options = {
url: function(query) {
return "/getUser/"+ query
},
getValue:"name"
list: {
onClickEvent: function() {
var value = $("#basics").getSelectedItemData();
function toArray(value){
return value.loc;
}
var allLocations=value.jobData.map(toArray);
$.each(allLocations,function(i,p){
$('#select').append($('<option></option>').val(p).html(p));
})
}
}
};
$('#basics').easyAutocomplete(options);
});
}
How do I get and pass the id ?
EDIT:
html code:
<label for="client1" class=" control-label">First Client</label> <input type="text" name="client" value="" class="form-control input-lg " id="basics"/>
<label for="sel1">Select location:</label>
<select class="form-control input-lg" id="select" >
<option></option>
<input type="text" class="hidden" />
</select>
easyAutocomplete issues:
Your code should be more like this (see remote data source example) - i.e. you should only call easyAutocomplete once:
$("#basics").easyAutocomplete({
url: function(query) {
return "/getUser/" + query;
},
getValue: "name",
list: {
// ...
}
});
HTML issues:
Move the input outside the select, and give them both names (so the values can be submitted to server):
<select class="form-control input-lg" id="select" name="location">
<option></option>
</select>
<input type="text" class="hidden" name="job-id" id="job-id">
To set the value of the hidden field when the select value changes, you need a change handler:
function updateSelect(jobData) {
// Reset options:
$("#select")
.empty()
.append(new Option());
// Add locations:
jobData.forEach(function(job) {
$("#select").append(new Option(job.loc));
});
// Handle dropdown change:
$("#select")
.off("change")
.on("change", function() {
// Reset job id (needed when user selects blank option at top of dropdown)
$("#job-id").val("");
var selectedLocation = this.value;
jobData.forEach(function(job) {
if (job.loc === selectedLocation) {
// Copy job id to hidden field:
$("#job-id").val(job.id);
}
});
});
}
Call updateSelect from your easyAutocomplete onClickEvent handler:
onClickEvent: function() {
var value = $("#basics").getSelectedItemData();
updateSelect(value.jobData);
}

How can I select Price range with Input provided in textbox in jquery?

I have one DropDownList which contains price range as depicted below
Up to 50L
50L to 1CR
1CR to 5CR
5CR to 10CR
I also have one textbox which allows users to put input price in textbox. Now I want whenever user provides some valid price money then selected item should be set as per given price. e.g. if I put 2345 or 543245 or 887 then DropDownList's selected item should be Up to 50L and if I put 8432321 then selected value should be 50L to 1CR. I have tried to put the following code for that but not working as per expectation.
Javascript Code:
jQuery(function ($) {
debugger;
$('#txtPrice').on('change', function () {
var value = parseInt(this.value, 10),
dd = document.getElementById('ddlPriceRange'),
index = 0;
$.each(dd.options, function (i) {
if (parseInt(this.text, 10) <= value) {
index = i;
}
});
dd.selectedIndex = index; // set selected option
});
});
.ASPX Code:
<asp:DropDownList ID="ddlPriceRange" runat="server" ClientIDMode="Static"/>
<asp:TextBox ID="txtPrice" runat="server" ClientIDMode="Static"/>
Output which is being produced with above given code is given below
I have made two minor changes to your logic.
I added the minimum value allowed for given range as the value attribute on the option elements. So instead of comparing the input value with the text of the option, you can compare it to the absolute value.
<option value="5000000">50L to 1CR</option>
Instead of observing the change event, I added the event on input event so that the dropdown is updated as the user types in the number.
jQuery(function($) {
$('#txtPrice').on('input', function() {
var value = parseInt(this.value, 10),
dd = document.getElementById('ddlPriceRange'),
index = 0;
$.each(dd.options, function(i) {
if (parseInt(this.value, 10) <= value) {
index = i;
}
});
dd.selectedIndex = index; // set selected option
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="ddlPriceRange">
<option value="0">Up to 50L</option>
<option value="5000000">50L to 1CR</option>
<option value="10000000">1CR to 5CR</option>
<option value="50000000">5CR to 10CR</option>
<option value="9007199254740991">Above 10CR</option>
</select>
<input type="text" id="txtPrice" value="0" />

Append options to select2

I have the following select:
<select id="street" name="client[street_id]" class="form-control select2" data-placeholder="Select or Insert The Street" style="width: 100%;">
#foreach($streets as $street)
<option value="{{ $street->id }}">{{ $street->name }}</option>
#endforeach
</select>
And the initialisation:
$(".select2").select2({tags: true});
Note that multiple has not been set to true. The problem is when I enter a new option (tag), first time will add the tag but second time will replace the first one in the list. So how can I add options in the select and keep them? (on each add I will make a request to server to save to db).
https://jsfiddle.net/8c7ujd4g/
I found this solution:
$('.select2').on("select2:select", function(e) {
// what you would like to happen
if(e.params.data.isNew){
$(this).find('[data-select2-tag="true"]').replaceWith($('<option selected>', { value : e.params.data.id })
.text(e.params.data.text));
$.ajax({
// ...
});
}
});
$(".select2").select2({tags: true,
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
isNew: true // add additional parameters
}
}
});

Issue with default selected option of a select list?

I am using knockout options binding and select2 plugin on a select list. Initially i do not want to select any option by default instead i want to show a text something like 'Select country..' and this text should be selected initially. For this i used knockout optionsCaption binding. It works fine, but if i apply select2 plugin on the select list the initial default text is not selected. Here my code:
HTML
<select data-bind="options: array, optionsCaption: 'All'" size="1">
</select>
JS
$('select').select2();
function VM(){
this.array =
['Afghanostan', 'Albania', 'Algeria', 'Argentina'];
}
ko.applyBindings(new VM());
I have created a JSFIDDLE also.
How to solve this issue ?
Try this code
$('select').select2({
placeholder: "ALL"
});
<select data-bind="options: array" size="1" style="width: 200px;">
<option><option>
</select>
See this link http://jsbin.com/ivetel/19/edit
It has to do with the fact that "All" has a value of "". From select2's source:
initSelection: function () {
var selected;
if (this.opts.element.val() === "") {
this.close();
this.setPlaceholder();
} else {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(selected){
if (selected !== undefined && selected !== null) {
self.updateSelection(selected);
self.close();
self.setPlaceholder();
}
});
}
}
As you can see, it shortcircuits if element.val() === ''. You would need to modify the source of select2 to work with an empty-value option.

Updating Textbox's info upon selecting listbox item using javascript

I'm trying to update Textbox's with the selected items info(properties). Can I get the selected Items Name instead of the Id, or in other words how can I get the properties of whats in my ViewData in the javascript upon selecting an item and then set it to a txtbox?
#Html.ListBox("ListBoxName", new SelectList((IEnumerable<Epic>)ViewData["selectedestimate"], "Id", "Name", "EstimatedTime"), new {#class = "ListBoxClass", #style = "height: 325px;"})
#Html.TextBoxFor(model => model.Name, new {#class = "TimeClass"})
<script type="text/javascript">
$(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
// get items properties and info so that the value can be set to a textbox
//set textbox value to Name of selected Value
$(".TimeClass").val(selectedid);
event.preventDefault(); // Stop the browser from redirecting as it normally would
$.get('#Url.Action("UserStoriesList", "Estimate")', { id: selectedid }, function (result) {
$('#stories').html(result);
});
});
});
</script>
A ListBox is like a DropDownList except that it allows for multiple items to be selected. It uses the same HTML tag (<select>) but it adds the multiple attribute. So when rendered your markup will look like this:
<select id="ListBoxName" name="ListBoxName" multiple="multiple">
<option value="id1">text 1</option>
<option value="id2">text 2</option>
<option value="id3">text 3</option>
...
</select>
So as you can see you have information about the id and the text inside the DOM. If you wanted to fetch some other information about the selected item you will need to send an AJAX request to the server and pass the selected id to retrieve it. So if you only wanted to show the text:
$(function() {
​$('.ListBoxClass option')​.click(function() {
if ($(this).is(':selected')) {
var selectedId = $(this).val();
var selectedText = $(this).text();
$('.TimeClass').val(selectedText);
...
}
});​
});
The click handler will run everytime the user clicks on an element in the listbox but the if condition will be satisfied only if he selected the item.

Categories