How to get the current selected/unselected in a Jquery multiselect?
I already know how to get the selected values in a multiselect. The problem is that I need to get the one that was currently selected/unselected when the user clicked on it. It looks like a trivial question but I haven't really found a proper solution so far.
This is what I previously tried:
$('#mySelect').change(function(){
var element = $(this).val();
})
Unfortunately it returns an array with all selected options. What I need is to get the current either selected or unselected value by the user. I just tried to create a method myself using auxiliar variables and it seems that it works now.
if($(this).attr('id').includes('Type')) Key = "trackertype";
if(selectedValue.length > 0 && $(this).val() == null){
Value = selectedValue[0].toString();
selectedValue = [];
Key = '-' + Key;
}else if(selectedValue.length == 0 && $(this).val() != null){
selectedValue.push($(this).val()[0]);
Value = selectedValue[0].toString();
}else if(selectedValue.length > 0 && $(this).val() != null && selectedValue.length < $(this).val().length){
var selected = true;
$.each($(this).val(),function(i,item){
var current = item.toString();
$.each(selectedValue,function(i,itemV){
if(current != itemV.toString()){
Value = current.toString();
selectedValue.push(current.toString());
selected = false;
}
});
});
}else if(selectedValue.length > $(this).val().length){
$.each($(this).val(),function(i,item){
var current = item.toString();
$.each(selectedValue,function(i,itemV){
if(current != itemV.toString()){
Value = itemV.toString();
selectedValue = jQuery.grep(selectedValue, function(value) {
return value != itemV.toString();
});
selected = true;
}
});
});
}
if(selected){
Key = '-' + Key;
}
I needed to send Value(value of the current selected option) and Key(select Name) to a web service. Its not the best possible code(sorry about that) but it actually does its job.
Thanks
var selectedItems = document.querySelectorAll('#selectBoxid option:checked');
// here selectboxid is id of select element of your page.
It is simple when any html element can get using document.getElementsById('id').
Just same as if you want to get html element using css class or any css selector rather than id of element or name of html element.
For example :
<p class="text-center" > abcd </p>
Then, we can retrive all html using:
document.querySelectorAll('.text-center')
Same in given example we want option html element which is selected for that property I use:
document.querySelectorAll('option:checked');
Related
I have three dropdownlist controls in my asp.net web app project from which the user will choose items. What I want is that the user must not choose the same values, meaning that the value selected in the one Dropdownlist can not be selected in the other dropdownlist, and if the user tries to select the same value I want to reset the selectedValue property to that dropdownlist. Is there anyway I can achieve this using javascript? It's better to make it on the client side.
Thank you!
The Dropdownlist Looks like this: Image here
First add same class name in all three dropdowns. e.g
'class=dropdownClass'
Add dropdown Number as attribute in all
three dropdowns -> 'dropdownNo=1' , 'dropdownNo=2' , 'dropdownNo=3'
Also add ids (it must be different)-> dropdownId1 , dropdownId2 ,
dropdownId3 respectivitely
<script>
$(document).ready(function () {
$('.dropdownClass').on('change', function () {
//when ever any dropdown change (class name is same)
//get the attribe no
var CurrentdropdownNo = $(this).attr('dropdownNo')
var CurrentdropdownValue = $(this).val();
if (CurrentdropdownNo == 1) {
var value2 = $('#dropdownId2').val() ;
var value3 = $('#dropdownId3').val() ;
//check with dropdown 2,3
if (CurrentdropdownValue == value2 || CurrentdropdownValue == value3)
{
//reset the current dropdown
//do stuff here , what you want
}
}
if (CurrentdropdownNo == 2) {
var value1 = $('#dropdownId1').val();
var value3 = $('#dropdownId3').val();
//check with dropdown 1,3
if (CurrentdropdownValue == value1 || CurrentdropdownValue == value3) {
//reset the current dropdown
//do stuff here , what you want
}
}
if (CurrentdropdownNo == 3) {
var value1 = $('#dropdownId1').val();
var value2 = $('#dropdownId2').val();
//check with dropdown 1,2
if (CurrentdropdownValue == value1 || CurrentdropdownValue == value2) {
//reset the current dropdown
//do stuff here , what you want
}
}
})
})
Note: Change class name Or id name as want ..
Use change Event of every dropdownlist
this is just one change event that i use for Dropdownlist. Do same thing for other drowpdownlists.
var firstDropVal="";
var SecndDropVal="";
var ThrdDropVal ="";
$("#dropOne").change(function () {
var firstDropVal = $("#dropOne").val();
var firstDropVal = $("#dropTwo").val();
var firstDropVal = $("#dropThree").val();
if(firstDropVal == SecndDropVal){
$("#dropOne").val(0)// Or Do what you want to do
}
});
I have a post ajax that return retorno1 and just to get it simple i put their output as string value as ajax posted like the example .. then I need to add more than 1 option that the value is 0 so I need to say if the value is 0 show the selected item "NON" and if the value other so show it and select it.
I'm using setAttribute("selected", "selected") but I know it's wrong, so what is the correct code to add attribute to this string?
var i = 0;
var returno1 = "<option value='21'>Hello</option><option value='22'>Bye</option>";
var pre = retorno1 + '<option value="0">------ N/A ------</option>';
var count = $($.parseHTML(pre)).filter('option').length;
var dep_dr = $("#departamento_drop option:selected").val();
$.each($.parseHTML(pre),function(i,item){
var val_drop =($(item).val());
var text_drop =($(item).html());
if (val_drop == dep_dr){
jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
}else if(dep_dr == "0"){
jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
}
})
Working fiddle
Try to use attr() or prop() to set or get attribute to elements, check example bellow :
jQuery("#departamento_drop").empty();
$.each($.parseHTML(pre),function(i,item){
var current_itme=$(item);
var val_drop =current_itme.val();
var text_drop =current_itme.html();
if (val_drop == dep_dr || dep_dr == "0"){
current_itme=current_itme.attr("selected", "selected");
}
jQuery("#departamento_drop").append(current_itme);
})
Hope this helps.
Why do you need use strings? Use objects insted.
var values = [{val:33, title:'Hi'},{val:34, title:'Bue'},{val:0, title:'-------NA-------'}],
selected = 34;
values.forEach(function(item){
$('#dd').append($('<option>', {value:item.val, text:item.title, selected: item.val==selected}));
})
I am using Data Table in jquery. So i passed one input type text box and passed the single id. This data table will take a multiple text box. i will enter values manually and pass it into the controller. I want to take one or more text box values as an array..
The following image is the exact view of my data table.
I have marked red color in one place. the three text boxes are in same id but different values. how to bind that?
function UpdateAmount() {debugger;
var id = "";
var count = 0;
$("input:checkbox[name=che]:checked").each(function () {
if (count == 0) {
id = $(this).val();
var amount= $('#Amount').val();
}
else {
id += "," + $(this).val();
amount+="," + $(this).val(); // if i give this i am getting the first text box value only.
}
count = count + 1;
});
if (count == 0) {
alert("Please select atleast one record to update");
return false;
}
Really stuck to find out the solution... I want to get the all text box values ?
An Id can only be used once; use a class, then when you reference the class(es), you can loop through them.
<input class="getValues" />
<input class="getValues" />
<input class="getValues" />
Then, reference as ...
$(".getValues")
Loop through as ...
var allValues = [];
var obs = $(".getValues");
for (var i=0,len=obs.length; i<len; i++) {
allValues.push($(obs[i]).val());
}
... and you now have an array of the values.
You could also use the jQuery .each functionality.
var allValues = [];
var obs = $(".getValues");
obs.each(function(index, value) {
allValues.push(value);
}
So, the fundamental rule is that you must not have duplicate IDs. Hence, use classes. So, in your example, replace the IDs of those text boxes with classes, something like:
<input class="amount" type="text" />
Then, try the below code.
function UpdateAmount() {
debugger;
var amount = [];
$("input:checkbox[name=che]:checked").each(function () {
var $row = $(this).closest("tr");
var inputVal = $row.find(".amount").val();
amount.push(inputVal);
});
console.log (amount); // an array of values
console.log (amount.join(", ")); // a comma separated string of values
if (!amount.length) {
alert("Please select atleast one record to update");
return false;
}
}
See if that works and I will then add some details as to what the code does.
First if you have all the textbox in a div then you get all the textbox value using children function like this
function GetTextBoxValueOne() {
$("#divAllTextBox").children("input:text").each(function () {
alert($(this).val());
});
}
Now another way is you can give a class name to those textboxes which value you need and get that control with class name like this,
function GetTextBoxValueTwo() {
$(".text-box").each(function () {
alert($(this).val());
});
}
I'm trying to iterate a bunch of SELECT OPTION html drop-down fields and from the ones that are NOT empty, take the values and add a hidden field for a PAYPAL shopping cart.
My problem is that for some reason, the variable "curitem" is not passed inside the each function and I can't add the hidden field like they should. All I get is "NaN" or "undefined".
What PAYPAL expects is: item_name_1, item_name_2, etc. All numbers must iterate by +1.
How can I do this?
Thanks a bunch in advance
var curitem;
$.each($("select"), function(index, item) {
var attname = $(this).attr("name");
var nom = $(this).attr("data-nom");
var prix = $(this).attr("data-val");
var partname = attname.substring(0, 1);
var qte = $(this).val();
// i want all my <select option> items that the NAME start with "q" AND have a value selected
if (partname == "q" && isNaN(qte) == false && qte > 0) {
// item name
var inp2 = document.createElement("input");
inp2.setAttribute("type", "hidden");
inp2.setAttribute("id", "item_name_"+curitem);
inp2.setAttribute("name", "item_name_"+curitem);
inp2.setAttribute("value", nom);
// amount
var inp3 = document.createElement("input");
inp3.setAttribute("type", "hidden");
inp3.setAttribute("id", "amount_"+curitem);
inp3.setAttribute("name", "amount_"+curitem);
inp3.setAttribute("value", prix);
// qty
var inp4 = document.createElement("input");
inp4.setAttribute("type", "hidden");
inp4.setAttribute("id", "quantity_"+curitem);
inp4.setAttribute("name", "quantity_"+curitem);
inp4.setAttribute("value", qte);
// add hidden fields to form
document.getElementById('payPalForm').appendChild(inp2);
document.getElementById('payPalForm').appendChild(inp3);
document.getElementById('payPalForm').appendChild(inp4);
// item number
curitem = curitem + 1;
}
});
I think you have to initialize curitem variable.
var curitem = 1;
I have an UpdatePanel and in my updatepanel_Load I have some code which looks like this:
if (!IsPostBack || triggeredRefresh.Value == "1")
{
create hidden fields and add to list using
itemFields.Add(newField);
}
else if ( triggeredCheck.Value == "1" )
{
lookup field values
}
The list is declared at class level using:
List itemFields = new List();
The problem is that whenever I want to lookup values in the hidden fields the list is empty. Why is it empty at this point and how can I fix it?
Thanks
Class level fields are not persisted between postbacks. Use the Session state Collection to persist values. For persisting controls, you can use <asp:PlaceHolder />.
EDIT:
If you are using the HiddenField to just store a single value and access from server side and if it's not being accessed from client script, you can do something like this.
Remove your class level list.
if (!IsPostBack || triggeredRefresh.Value == "1")
{
Session["someValueKey"] = 0;
}
else if ( triggeredCheck.Value == "1" )
{
var x = Convert.ToInt32(Session["someValueKey"]);
}
if you do need a list of values, then you can do
if (!IsPostBack || triggeredRefresh.Value == "1")
{
Session["someValueKey"] = new List<int>{100,200};
}
else if ( triggeredCheck.Value == "1" )
{
var x = Session["someValueKey"] as List<int>();
}
if you do need it to be a control (to access from client script) you can do
if (!IsPostBack || triggeredRefresh.Value == "1")
{
HiddenField hiddenField = new HiddenField();
hiddenField.ID ="hiddenField1";
hiddenField.Value = "0";
placeHolder1.Controls.Add(hiddenField);
}
else if ( triggeredCheck.Value == "1" )
{
HiddenField hiddenField = placeHolder1.FindControl("hiddenField1") as HiddenField;
var x = Convert.ToInt32(hiddenField.Value);
}