I'm using Django-select2 to show select2 widgets on my forms.
On one of these form select-fields I want to user to be able to set the value by clicking a link containing a suggestion.
My javascript looks like:
<script type="text/javascript">
$( document ).ready(function() {
// When the topicSuggestion is clicked, populate the select2 field with that value.
$('#topicSuggestion').on('click',function (e) {
var value = {{ object.suggestion.topic.id }};
$('#id_topic').val(value).trigger('change');
});
});
</script>
This isn't quite working as expected though. Instead of nicely populating the value, this is the behaviour I see:
Click the link, nothing happens
Select a random value from the list, and click the link. The select seems to clear
Select the desired value once, now click a random value and click the link. Now the value populates correctly
I can imagine this is related to my non-existing js skills. Could someone be kind enough to help me clear this up on this newyears day?
As we can see in https://github.com/codingjoe/django-select2/discussions/145
the items are loaded async. So if you want to pre-populate, you need to add the value first.
The select2 docs explain this: https://select2.org/programmatic-control/add-select-clear-items#create-if-not-exists
The answer in this case is:
$( document ).ready(function() {
// When the topicSuggestion is clicked, populate the select2 field with that value.
$('#topicSuggestion').on('click',function (e) {
$( "#topicSuggestion" ).css( "border", "9px solid red" );
var data_id = {{ object.suggestion.topic.id }};
var data_name = "{{ object.suggestion.topic.name }}";
// Set the value, creating a new option if necessary
if ($('#id_topic').find("option[value='" + data_id + "']").length) {
$('#id_topic').val(data_id).trigger('change');
} else {
// Create a DOM Option and pre-select by default
var newOption = new Option(data_name, data_id, true, true);
// Append it to the select
$('#id_topic').append(newOption).trigger('change');
};
});
Related
Since my previous questions I learned and progressed a lot (this all started from HTML code in println inside a Java file !)
I'm close to my target.
I've got 2 dropdown : dd1 and dd2
I got a java to get values in database
dd1 is an independant list
dd2 options depend of the choice in dd1
Using gson/jquery it works perfectly
My issue is the initialisation of the page.
I load the dd1 using my fillOption function and by default my page display the first value as selected.
So I want that dd2 initialised with this value but when I trigger the change() on dd1 this.value is empty and I don't get why.
$(document).ready(function() {
fillOptions('dd1', this); // Init the first dropdown with my values, works fine
$('#dd1 option:eq(1)').prop('selected', true); // Here I tried to force the selection of the first item, doesn't change anything
// Delcaration of the change function for the first dropwdown
$('#dd1').on('change', function() {
alert(this.value); // display blank on the page load, display the value if I select manually afterwards
fillOptions('dd2', this); // at load, 'this' is blank so nothing is loaded for dd2. Works fine if selected manually. I expected to have the value displayed on screen here.
});
$('#dd1').trigger('change');
});
function fillOptions(ddId, callingElement) {
var dd = $('#' + ddId);
$.getJSON('${pageContext.request.contextPath}/optionsSousType?dd=' + ddId + '&val=' + $(callingElement).val(), function(opts) {
$('>option', dd).remove(); // Clean old options first.
if (opts) {
$.each(opts, function(key, value) {
dd.append($('<option/>').val(key).text(value));
});
} else {
dd.append($('<option/>').text("Choisir parent"));
}
});
}
I also tried getting the value using :
$('#colonne').on('change', function() {
var col = $('#colonne').find(":selected").text();
alert(col);
fillOptions('libelle', col);
});
Same result, col is blank. I'm pretty sure it's simple but I couldn't find an answer. Thanks for your help
I have a list of 2 columns, the first one is "City" which is choice type.the second column is "Other" which is a single line of text.
when the user chooses "other " in City I want "OtherCity "column appears, if he chooses another choice, I want to hide.
I write the code using simple javascript, I do not want to use any library just simple code in javascript.
<script type="text/javascript">
function mySelectfunction(){
getValue = document.getElementById("City").value;
if(getValue == "other"){
document.getElementById("OtherCity").style.display ="none";
}else{
document.getElementById("OtherCity").style.display ="block";
}
}
</script>
but it does not work. can you help make it work?
*another question: if the second column which I want to hide type is "lookup " will the code be different?
My test code for your reference,and Choice and lookup column do not need to change the code.
Add a script editor in NewForm,and insert the code into it(replace the column name).
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.js"></script>
<script src="https://xxxx.sharepoint.com/sites/dev/SiteAssets/sputility.js">
</script>
<script>
$(document).ready(function () {
// Get a single select dropdown field
var relacionField = SPUtility.GetSPField('CityLookUp');
// create a function to show or hide Rates based on Rate value
var showOrHideField = function() {
var relacionFieldValue = relacionField.GetValue();
// Hide the Rates field if the selected value is Especial
if(relacionFieldValue === 'other') {
SPUtility.ShowSPField('Other')
}
else {
SPUtility.HideSPField('Other')
}
};
// run at startup (for edit form)
showOrHideField();
// make sure if the user changes the value we handle it
$(relacionField.Dropdown).on('change', showOrHideField);
});
</script>
You can download sputility.js here: https://archive.codeplex.com/?p=sputility
Updated:
Did the code above report any error?
JavaScript code:
ExecuteOrDelayUntilScriptLoaded(show,"sp.js");
function show () {
//Get the select element corresponding to column
var selectElement=document.getElementById('CityLookUp').parentNode.parentNode.childNodes[3].childNodes[3].childNodes[0];//chnage coulmn name
//get tr the hidden column located
var trElement=document.getElementById('Other').parentNode.parentNode;//change column name
//hide tr when we get into page,if the default value is 'other' ,do not need this
trElement.style.display='none';
//select change event
selectElement.onchange = function () {
var index = selectElement.selectedIndex;
//get option value
var value = selectElement.options[index].text;
if(value==='other'){
//show tr element
trElement.style.display='';
}else{
//hide tr element
trElement.style.display='none';
}
}
}
The code idea is to find the corresponding select element and decide whether to hide the tr element where column other is located according to the value of option.
Tip: Our page dom structure may be different, so you may need to modify the code according to your page dom structure. You could view your page dom structure by Developer tool.
Test result:
I've got two datatables and there is a dropdown created in the second one with data from the first. I've created a jsbin here
If you add a couple of instructions to the first table (add any text and then click Add Instruction) - then click on the Load Copied Data button, you will see the dropdown box is populated from the first table.
If I do:
$('#btnTest').on('click', function (e) {
var tsor = $('#tblSORSInstall').dataTable();
var ins = tsor.fnGetData();
alert(ins);
});
It basically gives me the html for the dropdown - how do I get which value they have chosen? I was thinking of having a hidden column and updating that on the onchange of the dropdown, but is there a better way?
Thanks in advance
You may use jQuery.map() to generate an array of selected text/value, like below.
$('#btnTest').on('click', function (e) {
//var tsor = $('#tblSORSInstall').dataTable();
var ins = $('#tblSORSInstall').find("tbody select").map(function() {
return $(this).find(":selected").text() // get selected text
//return $(this).val() // get selected value
}).get()
alert ( JSON.stringify(ins, null, 2) )
});
Here is your JS Bin - updated
Using tsor.fnGetNodes() you can get all table row nodes, then you can loop through those and get the select values.
Final code will look something like
$('#btnTest').on('click', function (e) {
var tsor = $('#tblSORSInstall').dataTable();
var ins = tsor.fnGetData();
var a = tsor.fnGetNodes();
$.each(tsor.fnGetNodes(), function (index, value) {
alert($(value).find('select').val());
});
});
This drives me crazy! Why cant Select2 implement clear methods or examples on their page how to do simple CRUD manipulation on Select2 :)
i have a select2 which gets data from a ajax call.
<input id="valueg" type="hidden" style="width: 300px;" data-placeholder="Select a Conference" />
$("#valueg").select2({
data: conferences,
allowClear: true,
initSelection: function (element, callback) {
var data = { id: element.val(), text: element.val() };
callback(data);
}
}).on("change", function (e) {
// show data in separate div when item is selected
});
Can some one provide a clear method how to delete and add an item from the Select2.
For example:
I add an item via ajax call to db, and just want to append an option to Select2 and set it as selected.
I remove an item via ajax to db, and want to remove an option from Select2 and have no option selected.
From your example I can see that you attached Select2 plugin to hidden element. In addition you use Ajax call to populate results, so in this case if you need to add a new option to the list you simple call:
$('#valueg').select2('val', 'YOUR_VALUE');
In case of using select element as a container the only way that I found is to reinitialize plugin with new options... Something like this:
var el = $('select[name="type"]', '#details-form');
var temp = el.select2('val'); // save current value
temp.push(NEW_VALUE); // append new one
var newOptions = '<option value="1">1</option><option value="2">2</option>';
el.select2('destroy').html(newOptions ).select2().select2('val', temp);
I did it this way:
var $select2 = $('#valueg').select2(); // getting the select2
var item = 'xyz'; // item to be added
$select2.val(function(i, val) { // val can take function as parameter
val = val || []; // if value is null init val as an array
val.push(item); // add the new item
return val;
}).trigger("change"); //refresh
Hope that helps
I had the same issue. This is how i solved it
This has nothing to do with select2, manipulating the itself seems to work for me
$("#lstService").empty();
for(var i=0;i<data.length;i++){
$("#lstService").append('<option value="'+data[i].service_id+'">'+data[i].service_name+'</option>');
}
In my case, the key thing to add after manipulating the underlying select is:
$selectlist.trigger("change"); //$selectlist is the underlying select element.
Select2 works around the change event on a select, so calling "change" updates the option displayed in the select 2.
It is too late... but this is my solution for people that still have this problem:
html = "";
jQuery("#select_2 option").each(function()
{
html += '<option value="'+jQuery(this).attr("value")+'">'+jQuery(this).text()+'</option>';
});
html += '<option value="NEWVALUE">NEW OPTION</option>';
jQuery("#select_2").html(html);
I have a form with hidden inputs.
I .clone() them and show them to the user in a .dialog().
The user makes some changes and i use .val() to change the hidden fields.
However the next time i clone the form(without reloading the page) i have the initial values again, and never the updates ones.
There seems to be this weird bug/result? see http://jsfiddle.net/YvBfP/ (broken for visible input too)
$(this).closest('td').find('button').click( function ()
{
var d = $('#pagamento_anticipato').html();
$(d).dialog({
modal: true,
width: 400,
height: 300,
close: function( event, ui ) {
var importo = $(this).find('input[type="text"]').val();
var descrizione = $(this).find('textarea').val();
var select = $(this).find('select').val();
$(this).remove();
$('#pagamento_anticipato').find('input[id="importo"]').val( importo );
$('#pagamento_anticipato').find('#descrizione').val( descrizione );
$('#pagamento_anticipato').find('#tipo').find('option[value="' + select + '"]').attr('selected', true);
}
});
return false;
});
using .val() sets/gets the current value and not the attribute for the element.
$(element).val(value) // sets current value
$(element).val() // <-- will always return the current value
to change the attribute you have to use .attr()
$(element).attr('value',value)
Then you will see the change in the HTML
http://jsfiddle.net/wirey00/bJjjw/
EDIT:
Just found out this doesn't work with jQuery 1.5.x and lower.. tested it with jQuery 1.6.0+ and it worked fine
You are setting the value property of the input but checking to see if the value attribute has changed. To see the elements value use .val() don't check its html. However if you need to change the elements value attribute use setAttribute
$('#money')[0].setAttribute('value', 3000);
http://jsfiddle.net/YvBfP/4/