Empty a select if the option was already selected - javascript

I have a button that append a row with a select with its options. I gave those select a class (".nuevaDescripcionProducto"). The select has its first option (with the value: "Select an option" or whatever) and the rest of the options are added when I click the button to add the new row. Ok, what I want is: To go back to the first option if I select an option that is already selected in another row. Maybe you could get it more clear by looking a the picture:
This is my code so far:
$(".formularioVenta").on("change", "select.nuevaDescripcionProducto", function() {
var nombreProducto = $(this).val();
var productos = $(".nuevaDescripcionProducto");
for (var i = 0; i < productos.length; i++) {
var x = $(productos[i]).val();
if(nombreProducto == x) {
$(nombreProducto).val();
}
}
})
I think most of what is needed its done. But I would hugely appreciate any help for you. Thanks.

Related

Reset link for Datatables and ColumnFilterWidgets doesn't repopulate select

When I click the reset link, the table refreshes, but it fails to refresh the <select> option list. (It doesn't put the <option> back into the <select> element.) Also, when I click on a new select option after hitting refresh, it displays the table as if I have two select options active instead of just one selection. (The previous select table entries are shown with the second select table entries.)
Here are some similar threads I have tried to learn from with the same problem:
jQuery DataTables and Columnfilterwidget Reset all filters button
https://github.com/cyberhobo/ColumnFilterWidgets/issues/33
ColumnFilterWidgets Code:
https://github.com/cyberhobo/ColumnFilterWidgets/blob/master/media/js/ColumnFilterWidgets.js
DataTables Code:
https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js
My JSFiddle:
https://jsfiddle.net/suzyweb/9qzy0sb2/19/
var oTable = $('#example').DataTable({
ajax: "https://api.myjson.com/bins/esbxz",
"sDom": 'W<"clear"><"toolbar">frtipl',
"oColumnFilterWidgets": {
"aiExclude": [0, 4, 5]
},
});
$.fn.dataTableExt.oApi.fnResetAllFilters = function(oSettings, bDraw /*/default true/*/ ) {
for (iCol = 0; iCol < oSettings.aoPreSearchCols.length; iCol++) {
oSettings.aoPreSearchCols[iCol].sSearch = '';
}
$('.filter-term').remove();
oSettings.oPreviousSearch.sSearch = '';
if (typeof bDraw === 'undefined') bDraw = true;
if (bDraw) this.fnDraw();
};
$("div.toolbar").html('<b>RESET</b>');
$(".reset").click(function(e) {
e.preventDefault();
//alert("You clicked refresh");
//oTable.fnFilterClear();
$('#example').dataTable().fnResetAllFilters();
// oTable.search("").draw();
})
});
I'm very new to Javascript and feel really lost with trying to fix this one! I have spent so many days trying to understand this and it looks like others have been in the same boat, but I don't see how to do it. Thanks so much for any help you can offer!!!
I sought some expert help from ruslancer and he is allowing me to post the fixed code here. Thanks to all others who looked into this problem for me!
$.fn.dataTableExt.oApi.fnResetAllFilters = function(oSettings, bDraw /*/default true/*/ ) {
var t = $("a.filter-term");
for (var i=0; i<t.length; i++) {
$(t[i]).click();
}
for (iCol = 0; iCol < oSettings.aoPreSearchCols.length; iCol++) {
oSettings.aoPreSearchCols[iCol].sSearch = '';
}
$('.filter-term').remove();
oSettings.oPreviousSearch.sSearch = '';
if (typeof bDraw === 'undefined') bDraw = true;
if (bDraw) this.fnDraw();
};

how to get previously selected rows of a bootstrap dataTable while searching

I have used a bootstrap DataTable to show data. At the same time i have a HTML checkbox as a column of that dataTable. I have a submit button to get the selected checkbox's value to do some stuff. I am fetching the following problem while select checkboxes under searching.
When i select all checkboxes and Click Save button I got all the values. It works as my expectation.
But Unexpected occures when i search via built-in search box of bootstrap dataTable.Here is the pictorial view
In this case when i press Save i got just the two value though all other values are still selected. How can i get all the selected values while searching
Here is my jquery code of Save button of getting the checkboxes value
$("#btnSave").click(function () {
var checkboxes = document.getElementsByName('foo');
var vals = "";
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked) {
vals += "," + checkboxes[i].value;
}
}
....
//Other stuff
....
}
Please help me.
When you are doing a search, it is going to check only for the rows, that satisfy the given criteria. So your search logic works like this
if(searchCriteria==true)
{
showValue
}
Even if you had previously selected values it won't be showing all of them, because they don't satisfy the given criteria. Now in this case when you click on Save, it is taking only those rows in the datatable which are checked and satisfy the given criteria, as per your java script.
Now if you still wish, that all selected values should be taken in, there is one way you can try, put the selected values in some kind of List or Set, and place the list object in session. So everytime you click on Save, you can retrieve the List from the session. But I really don't see why you would want to do it, unless you need to retrieve the selected values every time.
I got my job done like this
var table = $('#tblReportList').dataTable();
When i was searching through dataTable, i was getting just the selected values matching the search criteria. But the previously selected values was disappeared. To get the previously selected value i used the following code...
table.$('input[type="checkbox"]').each(function () {
if (!$.contains(document, this)) {
if (this.checked) {
previousVal = previousVal + ',' + this.value;
}
}
});
Now, for getting the selected values of search I used the previous code posted before. And that was
var checkboxes = document.getElementsByName('foo');
var vals = "";
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked) {
vals += "," + checkboxes[i].value;
}
}
So all selected checkbox's values are
var allValues=previousVal+vals;

Changing one select option changes many others (JavaScript, JQuery)

I have a lot of select drop downs on a jsp page with a long list of elements. All of these drop downs have the same list of elements. Say I have to get the choice in descending order of preference from the user. I made (many) selects in the following way:
<select id="sel1" class="myClass">
<script>
populate(document.getElementById('sel1'));
</script>
</select>
...
<script>
function populate(op1)
{
var myArray = ["Chinese", "Italian", "Indian", ...//a long list of elements
var sel = op1;
for(var i = 0; i < myArray.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = myArray[i];
opt.value = myArray[i];
sel.appendChild(opt);
}
}
</script>
I have to create javascript/JQuery code in such a way that if a user selects an option the first select, that option gets disabled/removed in the others, leaving room for changes later. Say, the user's preference order is: Chinese, Indian, Italian... then on selecting Chinese in the first drop down, it gets disabled/removed from the other drop downs. Then, on selecting Indian from the second, it gets disabled/removed from all the others (including the previous one).
Now, if the user decides his order of preference is actually Chinese, Italian, Indian, .. he should be able to change his choice in such a way that the code doesn't break down. Say, we can have a button for reset and it resets all the choices by calling this function:
function resetFunc()
{
var options = document.getElementsByClassName("myClass");
for (var i = 0, l = options.length; i < l; i++)
{
options[i].selectedIndex = "0";
}
}
Any idea how to accomplish this? I need the code to be browser independent (while googling, I read somewhere that IE doesn't support removal of elements from drop down).
EDIT: Here's what I basically want:
http://jsfiddle.net/RaBuQ/1/
However, there's a problem in this. If a user keeps changing his choices, this thing breaks down. I'm able to select multiple choices.
$('select').change(function(){
var v = $(this).val();
$('select option[value="'+$(this).data('old-val')+'"]').prop('disabled', false);
$(this).data('old-val',v);
if(v != "0"){
$('select option[value="'+v+'"]').not(this).prop('disabled',true);
}
});
Here's a fiddle.
If I selected 'Football', 'Golf', 'Tennis', I'd need to select 'No preference' in the third box before I could then select it in one of the other boxes. I think this is acceptable from a UX perspective.
Since you've tagged this jQuery my example below will utilize that:
function populate() {
var myArray = ["Chinese", "Italian", "Indian"];
$('.myClass').each(function() {
var dis = $(this);
dis.append($("<option>").attr("value", "").text("select"));
$.each(myArray, function(i, o) {
dis.append($("<option>").attr("value", o).text(o));
});
});
}
function init() {
$('.myClass').html('').prop('disabled', false);
populate();
}
$(document).on('change', '.myClass', function() {
$('.myClass option[value="' + $(this).val() + '"]:not(:checked)').remove();
$(this).prop('disabled', true);
});
$('#reset').click(init);
init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel1" class="myClass"></select>
<select id="sel2" class="myClass"></select>
<select id="sel3" class="myClass"></select>
<input type="button" id="reset" value="Reset options" />
The following might not be the most efficient solution, but you should try it if there is nothing better: when you change a select, empty all other selects and then fill them with all the other options.
lets say you have 3 selects: sel1, sel2, sel3
in the onchange event, you could call a function "fill_other_sel(number)" where number is the number of the current selector.
This function should delete current options and then populate checking with the previous selectors so that you dont populate with a previously selected value.
function fill_other_sel(number){
var num_selectors = 3;
while (number <= num_selectors){
number++;
$('#sel'+number).options.length=1;
populate('sel'+number, already_selected_values_array);
}
}
also you might add a parameter to your populate function showing which values have already been selected to prevent them from appearing again

How do I add items to multiple drop down lists at the same time with Javascript in Razor?

I'm creating an MVC form, and I have multiple checkboxes and two drop down lists. I have figured out how to populate the first DDL based on what boxes are checked (i.e. empty at the beginning, checking boxes fills the items). However, I want to add another DDL that has the same items and populates in the same manner. My code looks like this:
<script type="text/javascript">
function checkedToggle(value, checked) {
x = document.getElementById("filter1");
y = document.getElementById("filter2");
if (checked == true) {
var option = document.createElement("option");
option.text = value;
x.add(option, null);
y.add(option, null);
}
else {
for (i = 0; i < x.length; i++) {
if (x.options[i].value == value) {
x.remove(i);
y.remove(i);
}
}
}
}
</script>
The else statement obviously removes an item from the list once you uncheck the box.
Now, when you click a check box, rather than adding the item to both lists, it only adds to the second one, and I'm not exactly sure why. Any advice?
You need to create two elements, since in your code you just move the first DOM element to the second select.
var option = document.createElement("option");
var option2 = document.createElement("option");
option.text = value;
option2.text = value;
x.add(option, null);
y.add(option2, null);

How to make a selection list to null in runtime?

I have a code that fetches a list from DB. Using that returned array i am creating a grid table and two combo boxes dynamically. Now, the code is working fine for first time. I can also able to add new entry to the database and show it in the grid. Now the problem is with the combo box.
Whenever i add a new entry, the table gets updated by deleting the previous content in the table and fetching again from the DB along with new entry. But the combo options get appended with the newly arrived data. See, the image. Chemical Engg is newly addded.
But i dont know to reset or delete existing combo box contents. I know that the solution is a piece of code that makes the combo box null. It has to be placed on the top of combo box generation code. So, that it ll reset every time before generating new elements.
My question is how to make that combo box null in the starting point.(I dont know what exact term is "null" or "reset", i new to DOM elements).
Here my Code.
The HTML ELEMENT:
<select id="departmentField" >//Both using same data source.
<select id="searchDepartments">
The Script:
Its DWR Call... I think the problem comes below the grid.
EmployeeManagement.getDeptList(function(deptRecords) {
$("#depts").clearGridData(true);
$("#depts").jqGrid('addRowData', "deptID", deptRecords);
var deptSearchSelect = document.getElementById('searchDepartments');
var searchOptions = null;
searchOptions = document.createElement('option');
searchOptions.value = 0;
searchOptions.innerHTML = "ALL";
deptSearchSelect.appendChild(searchOptions);
var depFieldSelect = document.getElementById('departmentField');
var deptFieldOpts = null;
deptFieldOpts = document.createElement('option');
deptFieldOpts.value = 0;
deptFieldOpts.innerHTML = "";
depFieldSelect.appendChild(deptFieldOpts);
for(i = 0; i<deptRecords.length; i++) {
var dept = deptRecords[i];
searchOptions = document.createElement('option');
searchOptions.value = dept.deptID;
searchOptions.innerHTML = dept.deptName;
deptSearchSelect.appendChild(searchOptions);
deptFieldOpts = document.createElement('option');
deptFieldOpts.value = dept.deptID;
deptFieldOpts.innerHTML = dept.deptName;
depFieldSelect.appendChild(deptFieldOpts);
}
deptSearchSelect.selectedIndex = "ALL";
deptSearchSelect.selectedIndex = "";
//var respDiv = document.getElementById("respCheck");
});
How shall i reset?
Any suggestions would be more appreciative
Thanks in advance!!!
Try deleting each element in the select:
while(deptSearchSelect.hasChildNodes()) {
deptSearchSelect.removeChild(deptSearchSelect.firstChild);
}
while(depFieldSelect.hasChildNodes()) {
depFieldSelect.removeChild(depFieldSelect.firstChild);
}
Are you also not able to set the select box properly?

Categories

Resources