How to change asp.net DropDownList SelectedValue using javascript? - javascript

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

Related

Get current option in multiselect

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

In Jquery take a different values from single text box id

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

get all checked checboxes and add their names and values in array

I have large form mainly drop down lists and checkboxes. Checkboxes are created dynamically so i don't know their id's before they are created. I use drop down onChange event to do create them on the fly.
How can i loop trough the form and get all the checkboxes that are checked, that is their id and their value? I need to do this only for check boxes that are checked. All checkboxes share the same name, that is: categoriesfilters[]. Currently i have on click event on the checkbox which invoke the javascript function.
Here is the code:
function update_number_of_adds_found(field_dropdown,selected_value) {
selected_value="";
var addtypeid = $("#addtypeid").val();
// trying to store the values of the checkboxes
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
alert(value);
}
);
var selected_value = {
addtypeid: addtypeid,
// need to add the ids and the values here as well
};
var url = "<?php echo site_url('search/findNumberOfAdds'); ?>";
$.post(url, selected_value, function(r){
if(r) {
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(r.result);
} else {
// alert(selected_value);
}
}, 'json')
}
Regards, John
Try this :
var categories = [];
$("input[name='categoriesfilters[]']:checked").each(
function() {
var id = $(this).attr("id");
var value = $(this).val();
categories[categories.length] = {id : value};
}
);
console.log(categories);
$.post(url, categories, function(r){
...
Try this :
$('form').submit(function(){
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
}
);
});
I guess you want to check that on form submit.
var arr = [];
$('input[name^="categoriesfilters"]:checked').each(function() {
var obj = {
id: $(this).attr('id');
value: $(this).val();
};
arr.push(obj);
});
console.log(arr); // show us the array of objects
Would you like to use Jquery?
Add a class to each of the checkbox i.e "class_chk";
$(function(){
$('.class_chk').each(function(){
if($(this).is(':checked')){
var id = $(this).attr('id');
var val = $(this).val();
alert("id = "+id+"---- value ="+val);
}
});
});
The above way you can get all the check box id and value those are checked.
Thanks..

How to change DropDownList Selected value in Javascript?

how to change the selected value in javascript and get the selected value in codebehind page? AutoPostBack is set to false.
You can change it like this:
var ddl = document.getElementById('ddl-id');
var opts = ddl.options.length;
for (var i=0; i<opts; i++){
if (ddl.options[i].value == "some-value"){
ddl.options[i].selected = true;
break;
}
}
//setting the value of a drop down list
document.getElementById('my_drop_down').selectedIndex=2;

How to pass a variable inside a jquery function $.each($("abc")...?

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;

Categories

Resources