Select2 clear 'x' button to set default value? - jquery-select2

Is it possible that pressing "x" button on Select2 dropdown with allowClear enabled set default (predefined) value?

Select2 allows you to associate the placeholder with an id other than a blank string.
$("select").select2({
placeholder: {
id: "the_predefined_value",
text: "The placeholder text"
}
});
So when you click on the "x", it will set the value to the_predefined_value and display the placeholder text. You are going to need an <option> with a value of the_predefined_value in order for this to work.

Use the onchange event. Check if the value is empty and set the value to whatever predefined is.
$("select").on("change", function (e) {
if($(this).val()==""){
$(this).val("predefined value");
}
});

The code i have written below will work for you,
$(".myselect").select2({
placeholder: "Select a option",
allowClear: true,
width: '100%'
}).off('select2:clear').on('select2:clear', (e) => {
$(e.currentTarget).val("predefined value");
});

Related

event while choosing a specific option with select2

Im using select2.js and i want to add an option that while choose that specific one, it will run a JS function or link to a web.
This is my js code:
jQuery(document).ready(function($) {
$(".client-select").select2({
placeholder: "choose client",
allowClear: true
});
});
You need to add select2:select listener which is similar to onChange,which will trigger function everytime you select a value from options.
Here it is,
jQuery(document).ready(function($) {
$(".client-select").select2({
placeholder: "choose client",
allowClear: true
});
$('.client-select').on('select2:select', function (e) {
var data = e.params.data;
if(data=='your_value'){
yourFunction();
}
});
});

jQuery Autocomplete wrong item in text box on select

When a user begins typing in the DRMCompanyName input text box, and autocomplete feature fires that displays both the company name and the company id. When the use clicks on a selection, the company name and id are to be placed into the DRMCompanyName text box and the id in the DRMCompanyId text box just below.
When the json results are returned from the controller, the code in the autocomplete ajax success function populates the drop down list by setting the label to be equal to the value (company name) plus the key (company id) being returned. Likewise the value is set to just the key (company id).
When the user selects a particular item, the label is supposed to go in the DRMCompanyName text box and the value in the DRMCompanyId. However, what winds up happening is the value gets placed in both.
I've scoured my code over and over and cannot find out why the label does not get placed in the DRMCompanyName field.
jQuery
$(function () {
$('#DRMCompanyName').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("compSearchByName", "AgentTransmission")',
type: 'GET',
dataType: 'json',
data: request,
success: function (data) {
response($.map(data, function (value, key) {
return {
label: value + " " + key,
value: key
};
}));
},
});
},
minLength: 2,
select: function (event, ui) {
console.log(ui);
$('#DRMCompanyName').val(ui.item.label);
$('#DRMCompanyName').text(ui.item.label);
if ($('#DRMCompanyId').text() == '') {
$('#DRMCompanyId').val(ui.item.value);
$('#DRMCompanyId').text(ui.item.value);
}
}
});
});
Here is a sample screen shot of the ui item from the select function above (the company name is blacked out for privacy). When I click on this particular item in the autocomplete drop down, 200014 gets placed in both the DRMCompanyName and DRMCompanyId fields.
Razor Markup
<div class="M-editor-field">
#Html.TextBoxFor(model => model.DRMCompanyName)
#Html.ValidationMessageFor(model => model.DRMCompanyName)
</div>
<div class="M-editor-label">
#Html.LabelFor(model => model.DRMCompanyId)
</div>
<div class="M-editor-field">
#Html.TextBoxFor(model => model.DRMCompanyId, new { maxlength = 10, title = "Start typing company name to activate DRM Company Name lookup. When DRM Company is found, select to fill in DRM Company ID and DRM Company Name fields." })
#Html.ValidationMessageFor(model => model.DRMCompanyId)
</div>
EDIT
After following the suggestion in the answer below, I modified the select function like so:
select: function (event, ui) {
console.log(tempResults[ui.item.value]);
$('#DRMCompanyName').val(tempResults[ui.item.value]);
$('#DRMCompanyName').text(tempResults[ui.item.value]);
if ($('#DRMCompanyId').text() == '') {
$('#DRMCompanyId').val(ui.item.value);
$('#DRMCompanyId').text(ui.item.value);
}
}
Based on the console.log readout, this accesses the correct value when the user clicks on the autocomplete item. However, it still places the value in both text boxes. What I can't understand, when I select Inspect Element, is that the correct value for DRMCompanyName actually is placed in the HTML, however it does not appear on the screen, only the id or value (as opposed to label).
You are setting label: value + " " + key which will of course add the id in the label.
When you set $('#DRMCompanyName').val(ui.item.label);, it's going to set what you concatenated in the $.map to the value.
One way to do this is to store a temporary result set from the data in the source ajax call to access later. With this temp set, you can now pull any object or key/value from it for use later.
When getting results, store a temporary list of the results.
var tempResults = [];
...
source: function (request, response) {
$.ajax({
url: '#Url.Action("compSearchByName", "AgentTransmission")',
type: 'GET',
dataType: 'json',
data: request,
success: function (data) {
tempResults = data;
response($.map(data, function (value, key) {
return {
label: value + " " + key,
value: key
};
}));
},
});
}
Then, on the select, you can now access the stored data and set values:
select: function (event, ui) {
event.preventDefault();
var name = tempResults[ui.item.value].value;
var id = tempResults[ui.item.value].key;
$('#DRMCompanyName').val(name);
$('#DRMCompanyName').text(name);
if ($('#DRMCompanyId').text() == '') {
$('#DRMCompanyId').val(id);
$('#DRMCompanyId').text(id);
}
}
EDIT
Forgetting one minor thing! Add this to the beginning of the select: function!
event.preventDefault();
By default, when selecting, the autocomplete will use the ui.item.value to populate the element that it's wired up with. Using event.preventDefault() will prevent the already wired up event handler to be called used within the autocomplete.
event.preventDefault() documentation.

Bootstrap datepicker is appending one by one for 2 fields at a time

In rails 3.2.9, I am using bootstrap's datepicker to display the date. In a single form, I need to display datepicker for 2 fields.
If I click first field then datepicker will popup. After that if I click 'tab' button then it will popup the second field's datepicker by appending to the first datepicker.
I need to display one datepicker at a time for particular field's onclick. If I click 'tab' button then first field's datepicker should be hidden and the second field's datepicker should popup.
Javascript is like below
function currentDatePicker(id){
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
$('#' + id).datepicker({
format: "yyyy-mm-dd",
onRender: function(date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
});
}
In views,
<%= f.input :start_date, :as=>:string, :label =>"Start Date", :required => false,
:input_html=>{:readonly=>true, :value=>#user.start_date.blank? ? "" : #user.start_date} %>
<%= f.input :end_date, :as=>:string, :label =>"End Date", :required =>false,
:input_html=>{:readonly=>true, :value=>#user.end_date.blank? ? "" : #user.end_date} %>
<script type="text/javascript">
currentDatePicker('user_start_date');
currentDatePicker('user_end_date');
</script>
Above I have added an image for more information. Please help me to solve this issue.
You can use different ids for date picker and then use event handling on ids. Hide manualy first datepicker when clicked on 2nd datepicker.
Or use autoclose attribute of datepicker.
$('#from').datepicker( { autoclose: true, startDate: today.getDate.toString() } );
$('#to').datepicker( { autoclose: true, startDate: today.getDate.toString() });
form and #to are ids.
I ran into the exact same issue. I solved it by doing the following:
var pickers = $(".datepicker")
.datepicker({
format: "mm/dd/yy",
autoclose: true
})
.on("show", function(e){
pickers.not(e.currentTarget).datepicker("hide");
});

jQuery UI Dropdown value doesnt change

I have a dropdown menu which contains 3 options. This menu is shown inside a modal jQuery UI dialog.
I can open open the dialog and choose one of the three options. The chosen option is stored in a variable. This works fine. But if I open the dialog again and choose another option, the variable does not change - it contains the value of first selection.
$("#button").click(function()
{
var diag = "<select id='diagDropdown'>"
+"<option>Option 1</option>"
+"<option>Option 2</option>"
+"<option>Option 3</option>"
+"</select>";
$(diag).dialog(
{title: "Choose Option"},
{autoOpen: "false"},
{modal: "true"},
{draggable: "false"},
{ buttons: {OK: dialogOK} });
function dialogOK()
{
var chosenOption=$("#diagDropdown option:selected").val().toLowerCase();
//working with chosen option
$(this).dialog("close");
});
Hope you can help me. Thanks in advance!
The problem is that each time you click on your element with id "button", you are creating a new dropdown with id "diagDropdown" in a new dialog.
Then your code :
var chosenOption=$("#diagDropdown option:selected").val().toLowerCase();
is always selecting the first dropdown with id "diagDropdown" in the DOM.
Try this :
<input type="button" value="click me" id="button"/>
<script type="text/javascript">
// On DOM ready
$(function() {
var dropdown =
$('<select id="diagDropdown"> ' +
'<option>Option 1</option>' +
'<option>Option 2</option>' +
'<option>Option 3</option>' +
'</select>');
// Create the dialog (only once)
dropdown.dialog({
title: "Choose Option",
autoOpen: false,
modal: true,
draggable: false,
buttons: {
"OK": function() {
var chosenOption=$('#diagDropdown option:selected').val().toLowerCase();
//working with chosen option
$(this).dialog('close');
}
}
});
// Bind click event : on click just open the existing dialog
$('#button').click(function() {
$('#diagDropdown').dialog('open');
});
});
</script>

In jqgrid search popup, when I add new field, the previously inserted value autocomplete is cleared

First of all, I introduce a text in the city input, city input is autocomplete(Jquery UI), and then I select a locality and press enter. Afterwards I add new field to search. When I press new field, jqgrid clears city field.
This is a part of my code.
{
name:'City',
index:'City',
width:220,
align:"center",
sortable:true,
editable:true,
edittype:'select',
editoptions:{
value:load_City
},
stype:'text',
searchoptions:{
dataInit:function(el){
$(el).autocomplete({
selectFirst:true,
source: "Codigo/Datos/localidades.php?autocomplete=verdadero"
})
},
sopt:['eq','ne','lt','le','gt','ge']
}
}
If I understand your problem correctly you should add should trigger change event after new value in autocomplete will be selected:
$(el).autocomplete({
selectFirst: true,
source: "Codigo/Datos/localidades.php?autocomplete=verdadero",
select: function (event) {
$(el).trigger('change');
}
});

Resources