Clearing select options with javascript on change - javascript

Before you -1 this for being such a simple question read further, because ive spent a while searching and cant figure it out. What i have is 5 select boxes. Each ones results depend on what is selected before it. There is no submit button. I just need the to change based on whats selected in the previous box and so far i have that. Oh and the results are being pulled from a database. The problem is when you select an option in lets say box 1, box 2 options appear, but when you go and select an option in box 1 again, they options are just stacked on the others. I need them to clear when its changed again. I'll post the js i have and if you need anything else just ask.
p.s. im getting the options using php-mysql.
p.s.s this site has to be finished by tomorrow so im kinda in a rush. Please dont waste time telling me this is a stupid question or what not.
Thanks in advance for the help.
$(function () { //When the page is finished loading run this code
$('#country').change(function () {
$.ajax({
url: "<!--Base url taken out-->/discovery/aLoad",
success: function (data) {
eval(data);
},
error: function () {
alert('failed');
},
data: {
country: getSelectValues('#country')
},
type: 'POST'
});
});
});
function changeSearchBar (newBar) {
//remove the crap
function ClearOptions(country)
{
document.getElementById('country').options.length = 0;
}
for (var i = 0; i <= newBar.length; i++) {
newBar[i].id = newBar[i][0];
newBar[i].name = newBar[i][1];
$('#group').append(
$('<option></option>').attr('value', newBar[i].id).text(newBar[i].name)
);
}
}
function getSelectValues (sId) {
var str = "";
$(sId +" option:selected").each(function () {
str += $(this).val() + ",";
});
return str.replace(/.$/g, '');
}

From what I understand from your long post you just need to remove all select child's before starting to append the new option from the AJAX request.
Try something like this before your for loop:
$('#group').html('');​
Demo: http://jsfiddle.net/57TYu/2/

Here you go, I think this is basically what you are trying to do:
How do you remove all the options of a select box and then add one option and select it with jQuery?
Basically, find the 'option' tags inside the select and remove them.
$('select').find('option').remove()
will clear all the select boxes.
This will append the data, which is assume are the options in their place:
$('select').find('option').remove().end().append(data);
I think that is what you are looking for.

Related

Chosen multiple select becomes huge when many/all options are selected

When using Chosen.js on a multiple select field, if there are over 500 options that the user has selected, the list just becomes ridiculously long.
Is there any way I could limit the number of show elements? For example when chosing over 3 options, the user will have (4) options are selected..., instead of them being listed.
I wonder why there's no such option in their documentation.
Thanks in advance.
You can use something like this:
$('.element').chosen().change(function() {
var totalSelected = $(this).find('option:selected').size();
var placeholder = $(this).find('option:first-child').text();
if(totalSelected > 3) {
$(this).next().find('.chosen-choices').find('li.search-choice').hide(),
$(this).next().find('.chosen-choices').find('.literal-multiple').show();
$(this).next().find('.chosen-choices').find('span.literal-multiple').text(placeholder + " ("+totalSelected+")");
}
});
The class literal-multiple is a custom element to show the totalSelected elements. You need to add it in the prototype of the chosen plugin:
file chosen.jquery.js
Chosen.prototype.set_up_html = function() {
//stuff
if(this.is_multiple) {
var selVal = this.default_text;
this.container.html('<ul class="chosen-choices"><span class="literal-multiple"></span></ul>');
}
};
SOrry I am unable to comment since I don't have enough reputation.
But to add to the previous answer, instead of adding a separate container,
why don't we just append the n users selected as a <li> item.
Something like this -
$('.element').chosen().change(function() {
var totalSelected = $(this).find('option:selected').size();
var placeholder = $(this).find('option:first-child').text();
if(totalSelected > 3) {
$(this).next().find('.chosen-choices').find('li.search-choice').hide(),
$(this).next().find('.chosen-choices')append('<li class="search-choice" <span>'+totalSelected+' users selected. </li>');
}
});
This seems to work for me.

How to get value from dropdown in datatables cell

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

Jquery Chosen plugin. Select multiple of the same option

I'm using the chosen plugin to build multiple select input fields. See an example here: http://harvesthq.github.io/chosen/#multiple-select
The default behavior disables an option if it has already been selected. In the example above, if you were to select "Afghanistan", it would be greyed out in the drop-down menu, thus disallowing you from selecting it a second time.
I need to be able to select the same option more than once. Is there any setting in the plugin or manual override I can add that will allow for this?
I created a version of chosen that allows you to select the same item multiple times, and even sends those multiple entries to the server as POST variables. Here's how you can do it (fairly easily, I think):
(Tip: Use a search function in chosen.jquery.js to find these lines)
Change:
this.is_multiple = this.form_field.multiple;
To:
this.is_multiple = this.form_field.multiple;
this.allows_duplicates = this.options.allow_duplicates;
Change:
classes.push("result-selected");
To:
if (this.allows_duplicates) {
classes.push("active-result");
} else {
classes.push("result-selected");
}
Change:
this.form_field.options[item.options_index].selected = true;
To:
if (this.allows_duplicates && this.form_field.options[item.options_index].selected == true) {
$('<input>').attr({type:'hidden',name:this.form_field.name,value:this.form_field.options[item.options_index].value}).appendTo($(this.form_field).parent());
} else {
this.form_field.options[item.options_index].selected = true;
}
Then, when calling chosen(), make sure to include the allows_duplicates option:
$("mySelect").chosen({allow_duplicates: true})
For a workaround, use the below code on each selection (in select event) or while popup opened:
$(".chosen-results .result-selected").addClass("active-result").removeClass("result-selected");
The above code removes the result-selected class and added the active-result class on the li items. So each selected item is considered as the active result, now you can select that item again.
#adam's Answer is working very well but doesn't cover the situation that someone wants to delete some options.
So to have this functionality, alongside with Adam's tweaks you need to add this code too at:
Chosen.prototype.result_deselect = function (pos) {
var result_data;
result_data = this.results_data[pos];
// If config duplicates is enabled
if (this.allows_duplicates) {
//find fields name
var $nameField = $(this.form_field).attr('name');
// search for hidden input with same name and value of the one we are trying to delete
var $duplicateVals = $('input[type="hidden"][name="' + $nameField + '"][value="' + this.form_field.options[result_data.options_index].value + '"]');
//if we find one. we delete it and stop the rest of the function
if ($duplicateVals.length > 0) {
$duplicateVals[0].remove();
return true;
}
}
....

Set Dropdownlist selected index with javascript?

I have 2 dropdownlists on a asp page.
If user changes the selected index of the first drop down list, then set DDL2.selectedindex = DDL1.Selectedindex
and do this same logic except switch DDL1 and DDL2 respectively. I have these both getting populated from the same list of objects(just different properties set to each) and i have a order by clause on the query to ensure the data stays in sync. My question is how can i get this logic to work in javascript? My current method is as such..
Accounts.Attributes.Add("onBlur", Customers.SelectedIndex = Accounts.SelectedIndex)
Customers.Attributes.Add("onBlur", Accounts.SelectedIndex = Customers.SelectedIndex)
This code doesn't work but demonstrates what im shooting for. When the ddl getting the first selection loses focus, populate the other ddl(setting the selected index). Any help would be great!
Can someone see what i'm doing wrong here?
$("[id$=ddlStandardAcctNo]").change(function () {
var acc = $("[id$=ddlStandardAcctNo]");
var cust = $("[id$=ddlCustomerName]");
cust.selectedindex = acc.selectedindex;
});
It compiles and just doesn't work... :( These drop downs are inside of a asp gridview.
After looking at that i'm trying to do this..
$("[id$=ddlStandardAcctNo]").blur(function () {
var acc = document.getElementById('<%=ddlStandardAcctNo.ClientID %>');
var cust = document.getElementById('<%=ddlCustomerName.ClientID %>');
cust.selectedindex = acc.selectedindex
});
$("[id$=ddlCustomerName]").blur(function () {
var acc = document.getElementById('<%=ddlStandardAcctNo.ClientID %>');
var cust = document.getElementById('<%=ddlCustomerName.ClientID %>');
acc.selectedindex = cust.selectedindex
});
Problem is i never use document.ready cause the dropdownlist are in a gridview. I'm literally just learning javascript/jquery as i run across issues like this so feel free to crack the knowledge whip lol.
I figured this out finally!!!! the solution for jquery prior is the following
$("[id$=ddlStandardAcctNo]").change(function () {
$("[id$=ddlCustomerName]").attr("selectedIndex", this.selectedIndex);
});
$("[id$=ddlCustomerName]").change(function () {
$("[id$=ddlStandardAcctNo]").attr("selectedIndex", this.selectedIndex);
});

How do I use the Yahoo YUI to do inline cell editing that writes to a database?

So I have datatable setup using the YUI 2.0. And for one of my column definitions, I've set it up so when you click on a cell, a set of radio button options pops so you can modify that cell content.
I want whatever changes are made to be reflected in the database. So I subscribe to a radioClickEvent. Here is my code for that:
Ex.myDataTable.subscribe("radioClickEvent", function(oArgs){
// hold the change for now
YAHOO.util.Event.preventDefault(oArgs.event);
// block the user from doing anything
this.disable();
// Read all we need
var elCheckbox = oArgs.target,
newValue = elCheckbox.checked,
record = this.getRecord(elCheckbox),
column = this.getColumn(elCheckbox),
oldValue = record.getData(column.key),
recordIndex = this.getRecordIndex(record),
session_code = record.getData(\'session_code\');
alert(newValue);
// check against server
YAHOO.util.Connect.asyncRequest(
"GET",
"inlineeddit.php?sesscode=session_code&",
{
success:function(o) {
alert("good");
var r = YAHOO.lang.JSON.parse(o.responseText);
if (r.replyCode == 200) {
// If Ok, do the change
var data = record.getData();
data[column.key] = newValue;
this.updateRow(recordIndex,data);
} else {
alert(r.replyText);
}
// unblock the interface
this.undisable();
},
failure:function(o) {
alert("bad");
//alert(o.statusText);
this.undisable();
},
scope:this
}
);
});
Ex.myDataTable.subscribe("cellClickEvent", Ex.myDataTable.onEventShowCellEditor);
But when I run my code and I click on a cell and I click a radio button, nothing happens ever. I've been looking at this for some time and I have no idea what I'm doing wrong. I know you can also use asyncsubmitter within my column definition I believe and I tried that, but that also wasn't working for me.
Any ideas would be greatly appreciated.

Categories

Resources