Set Dropdownlist selected index with javascript? - 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);
});

Related

asp.net pass value from javascript to control on a modal popup

Ok, I changed the title because I can't get anywhere with previous approach, so I'm returning to the original question: how can I pass a variable obtained through javascript to a textbox on a modal popup?
I already tried to place a hidden field and even a textbox on the parent page, inside or outside an update panel, but when I click on the linkbutton that opens the modal popup their values are resetted to default.
I already searched and tried many different ways but I can't succeed.
I have a table in a repeater and I need to know the cells selected by the user: start and ending cell of the selection. I accomplish that with this javascript:
$(function () {
var mouse_down = false;
var row, col; // starting row and column
var $tr;
$("#tblPersonale td")
.mousedown(function () {
$("#col_to").html('?');
mouse_down = true;
// clear last selection for a fresh start
$(".highlighted").removeClass("highlighted");
$(this).addClass("highlighted");
$tr = $(this).parent();
row = $tr.parent().find("tr").index($(this).parent());
col = $tr.find("td").index($(this));
$("#row").html(row);
$("#col_fr").html(col - 1);
return false; // prevent text selection
})
.mouseover(function () {
if (mouse_down) {
$("#col_to").html('?');
if ($tr[0] === $(this).parent()[0]) {
var col2 = $(this).parent().find("td").index($(this)); // current column
var col1 = col;
if (col > col2) { col1 = col2; col2 = col; }
$("#col_fr").html(col1-1);
$("#col_to").html(col2 - 1);
// clear all selection to avoid extra cells selected
$(".highlighted").removeClass("highlighted");
// then select cells from col to col2
for (var i = col1; i <= col2; i++) {
if (col1>1){
$tr[0].cells[i].className = "highlighted";}
}
}
}
})
.bind("selectstart", function () {
return false; // prevent text selction in IE
})
$(document)
.mouseup(function () {
mouse_down = false;
});
});
So, when user selects one or more cells I have the start/end value in here:
<span id="col_fr" runat="server" enableviewstate="true">?</span>
<span id="col_to" runat="server" enableviewstate="true">?</span>
Then, when user click a linkbutton I want to use these values to write a text in a textbox on the modal popup that shows. As I said, I can't make it work, anything I tried the result is that the values are lost when popup shows, even if I assign values to global variables before showing the popup.
This is my linkbutton:
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click">
The idea behind the old question was to pass the values to the url as parameters and then in the page load use them, but then the table selection doesn't work anymore because at every selection the page refresh because of the url change.
Please anyone, I'm totally lost and not for lack of trying!
OLD QUESTION
asp.net pass a control value as parameter in onclientclick
I found similar questions but no one answer to my problem (or at least, I can't make anything working).
I want to concatenate to the url of the active page some parameters like Home.aspx?col_fr=2 where instead of the fixed "2" I want to pass the value of a hidden field. How can I achive that?
This is my current code:
<asp:hiddenfield runat="server" id="hdnColonnaDa" EnableViewState="true" />
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="window.location='Home.aspx?col_fr=2';return false;">
Thanks
It just have to move the parameter code o a javascript function like
function getURL(){
var param1 = someField.value/*get field value*/;
var url= "Home.aspx?col_fr="+ param1;
window.location= url;
return false;
}
Html
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="getURL()">
Don't use UpdatePanel or Modal popup server side. You can use a Thickbox or similar jquery plugin to open the popoup.
Popup can be an inpage div or another page. In case of page, you can easily pass parameters in the url, in case of inpage div, you can get hidden field values.
You can find jquery overlay as Thickbox: just add css and js to your site, the right class on the link and fix the url to open.
Solution using another page
Imagine to use Colorbox (http://www.jacklmoore.com/colorbox/):
PRE
Suppose you have your variable values in some hidden field in your page
TODO
include jquery in your page
Download and include css and js for colorbox
In your page add a html tag with on click event
Add a script section in your page
function openLink()
{
var hiddenValue= $("#col_fr").text(); // or .html()
var urlToOpen = "yourpage.aspx?ids=" + hiddenValue;
$.colorbox({
iframe: true,
width: "75%",
height: "75%",
href: urlToOpen
});
}
Then in Yourpage.aspx you can use url parameter "ids".
Code is not tested!
Finally I did what I want by tuning the original javascript function.
I added 3 hiddenfield on the page and then I add this bit
var hdncol_fr = document.getElementById("hdncol_fr").value;
var hdncol_to = document.getElementById("hdncol_to").value;
var hdnrow = document.getElementById("hdnrow").value;
if (hdncol_fr = '?'){
document.getElementById("hdncol_fr").value = col - 1;
document.getElementById("hdncol_to").value = col2 - 1;
document.getElementById("hdnrow").value = row;
}
This way the hidden fields values are set only when user actively select some cells, when there is a postback event the javascript function returns '?' for the 3 values, so with the added code the hidden field maintains the previous values until user select something else.

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

Create Dynamic checkboxes by iterating JSONArray in DOJO

I am new to DOJO and I am using DOJO 1.5.0 version.
I want to create dynamic checkboxes by iterating JSONArray in DOJO. This dynamic creation will be done on a particular event like when we selecting some combo-box value.
For example consider below JSONArray:
var tempJSONArray = [{role_id = '1', role_name = 'role1'},{role_id =
'2', role_name = 'role2'},{role_id = '3', role_name = 'role3'}]
I want display checkboxes corresponding to Role Name. Lable for checkbox will be role_name and value will be role_id from JSON object.
Also I want to add 'onChange' event to check-boxes, as on this event I want to do a Ajax call to server with role_ids.
Thank you for reading and also please let me know if further clarification is needed.
You can use the dojo.create() method for creating DOM nodes and the dojo.place() method for placing them inside another element, for example:
var checkbox = dojo.create("input", {
type: "checkbox",
value: "1"
});
You will probably have to wrap it inside a <label> to show the text (which you can also create with dojo.create()). Then you can place them inside a list, for example:
dojo.place(label, "checkboxes");
This will wrap the checkbox (or label) inside an element with ID checkboxes. So, if you create your checkboxes now inside a loop, it should work.
After doing some internet surfing and playing around code I able write below code, which working fine for my scenario. So thought it will be helpful for others.
for ( var i = 0; i < roleJSON.length; i++) {
var role = roleJSON[i];
var tr = dojo.create("tr",{id:"rolebasecheckbox"+i,'class':'rolebasecheckbox'});
alert("tr=" + tr);
var td= dojo.create("td",{innerHTML:'<input id="roleBaseCb_'+i+'" value="'+role.role_id+'" dojoType="dijit.form.CheckBox" onclick="alert('onclick event')" type="checkbox" /> <label for="roleBaseCb_'+i+'">'+role.role_name+'</label>',align:'center'},tr);
alert("td=" + td);
if(i==0){
alert("i is 0");
dojo.place(tr, "roleBaseComboTR", "after");
}else{
dojo.place(tr, "rolebasecheckbox"+(i-1), "after");
}
}

backbone sync passes wrong parameters

It's a pretty simple trick that I thought should work fine however it doesn't. So I have multiple checkboxes on the page. And whenever they are changed I would like to record any change to the database. So in the view event 'click' on checkbox I have similar to this:
var filter_name = $(e.target).attr("name");
var filter_value = $( "input:checkbox[name=" + filter_name + "]:checked" ).map(function () {
return this.value;
}).get();
console.log("filter_name: " + filter_name); #=> my_method_name
CarInsuranceApp.aciq.set({filter_name: filter_value});
CarInsuranceApp.aciq.save();
And here the results that I receive as a JSON:
"filter_name"=>"extra"
So my question would be how to dynamically pass model attribute name on the set?
use like this.
CarInsuranceApp.aciq.set(filter_name, filter_value);
Here is a possible one line JavaScript`ish solution:
CarInsuranceApp.aciq.attributes[filter_name] = filter_name;

Clearing select options with javascript on change

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.

Categories

Resources