Escaping select option values in jquery - javascript

I have a bunch of select boxes used to filter a large complex table whose contents is loaded via a sequence of ajax queries. As the table loads, not just the table but the select box filter update to reflect the current available options. As the use may already have selected options to filter the table at this point, I have a bit of code to preserve the currently selected value:
if($('#CourseFilter').length) {
selected = $('#CourseFilter').val();
$('#CourseFilter').replaceWith(sel);
if(selected != '') $('#CourseFilter option[value="'+escape(selected)+'"]').prop('selected', true);
} else {
sel.appendTo('#filters'); // Adding fitler for first time.
}
This works for most of the filters, but a couple, such as #CourseFilter, reset back to default instead of remembering current selection. It think it is because the values in these lists contain special characters such as -, / and \. I have tried using escape but it still doesn't work. Any ideas?

What you are probably looking for:
You should be able to just set the value of sel, instead of finding the right <option> and manually selecting that:
sel.val(selected);
If you want to find the right <option>:
You can avoid the escaping issue altogether by filtering for the right <option> using jQuery.filter:
$('#CourseFilter option').filter(function() {
return $(this).val() === selected;
}).prop('selected', true);

No need to look for each <option> since val() is both a getter and a setter.
Just use val() to set value on new <select>
if($('#CourseFilter').length) {
selected = $('#CourseFilter').val();
$('#CourseFilter').replaceWith(sel);
sel.val(selected);
} else {
sel.appendTo('#filters'); // Adding fitler for first time.
}

Related

How to check if option contains empty char?

I have a dropdownlist with list of some values from database.
<asp:DropDownList Runat="server" ID="cmbSalut" data-bind="value: drSalut"></asp:DropDownList>
Depending on what kind of record are opened, I am selecting its proper value in dropdown, and in case if there are nothing, I am selecting default value.
I use this to select default value:
$('select[Id="cmbSalut"] > option:contains("")').prop('selected', true);
It works fine until one issue appeared. It works because my datatable for dropdown contains record with "" value (empty value), but if I change it to " " (or more white spaces), this select not working anymore (it will be ignoret and last one value will be selected).
So my question is, how can I select option which value is empty or white space by using jquery (what should I change in my existing select)?
P.S Sorry for my bad English.
EDIT:
Fixed it.
Instead of contains use, I needed to write this:
('select[Id="cmbSalut"]').find('option[text=""]').prop('selected', true);
Worked out as I wanted.
Try this : You can use .filter() and return true if option has empty value. make use of .trim() to handle any empty space.
$('select[Id="cmbSalut"] > option').filter(function(){
return ""==$(this).val().trim();
}).prop('selected', true);

How can the "select inputs" DataTables solution be modified to allow a select input to be deselected?

select inputs
text inputs
These two DataTables filters provide the same functionality. For example, in the first column when you search for "Angelica Ramos" you get the single record for Angelica Ramos.
However, for the solution with select inputs, if "" (none) is selected after filtering for "Angelica Ramos" there are "No matching records found".
In the solution with text inputs, when the text is deleted the functionality works as desired.
How can the "select inputs" DataTables solution be modified to allow a select input to be deselected?
Here are two ways you could work around this solution, all done in the event handler function:
1) Remove the regex option for the column search, and instead use the smart search that they have built for you.
.on('change', function() {
table.column(i)
.search($(this).val()) // Uses default smart search
.draw();
2) Add in an if-else statement to check for a blank string ("") value.
.on('change', function() {
if ($(this).val() == "") {
// Uses default smart search in only this case
table.column(i).search('').draw();
} else {
// Uses regex search - this is what is shown on the select inputs page
table.column(i).search('^'+$(this).val()+'$', true, false).draw();
Here is a JSFiddle with both of these options implemented: http://jsfiddle.net/gk5zB/5/
One of the options in the JSFiddle is commented out, but they both work. I hope that one of these solutions fits your needs.

change name of dynamically added select option element

I am dynamically generating some dropdowns and then allowing them some of those to be removed on board dyanmically. so that time, i have encountered an error of selection option (dropdown) elements id mismatch. something like below is.
newly added dropdowns.
select name="CSSAtapsClient[client_time_window_arr][0]" id="client_time_window_0">/select>
select name="CSSAtapsClient[client_time_window_arr][1]" id="client_time_window_1">/select>
select name="CSSAtapsClient[client_time_window_arr][2]" id="client_time_window_2">/select>
select name="CSSAtapsClient[client_time_window_arr][3]" id="client_time_window_3">/select>
after i dynamically remove them via javascript. (lets say i am removing the second one) so then new ones will be displayed as followings,
select name="CSSAtapsClient[client_time_window_arr][0]" id="client_time_window_0">/select>
select name="CSSAtapsClient[client_time_window_arr][2]" id="client_time_window_2">/select>
select name="CSSAtapsClient[client_time_window_arr][3]" id="client_time_window_3">/select>
So now the issue i have is, the names of the dropdowns are like this, (0,2,3)
CSSAtapsClient[client_time_window_arr][0],
CSSAtapsClient[client_time_window_arr][2],
CSSAtapsClient[client_time_window_arr][3]
So this is causing an error for me and i need to reorder this name and make it be like this, (0,1,2)
CSSAtapsClient[client_time_window_arr][0]
CSSAtapsClient[client_time_window_arr][1]
CSSAtapsClient[client_time_window_arr][2]
how can i simply rename these dropdowns name attribute (from 0 to how much ever dropdows are exisiting) ? appreciate an early reply
EDIT 1
I tried this, but didnt work.
$('#tbl_dynamic_call_dates select').each(function(i){
$(this).attr('name',"CSSAtapsClient[client_time_window_arr][i]");
});
You can simply reset the values using .attr() method:
$('#tbl_dynamic_call_dates select').attr('name', function(i) {
return 'CSSAtapsClient[client_time_window_arr]['+ i +']';
});
I did this,
$('#tbl_dynamic_call_dates select').each(function(i){
$(this).attr('name',"CSSAtapsClient[client_time_window_arr][" + i + "]");
});

Removing an <option> from a <select> tag according to previously selected <option> tag? (POLL Example)for

I have 50 rows of data and i want users to give them points by 1 to 50. I put dropdown boxes near them with options 1/50. But all i want is when a user selects 15(for example) for a row, 15 will be deleted from all other select tags of other rows. I am not as good as you in JavaScript. How can i accomplish this?
Hi casablanca i couldnt make he script you sent work. I need it to work on just one select tag so i give select tag an ID and an ID for the form too. I edit the scripts getElementsByTagName with getElementsByTagID (select tag's ID) to effect only one select tag. But the function doesnt triggered?
This might not be a very good idea, because it is very difficult for the user to modify choices -- for example, if I want to give 15 to a different option, I need to change the old one to something else and then change the new one to 15. Also, once all points have been assigned, it's impossible to make any changes because all options are gone.
A better idea would be to let the user do whatever he/she wants and then validate the form in the end. You could do that like this:
function validate() {
var used = []; // This array stores already used options
var rows = document.getElementById('myForm').getElementsByTagName('select');
for (var i = 0; i < rows.length; i++) {
var points = rows[i].value;
if (used[points]) {
// This value was already used
alert('Please choose a different value.');
rows[i].focus();
return false;
} else {
// This value was not used before; mark it as used now
used[points] = true;
}
}
return true;
}
And call this function in the onsubmit handler of your form:
<form id="myForm" onsubmit="return validate();">
EDIT1: id -> class
give each option the class of the number it is
<option class="15">15</option>
<option class="16">16</option>
etc.
Then jquery can remove() an item by class
$('.15').remove();
obviously have to do an on change and get the value just set. "remove()" is nice in this instance because I believe it will yank every instance of that class.
EDIT3: upon further consideration the above method would be further complicated by the need to not remove the "selected" option. Not going to figure out the exact method but I think changing the class from "15" to "selected15" with a $(this).append() or something of the sort before calling the remove would get the job done fairly safely.
EDIT2:
As noted by casblanca below this is not an ideal user interface at all for this type of input. You may want to look into this: http://www.utdallas.edu/~jrb048000/ListReorder/
Allows user to drag and drop items in a list to reorder them. Much more natural.

How to trigger an event ONLY if both dropdowns are selected?

I have a dropdown select list on my page of class="TypeFilter".
I have a jQuery event that fires when a value in that list is selected.
$(".TypeFilter").change(function()
{
// Extract value from TypeFilter and update page accordingly
));
I now have to add another list to the page, and I want to implement functionality which will prevent the .change(function() from running unless both are selected.
In both lists the first option in the list is some text instructing the user to select one of the items, so I was thinking of just writing some logic to test that both lists have a selected index greater than 0.
I think this is a touch unclean though, especially considering that other pages that have a TypeFilter use the same logic.
Is there any nifty functionality in jQuery that can do this?
edit I should specify that the user needs to be able to update the page by selecting either dropdown, so I can't put the onchange on the second element and test that the first element has a selected value, as suggested in one of the answers
If you bind the same event to all dropdowns, you can get a collection of all the dropdowns and check that all of them are selected. Example:
$('.Dropdown').change(function(){
var elements = $('.Dropdown');
if (
elements.filter(function(){
return this.selectedIndex > 0;
}).length == elements.length
) {
// all dropdowns are selected
}
});
As you partly mention, put the onchange on the second element and test that the first element has a selected value before you fire off any logic.
Use bind instead, and as the eventdata, send a function that checks that either that both are selected or that the other is selected. Untested code:
function checker() {
// test your conditions
}
$(".TypeFilter").bind('change', {test: checker}, function(event)
{
if (event.data.test && event.data.test()) {
// Extract value from TypeFilter and update page accordingly
}
));
This way the other pages that use the same function will not notice any changes.

Categories