How to get value from dropdown in datatables cell - javascript

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

Related

show hide field depend on select value sharepoint online

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:

How to clear a selected value in Selectize.js dropdown?

I have a selectize.js dropdown and I have to clear the selected value .
I have tried this (as suggested in another question):
var selectize = $("#optionNetFlow")[0].selectize;
selectize.clear();
But it gives the following error:
When I change it to this:
var selectize = $("#optionNetFlow").selectize;
selectize.clear();
I gives this error:
What I am doing wrong here?
I finally found the answer here Selectize.js Demos
What works for me is:
var $select = $('#optionNetFlow').selectize();
var control = $select[0].selectize;
control.clear();
what I was missing var $select = $('#optionNetFlow').selectize(); before applying the solution provided in above question's answer.
Now I am to get all the functions in console like :
Try this,
$("#optionNetFlow")[0].selectize.clear();
Try this out:- http://jsfiddle.net/adiioo7/2gnq1ruv/204/
JS:-
jQuery(function ($) {
var $select = $('#input-tags').selectize({
persist: false,
create: true
});
$("#btnClear").on("click", function () {
var selectize = $select[0].selectize;
selectize.clear();
});
});
All other answers either clear a single selectize or need a specific reference to the selectize in the moment of it's creation.
The solution below, on the other hand, works for any number of selectize elements you have inside any form; you just need to specify the desired form:
$('form').find('.selectized').each(function(index, element) { element.selectize && element.selectize.clear() })
The rationale is that Selectize keeps the original element in the DOM (hiding it), adds a reference to the selectize on the .selectize property of the DOM element and adds a CSS class selectized to it.
So the solution finds all the elements that have the CSS class selectized, loops through them and calls element.selectize.clear().
$(document).on('click', 'div.selectize-input div.item', function(e) {
var select = $('#services').selectize();
var selectSizeControl = select[0].selectize;
// 1. Get the value
var selectedValue = $(this).attr("data-value");
// 2. Remove the option
select[0].selectize.removeItem(selectedValue);
// 3. Refresh the select
select[0].selectize.refreshItems();
select[0].selectize.refreshOptions();
});
This do not remove the item from the select, just remove it from the selected options.
Or if you have multi select, and do want to restore selected items in the drop-down list (hide selected set to true).
var selectize = $("#select-item").selectize;
//clone array
var items = selectize.items.slice(0);
for (var i in items) {
selectize.removeItem(items[i]);
}
selectize.refreshOptions();

show multiple selected span values in jquery using comma

I've posted my full code on jsfiddle. I'm trying to show the user selected seats here. If user selected 2 from BS the result should be BS-2. Again if user selected 4 from FC the result should be added with the old one like BS-2, FC-4.
But, I've tried something here. its show the value of span element but if i selected the another one it replaces the previous one. How to add a comma and show the multiple selected span values in jquery?
JsFiddle
jQuery
$(".text").click(function(){
$(this).toggleClass('selected');
var data = $(this).text();
$('.returndata').text(data);
})
Try
var $texts = $(".text").click(function () {
$(this).toggleClass('selected');
var selected = $texts.filter('.selected').map(function () {
return $.trim($(this).text())
}).get()
$('.returndata').text(selected.join());
})
Demo: Fiddle

filtering only previously unselected <select> options qith JQuery

Previously I asked how to do this and was directed to this:
<script>
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
</script>
(http://www.lessanvaezi.com/filter-select-list-options/)
When I use this filter on the select box it filters both the unselected AND the selected. I'd like it to ONLY filter the unselected because if a user wants to ammend the selections and filters again, the previously selected items go away - unless they meet the filter criteria.
I'm not that good at JavaScript or JQuery and can't understand how I might tell the above script to ignore options that are ":selected" but filter all else.
Here's a jfiddle if it helps: http://jsfiddle.net/UmKXy/ I'd like option one and two to remain selected and in the list when user begins to type.
Thanks for help!
The solution you had would not work with selected elements because he created an array of options at the start and then matched those options against the regex(Without regards to what is actually selected). I've used spans to hide options in the past and created an example for you to see how it works. Here is the link : http://jsfiddle.net/rD6wv/
Here is the code
$(function() {
$("#filterByText").bind('keyup',function(){
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$("#filez").find('option').each(function(){
if(!$(this).is(':selected')){
if($(this).val().match(regex) === null) {
$(this).wrap('<span>');
}else if($(this).parent().is('span')){
$(this).parent().replaceWith($(this));
}
}
});
});
});
You simply need to loop through all the options of the select when you type in the textbox.
You then check if it is selected, if it is you do nothing, else you check if it matches the search filter, if it does you wrap it in a span, making it invisible, else it means you need to see it, so you check if it is already wrapped in a span, and in that case you replace it with the option so you can see it again.
to selected the non selected options, use this:
$('option:not[selected]') or $('#myselect > option:not[selected]')
to remove them, use this:
$('option:not[selected]').remove();
in css, :not filters for opposite of what comes in the curved brackets.
and [] is attribute selector.
so :not[selected] means: does not have an attribute whose key is "selected"

Select2 Dropdown Dynamically Add, Remove and Refresh Items from

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

Categories

Resources