Updating of the asp.net dropdown control using javascript - javascript

In my ASP.Net default.aspx, I have dropdown list control and following javascript code
<asp:DropDownList ID="ddlGenres" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="EntityDataSource2" DataTextField="cityID" DataValueField="cityID" OnSelectedIndexChanged="ddlGenres_SelectedIndexChanged" ClientIDMode="Static" >
<script type="text/javascript">
var ddlClientID = '<%=ddlGenres.ClientID%>';
//document.getElementById(ddlGenres)
function SetddlVal(nIndx)
{
//$("#ddlGenres")
var ddlListSelect = document.getElementById(ddlClientID);
ddlList.SelectedIndex = nIndx;
}
</script>
====================================================================
In a external javascript file, I am calling the function SetddlVal.
I debugged the code and the ddlList selectedIndex is successfully changed within the script.
=====================================================================
The issue I am facing is, when the SelectedIndex value is changed in the javascript, The ddlGenres_SelectedIndexChanged code is not being triggered.
Please let me know if I am missing anything.
Thanks
Nate

In javascript the property of an <select> input is selectedIndex not SelectedIndex.
Change your function to this:
function SetddlVal(nIndx)
{
var ddlListSelect = document.getElementById('<%=ddlGenres.ClientID%>');
ddlListSelect.selectedIndex = nIndx;
}

Related

Retrieve value from javascript funcion on client click

I have a function on JS that must execute before the codebehind, but i'm having trouble retrieving it.
It will return a variable that i should use on the codebehind. The function i created is this one:
<script type="text/javascript" >
function returnHash() {
var checkout = new DirectCheckout('086F7D02A071267FEBF102EB759D9845B8B3333DFA65BC45B807F41A8525AD8D'); /* Em sandbox utilizar o construtor new DirectCheckout('SEU TOKEN PUBLICO', false); */
debugger;
var month = document.getElementById("txtDataVencUser").value;
var year = document.getElementById("txtDataVencUser").value;
var cardData = {
cardNumber: document.getElementById("txtNumeroCartaoUser").value,
holderName: document.getElementById("txtNomeCartaoUser").value,
securityCode: document.getElementById("txtCodSegurancaUser").value,
expirationMonth: month.substring(0, 2),
expirationYear: "20" + year.substring(3, 5)
};
checkout.getCardHash(cardData, function (cardHash) {
----------------------------> I NEED TO RETRIEVE "cardHash" VALUE IN CODEBEHIND
}, function (error) {
console.log(error);
});
}
</script>
I don't know if this step is correct, but i am using the onClientClick to try to execute the JS before the codebehind:
<asp:Button ID="btnFinalizarCompraJunoUser" runat="server" Text="FINALIZAR COMPRA" OnClientClick="returnHash()" OnClick="btnFinalizarCompraJunoUser_Click" Visible="true" />
I am having trouble figuring out what to do next, can someone help me please?
There are a number of ways - perhaps as many flavors of ice cream.
But, since you are going to run a "code behind" stub based on the click?
I would just drop a hidden field on the page, and then just set that value in js
So right below your button - add a hidden field say like this:
<form id="form1" runat="server">
<br />
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="myfun();return true" Width="68px"
ClientIDMode="Static"/>
<asp:HiddenField ID="HiddenField1" runat="server" ClientIDMode="Static" />
</form>
<script type="text/javascript">
function myfun() {
// do whatever - walk the dog - have fun!!!
var f1 = document.getElementById("HiddenField1");
f1.value = "2222";
}
</script>
So in above I just shove 2222 into the hidden1 field.
Now, in the the code behind button stub, you can do this:
Debug.Print("my click f1 = " & HiddenField1.Value);
So the code behind will now have a good old regular plane jane control to look at and get the value in question.
So, it depends on how many values - but using a code behind friendly (asp.net) control and setting the value with the js client side code probably is the least effort here.
I also of course used "staticID" for the above. If you for some reason don't like (or want) to use staticID for above, then the js selection would be:
var f1 = document.getElementById("<%=HiddenField1.Clientid%>");
f1.value = cardHash;

Asp radio buttons is not calling javascript function

I am working on using asp :radio buttons. I am trying to use 2 radio buttons so that if any one of them is selected then other will be unchecked. I am calling JavaScript function on change event of these buttons. That function will add some values and return the out put in the textboxes.I tried to use normal asp buttons then switch to radio button groups and now trying radio button list. need to call javascript function on radio button change event.These buttons will checked and unchecked but java script function is not returning correct values. I guess there are some naming conventions which are not correct or something is not working . looking forward for help to fix this. Neither one of these 3 way is working.
My test.aspx file contains
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="span2">Test Career:</div>
<div class="span8">
<asp:RadioButton ID="TestCareerList" runat="server" clientmode=Static Text="MasterDegree">
</div>
</ContentTemplate>
</asp:UpdatePanel>
Document.ready function in aspx page
$(document).ready(function () {
$("input:radio").click(function ()
{
updateYears();
}
}
javascript function is:
function updateYears() {
var yrsDocTemp = parseFloat(yrsDoc);
var yrsMastTemp = parseFloat(yrsMast);
if ($("ContentPlaceHolder2_drpEmplClass").val() != "" && $("#ContentPlaceHolder2_StudentCareerList]").SelectedValue!= "") {
var updateValue = 0;
//Get EmplCalss
if ($("#ContentPlaceHolder2_drpEmplClass").val() == "GA") {
updateValue = updateValue + 1;
}
else if ($("#ContentPlaceHolder2_drpEmplClass").val() == "GAF" || $("#ContentPlaceHolder2_drpEmplClass").val() == "GAP") {
updateValue = updateValue + .5;
}
if ($("#ContentPlaceHolder2_Career").Text =="DoctoralDegree")
{
yrsDocTemp = yrsDocTemp + updateValue;
}
else if ($("#ContentPlaceHolder2_Career").Text == "MastersDegree") {
yrsMastTemp = yrsMastTemp + updateValue;
}
}
//Update the fields
$("#ContentPlaceHolder2_drpYearsDoctoral").val(yrsDocTemp);
$("#ContentPlaceHolder2_drpYearsMasters").val(yrsMastTemp);
}
I am calling this function under document.ready function like this-
$("input:RadioButtonList[ID=^TestCareerList").change(function(){
updateYears();
});
$("#ContentPlaceHolder2_drpEmplClass").change(function () {
updateYears();
});
When I debug the javascript code I see the names of buttons have been changed.
<tr>
<td>
<input id="ContentPlaceHolder2_TestCareerList_0" type="radio" name="ctl00$ContentPlaceHolder2$TestCareerList" value="MastersDegree" />
<label for="ContentPlaceHolder2_TestCareerList_0">Master</label>
</td>
<td><input id="ContentPlaceHolder2_TestCareerList_1" type="radio" name="ctl00$ContentPlaceHolder2$TestCareerList" value="DoctoralDegree" />
<label for="ContentPlaceHolder2_TestCareerList_1">Doctoral</label>
</td>
</tr>
Kindly looking for help.
This is trying to bind to your server-side elements:
$("input:RadioButtonList[ID=^TestCareerList")
But JavaScript has no knowledge of the server-side code. It only operates on the client-side code. And, as you've noticed, your client-side HTML is different. So your JavaScript needs to target that code. Something like this:
$("input:radio[ID=*TestCareerList")
The same would be true for any other selectors you have. As you're discovering, WebForms controls are famously not great for finely controlling your client-side code. ASP.NET MVC makes this a lot easier, but may be a pretty fundamental shift for what you're doing.
One thing that may help is setting your ClientID property on some controls to Static. Take care when doing this however and debug your HTML accordingly, because if you end up with repeated id values in your HTML then it's invalid and the behavior of the JavaScript when selecting on that id would be undefined.

call javascript function on asp dropdown list change

<script type="text/javascript">
function ddl(id) {
// var id = document.getElementById('<%=DDLquestionType.ClientID%>').value;
if (id == "Open") {
AmericanAnswer.style.display = 'none';
document.getElementById('Answer1_Btn').style.visibility = false;
}
alert(id);
}
</script>
<asp:DropDownList ID="DDLquestionType" CssClass="ddlQuestionType box" runat="server" AutoPostBack="True" onchange="ddl(this)" >
<asp:ListItem Text="American" Value="American"></asp:ListItem>
<asp:ListItem Text="Open" Value="Open"></asp:ListItem>
<asp:ListItem Text="Yes/No" Value="YesNo"></asp:ListItem>
<asp:ListItem Text="Numerical" Value="Numerical"></asp:ListItem>
</asp:DropDownList>
I have this java script function:
Which I try to call on drop down list selection change
It doesn't work.
I also tried
onchange="javascript:ddl()" and function without parameters,
ononchange="javascript:ddl(this);",
ononchange="javascript:ddl(this.value);",
and many others.
I'm new to java script, any links with explanations also will be highly appreciated
you dosent need to pass this parameter or id, you just call the function and onchange() event call the function.
in javascript use id of your dropdown list to get the value of dropdown list.
<script type="text/javascript">
function processchange(value)
{
if(ddl.value=="American")
// your code
}
</script>
<dropdownlist id="ddl" onchange="processchange()" >
//enter your dropdown items
</dropdownlist>
When you pass this as a parameter, you pass the DropDownList itself to the Javascript function. Therefore, you don't need to use the id to retrieve the control. You can get the value of the selected item with the value property, and you can access the items with the options array.
<asp:DropDownList runat="server" onchange="processChange(this);" ... >
function processChange(ddl) {
if (ddl.value == 'Open') {
var americanItem = ddl.options[0];
...
}
}
Since you have set AutoPostBack="true" for the DropDownList, some of the changes that you make in your Javascript function may be lost after the postback. You can try with AutoPostBack="false" to see the difference.

Need to identify which textbox is used using javascript

I have four text boxes in 4 different tabs of an ASP.NET Page. I need to provide same validation message to all the text boxes. Presently I am using four different functions with same functionality. Kindly suggest a way to identify which textbox is being used make that a single funtion
Code from Commend:
<asp:TextBox ID="textBox1" runat="server" ValidationonGroup="abcd"></asp:TextBox>
<asp:CustomValidator ID="ID1" runat="server" ValidationGroup="abcd"
ControlToValidate="textBox1" ErrorMessage="message"
ClientValidationFunction="fname"></asp:CustomValidator>
--Javascript Fn--
function fname(sender, args) {
var x = document.getElementById('<%=txtBox1.ClientID%>').value;
if (some condition) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Edit
if you are using Asp.Net then you should use like this
Aspx page code
<div>
<asp:TextBox runat="server" ID="txt1" ClientIDMode="Static" onKeyPress="javascript:text_changed(this.id);"></asp:TextBox>
</div>
JS Code
<script type="text/javascript">
function text_changed(event)
{
var id = event;
alert(id);
}
</script>
You got the textbox id in id variable and now u can get value etc using this id you are applying your conditions.... i hope this will help u

How to pass ID to a java script function in ASP.NET

Hi, I have following java script function:
function EnableDisableTextBox(chkBoxId, txtBoxId) {
var isChk = document.getElementById(chkBoxId);
document.getElementById(txtBoxId).disabled = !(isChk.checked);
}
When I am trying to call above function, by clicking check box its not working as expected
<asp:CheckBox ID="chkBachelors"
onclick="javascript:EnableDisableTextBox('chkBachelors','txtFirstDegree');"
runat="server" Text='<%$Resources:Resource, FirstDegree %>' TextAlign="Left"/>
<asp:TextBox ID="txtFirstDegree" CssClass="form-text" runat="server"
MaxLength="250"></asp:TextBox>
Expected Result (When user click chkBachelors check box):
if "chkBachelors" check box is checked
then enable "txtFirstDegree" text box
else
disable "txtFirstDegree" text box
What is the problem and how to solve it?
<asp:CheckBox ID="chkBachelors"
onclick="EnableDisableTextBox(this);"
runat="server" Text='' TextAlign="Left"/>
<asp:TextBox ID="txtFirstDegree" CssClass="form-text" runat="server"
MaxLength="250"></asp:TextBox>
<script language ="javascript" type="text/javascript">
function EnableDisableTextBox(checkbox)
{
var txtBoxId= "<%=txtFirstDegree.ClientID%>";
document.getElementById(txtBoxId).disabled = !(checkbox.checked);
}
</script>
<%=chkBachelors.ClientID%> and <%=txtFirstDegree.ClientID%> will give the client side ID of the Asp.Net controls .You don't need to pass them explicitly
function EnableDisableTextBox() {
var isChk = document.getElementById(<%=chkBachelors.ClientID%> );
document.getElementById(<%=txtFirstDegree.ClientID%>).disabled = !(isChk.checked);
}

Categories

Resources