HI so my JS skills are a little rusty but I'm trying to create a few functions so they work on the client side, rather than running server code, here's what I'm trying to do:
I have a drop down control, and a textbox. The textbox is depended on the value from down down and is disabled on page load.
i'm trying to call a function so if YES is selected from dropdown, the textbox will be enabled for text entry. Here's what I'm doing:
function DependentControlByDropDown(sender, Control, DependentControlID) {
try {
var senderControl = sender.selectedOptions[0].text;
var controlEnable = (senderControl == Control);
console.log(controlEnable);
var control = document.getElementById(DependentControlID); this gives me NULL if i do console.log(control)
DependentControlID.disabled = controlEnable; //controlEnable has a value of either TRUE or FALSE but it doesn't work on DependentControlID
}
catch (e) {
alert("DependentControlByDropDown : " + e.message);
}
}
I'm calling this in dropdown like so:
onchange="DependentControlByDropDown(this,'Yes','txtbox1')"
So what's happening here is I get the right value 'Yes', or 'No' I tested it with console.log. The problem is with the dependednt control. If I do console.log(DependentControlID) it is showing me the correct control, but when I try to disabled=false it doesn't work. I also tried document.getElementByID(DependentControlID).disabled=false but that doesn't work either. Any help?!
As we've deduced in the comments of your question, you're using ASP.NET.
This is extremely important to note, because ASP.NET overrides assigned IDs to ensure that they are unique. For example, if you were to do...
<asp:Textbox runat="server" id="txtbox1"></asp:Textbox>
...the rendered HTML may look something like (example)...
<input id="ctl00$MainContent$txtbox1">
Because of this, getElementById("txtbox1") doesn't find anything.
To prevent this from happening, you can add ClientIdMode="static" to your textbox:
<asp:Textbox runat="server" ClientIdMode="static" id="txtbox1"></asp:Textbox>
The rendered HTML will now be the following...
<input id="txtbox1">
NOTE: If you have more than one of these textboxes on the page, for example if you're using it in a GridView or a Repeater, do not use ClientIdMode="static"! It will create duplicate IDs, which are not valid.
The problem is that you were trying to access the textbox via it's ID as text. You need set the disabled attribute on it's node value, which you already have, i.e. control.
Additionally you were trying to set the textbox's disabled attribute to the same value as controlEnable. I've set it to the OPPOSITE of controlEnable
function DependentControlByDropDown(sender, Control, DependentControlID) {
try {
var senderControl = sender.selectedOptions[0].text;
var controlEnable = (senderControl == Control);
console.log('controlEnable',controlEnable);
console.log('DependentControlID', DependentControlID);
var control = document.getElementById(DependentControlID);
console.log('control', control);
control.disabled = !controlEnable;
} catch (e) {
alert("DependentControlByDropDown : " + e.message);
}
}
<input id="txtbox1" />
<select onchange="DependentControlByDropDown(this,'Yes','txtbox1')">
<option value=""></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
Related
I have web form and JavaScript function like this:
web form
<div>
<asp:DropDownList runat="server" ID="ddlType">
<asp:ListItem Value="1" Text="Type1"></asp:ListItem>
<asp:ListItem Value="2" Text="Type2"></asp:ListItem>
</asp:DropDownList>
<asp:LinkButton ID="lnkTest" OnClientClick='<%= "getValue('0' + '|' + 'ddlType.SelectedValue');return false;" %>' runat="server" Text="text">
new
</asp:LinkButton>
</div>
JavaScript function
<script>
function getValue(Input) {
var result = Input.split("|");
section1 = result[0];
section2 = result[1];
}
</script>
I need to pass string includes '0' (hardcoded) and ddlType.SelectedValue to getValue.
This web form has syntax error Server tags cannot contain <% ... %> constructs (I know). I can get selected value by getElementById but I want to pass SelectedValue as argument. I read many posts but none of them don't pass SelectedValue.
It would be very helpful if someone could explain solution for this problem.
SelectedValue is a server-side value. It's available to the server-side code at page load (i.e. before the page is rendered to the user). In javascript it has no meaning at all, and isn't available at the time when a user clicks on the link.
If you want to get the selected value on the client side you can do something like this:
First get rid of the all the OnClientClick code from your LinkButton.
Second, write some javascript like this (at the bottom of the page, after all your HTML/ASP markup:
document.getElementById("<%=lnkTest.ClientID %>").addEventListener("click", function(event) {
event.preventDefault(); //stop default action of the link button, to allow script to execute
var selectedVal = document.getElementById("<%=ddlType.ClientID %>").value;
getValue('0|' + selectedVal);
});
This will cause the browser to listen for a user clicking on the button, and then run the JS function given. That function fetches the currently selected value of the dropdown (as selected in the browser - at this point the server has no idea what's selected because no postback has happened) and passes that selected value to your existing getValue function.
N.B. In case you're wondering, the reason I use the contruct <%=ddlType.ClientID %> is because ASP.NET dynamically creates the client-side ID of each element based on the structure of the server-side controls it lies within. So just relying directly on the server-side ID (e.g. "ddlType") will not reliably identify the element in the rendered DOM. .NET provides the ClientID value at runtime in order to allow us to access the generated ID.
i want to get select values of jquery select2 plugin in asp.net code behind.
Here is my source
Client Side:
<select id="ddlcountry" runat="server" class="select" style="width: 100%;">
</select>
Code Behind:
var query1 = from pcountry in CTX.Countries
orderby pcountry.Country1 ascending
select new
{
pcountry.CountryId,
pcountry.CountryName
};
if (query1 != null)
{
ddlcountry.DataSource = query1.ToList();
ddlcountry.DataValueField = "CountryId";
ddlcountry.DataTextField = "CountryName";
ddlcountry.DataBind();
ddlcountry.Multiple = true;
}
protected void btnSave_Click(object sender, EventArgs e)
{
Now i want to get all the selected country values here ?
}
Please help me,i will be very thankful.
If you're not creating the <select> element as an <ASP:DropDownList> control, then I don't believe you will have access to properties and methods such as "Datasource", etc. You can, however, access HTML elements that have the runat="server" attribute added.
I believe the <option> tag is of the generic HTML control type. I stick to VB.Net, so I'll have to write some psuedo code for you...
For each o as HtmlGenericControl in ddlcountry.Children.ofType(of HtmlGenericControl)
If o.Attributes("selected") then
' Here you can access your option value using the "value" attribute (and InnerHtml works too, I think)
End if
Next o
Here's a link to an answer where I showed how to loop through generic controls using a working example:
how can I get HTML attribute from ASP/VB.net code-behind
Thanks Lopsided,i appreciate your kind help.I tried this but it doesn't work for me.
According to your answer i thought some solution,should i get the select2 option list value in client side and store it into hiddenfield and then i get the hidden field value into server side code?
You can just loop through the items collection to find out which countries have been selected.
foreach (ListItem li in ddlcountry.Items) {
if ((li.Selected)) {
//Selected Country
}
}
I'm trying to find the best way to make my teachers' lives a little easier.
I've got a select field and list of options generated by a tlist sql query. The select field itself already has a javascript attached to it, which fleshes out other field values (credit values and credit types) elsewhere based on the id of the select option chosen. This is the javascript that works for that purpose:
<script type="text/javascript">
function changeValue(){
var option=document.getElementById('courseno').value;
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
}
</script>
I also need to populate a hidden field that is (and must remain) outside the tlist sql tag that generates the select list.
Here is my sql code:
<select id="courseno" name="course_number" onchange="changeValue();">
<option value="">Select a Course</option>
~[tlist_sql;
SELECT cc.course_number, cc.section_number, c.COURSE_NAME
FROM cc cc
RIGHT JOIN COURSES c ON c.COURSE_NUMBER = cc.course_number
RIGHT JOIN STUDENTS s ON cc.studentid = s.id
WHERE cc.studentid = ~(curstudid)
AND TERMID = ~(curtermid)
AND c.CreditType LIKE 'English%'
AND NOT EXISTS (
SELECT * FROM storedgrades sg
WHERE sg.studentid = ~(curstudid)
AND sg.course_number = c.course_number
)
ORDER BY c.course_name;]
<option name="~(course_no)" value="~(course_no)" id="~(secno)">~(course_no).~(secno) (~(cname))</option>
[/tlist_sql]
</select></td>
</tr>
And just below that is the hidden field I would like to populate:
<td width="25%" class="bold"> </td>
<td><input type="text" id="secnum" name="section_number" value=""> </td>
I gave each of the options the section number as its ID, thinking I could use the ID element of each of those options and some clever jquery to populate the hidden field, but I'm having no luck. I just read on another question that was ably answered by the community that you shouldn't use an option ID tag that begins with a number... so now what can I do?
Could somebody please help me?
Thanks forever,
Schelly
I don't think your problem comes from the ID being a number. We haven't seen what jQuery you've tried, but you most likely don't need jQuery at all. Assuming what you have is working correctly, and the PowerSchool code is putting out elements the way you expect them to be (View Source in your browser to be sure, if this doesn't work), you should be able to grab the ID from the selected option inside your changeValue function, store it in a variable, and push that value into the "secnum" field as follows:
function changeValue(){
var courseDropdown = document.getElementById('courseno');
var selectedElement=courseDropdown.options[courseDropdown.selectedIndex];
var option=selectedElement.value;
var courseNo = selectedElement.getAttribute("id");
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
document.getElementById('secnum').value=courseNo;
}
I changed the way that your "option" variable is being set, but it will work the same way. You might end up wanting to move the last line, where the "secnum" field is being set, or wrap it in an "if", etc.; I don't know your full requirements.
All that said, there would be nothing wrong with using jQuery in this situation, but it's not necessary in this case unless you need extreme backwards-browser compatibility.
Working Example Here
You can use multiple on change events to do whatever you want. On change add a new event and populate the hidden input. You can define custom attributes to any html element with any data that is required to populate the hidden input
<select id="myselect">
<option>Select</option>
<option data-number="1">One</option>
<option data-number="2">Two</option>
<option data-number="3">Three</option>
<option data-number="4">Four</option>
<option data-number="5">Five</option>
</select>
<input type="hidden" id="hiddenInput"/>
$(document).ready(function(){
$('#myselect').on('change', mySelectChange);
function mySelectChange(){
console.log('your standard change value here');
}
$('#myselect').on('change', mySelectChange2);
function mySelectChange2(){
var option = $("#myselect option:selected");
console.log(option.text());
console.log(option.attr('data-number'));
}});
I have a series of textboxes on a form. When the user inserts numbers into these textboxes, calculations are made and <asp:Label> controls are updated via JavaScript to reflect these calculations:
document.getElementById('<%=TotalLoans.ClientID %>').innerHTML = TotalLoans;
This correctly updates the UI. However, when I try to access the value in the codebehind, the Text property is empty. This makes sense I guess, since I was updating the innerHTML property via the JavaScript.
//TotalLoans.Text will always be equal to "" in this scenario
double bTotalLoans = string.IsNullOrEmpty(TotalLoans.Text)
? 0.00
: Convert.ToDouble(TotalLoans.Text);
How do I update the Text property of the <asp:Label> via JavaScript in such a way that I can read the property in the codebehind?
Update
This is a small problem on a large form that contains 41 labels, each of which displays the results of some calculation for the user. Taking the advice of FishBasketGordo I converted my <asp:Label> to a disabled <asp:TextBox>. I'm setting the value of the new textbox as such:
document.getElementById('<%=TotalLoans.ClientID %>').value = TotalLoans;
Again, in the codebehind, the value of TotalLoans.Text is always equal to "".
I don't mind changing how I approach this, but here's the crux of the matter.
I am using JavaScript to manipulate the property values of some controls. I need to be able to access these manipulated values from the code behind when 'Submit' is clicked.
Any advice how I can go about this?
Update 2
Regarding the answer by #James Johnson, I am not able to retrieve the value using .innerText property as suggested. I have EnableViewState set to true on the <asp:Label>. Is there something else I am missing?
I don't understand why, when I type in a textbox and submit the form, I can access the value in the codebehind, but when I programmatically change the text of a textbox or label by way of JavaScript, I cannot access the new value.
Place HiddenField Control in your Form.
<asp:HiddenField ID="hidden" runat="server" />
Create a Property in the Form
protected String LabelProperty
{
get
{
return hidden.Value;
}
set
{
hidden.Value = value;
}
}
Update the Hidden Field value from JavaScript
<script>
function UpdateControl() {
document.getElementById('<%=hidden.ClientID %>').value = '12';
}
</script>
Now you can access the Property directly across the Postback. The Label Control updated value will be Lost across PostBack in case it is being used directly in code behind .
This one Works for me with asp label control.
function changeEmaillbl() {
if (document.getElementById('<%=rbAgency.ClientID%>').checked = true) {
document.getElementById('<%=lblUsername.ClientID%>').innerHTML = 'Accredited No.:';
}
}
Use the following code
<span id="sptext" runat="server"></span>
Java Script
document.getElementById('<%=sptext'%>).innerHTML='change text';
C#
sptext.innerHTML
Instead of using a Label use a text input:
<script type="text/javascript">
onChange = function(ctrl) {
var txt = document.getElementById("<%= txtResult.ClientID %>");
if (txt){
txt.value = ctrl.value;
}
}
</script>
<asp:TextBox ID="txtTest" runat="server" onchange="onChange(this);" />
<!-- pseudo label that will survive postback -->
<input type="text" id="txtResult" runat="server" readonly="readonly" tabindex="-1000" style="border:0px;background-color:transparent;" />
<asp:Button ID="btnTest" runat="server" Text="Test" />
Asp.net codebehind runs on server first and then page is rendered to client (browser). Codebehind has no access to client side (javascript, html) because it lives on server only.
So, either use ajax and sent value of label to code behind. You can use PageMethods , or simply post the page to server where codebehind lives, so codebehind can know the updated value :)
Since you have updated your label client side, you'll need a post-back in order for you're server side code to reflect the changes.
If you do not know how to do this, here is how I've gone about it in the past.
Create a hidden field:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
Create a button that has both client side and server side functions attached to it. You're client side function will populate your hidden field, and the server side will read it. Be sure you're client side is being called first.
<asp:Button ID="_Submit" runat="server" Text="Submit Button" OnClientClick="TestSubmit();" OnClick="_Submit_Click" />
Javascript Client Side Function:
function TestSubmit() {
try {
var message = "Message to Pass";
document.getElementById('__EVENTTARGET').value = message;
} catch (err) {
alert(err.message);
}
}
C# Server Side Function
protected void _Submit_Click(object sender, EventArgs e)
{
// Hidden Value after postback
string hiddenVal= Request.Form["__EVENTTARGET"];
}
Hope this helps!
The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.
I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:
You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.
I have an ASP.NET TextBox ID="txtDate" in my usercontrol. It has ValidationGroup="MyUC" set. Now my UC is inside a Repeater Control. So there will be multiple instances of the same textbox.
I am able to get all textboxes like: $("[id$='_txtDate']");
Each of the txtDate will have a separate ValidationGroup assigned to it, dynamically.
So I want to get a textbox based on the id + ValidationGroup using jQuery / javascript.
How can it be done? Any guidance really appreciated.
Edited based on Josiah's Reply and the way I found:
Sorry, my scenario is kind of complicated to include entire code. In short the textboxes are attached to jquery datepicker and the code below runs when a date is selected. The same handler is attached to multiple textboxes. Here is what I have:
var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
var txtdate2 = $("[id$='txtDate']").filter(function(){return this.validationGroup == valgrp;});
alert("date1- " + txtdate1.val()); /*this returns date selected from datepicker*/
alert("date2 " + txtdate2.val()); /*this returns empty*/
Depending on the date I want to do something else. So txtdate1 is currently working for me where I don't have to add class to my textbox. I was playing with the txtdate2 which isn't behaving how I was expecting and so I had to post this question.
Here is a sample test to see this.validationGroup not returned:
$(function () {
$("#btntest").click(function () {
$("[id$='txtDate']").each(function () {
alert(this.validationGroup);//returns undefined
alert(this.Validators[0].validationGroup); //returns "test"
});
});
});
<input id="btntest" type="button" value="button" />
<asp:TextBox ID="txtDate" runat="server" ValidationGroup="test"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="*" ErrorMessage="Required." ControlToValidate="txtDate" ValidationGroup="test"></asp:RequiredFieldValidator>
While Josiah's solution didn't work but his idea of attaching class to textbox could have been a potential solution. Since it didn't exactly fit my needs I would answer my own question. Here is the solution I came up with:
var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
The above returns me the textbox I am looking for. The key is
this.Validators[0].validationGroup
It gets the validationGroup of the first validator control attached to the textbox (this).
From a few searches, the validation group is stored as a property on the Form Element.
So you can add a class selector like so:
$("[id$='_txtDate']").each(function(){
var group = this.validationGroup,
$this = $(this);
if(!$this.hasClass('validationgroup'))
$this.addClass('validationgroup ' + group);
});
Of course if you have a repeater you will need to run this code each time an row is repeated. But now you can select fields by validation group like this:
$('.validationgroup.[group name]')
I don't use jQuery, but I'd think it would be:
$("#txtDate[ValidationGroup='MyUc']")
since jQuery's selectors are based on CSS. That works with document.querySelector, unless having more that one element with the same id is causing problems.