How to find control from InsertItemTemplate in Java Script - javascript

I am new to Java Script. I have a aspx ListView with InsertItemTemplate and some buttons in it.Now i need to access the buttons from insertitemtemplate in JavaScript to disable it. This is not working?
document.getElementById('<%= Button1.ClientID %>').disable = true;
Please help me.

Solution 1
You can set the Javascript code in code-behind, where you have access to the ClientID property of the controls for each item of the ListView. For example, if you have two buttons in the item template and you want to disable btn2 when clicking on btn1, you can set the client code in the ItemDataBound event:
void lstView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.InsertItem)
{
Button btn1 = e.Item.FindControl("btn1") as Button;
Button btn2 = e.Item.FindControl("btn2") as Button;
btn1.OnClientClick = string.Format("var btn2 = document.getElementById('{0}'); btn2.disabled = true; return false;", btn2.ClientID);
}
}
Solution 2
If you cannot use the first method, but can modify the markup, then you can give the button a name that is unique in your page and set the ClientIDMode of the button to Static:
<asp:Button ID="btnUniqueName1" runat="server" ClientIDMode="Static" ... />
Since there is at most one insert item in the ListView, that ID should be unique in the form. You can retrieve the button like this:
document.getElementById('btnUniqueName1');
Solution 3
If you must find the button without modifying the server code, you can retrieve all the buttons in the form and look for some attribute that is found only in the button you are looking for:
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
// Check if that button is the one you want
// Look for some unique attribute, class name, etc.
if (button.className == 'btnUniqueClassName') {
// The button was found
button.disabled = true;
}
}

Related

How to add JavaScript event handler to dynamically generated TextBoxes on ASP control

We have conditions that will dynamically add TextBoxes to an ASP User Control like this:
if (conditionIsTrue) {
TextBox textField = new TextBox();
Panel.controls.Add(textField);
}
I would like to add an event listener that left-pads the TextBox value when the user unfocuses or is done editing the TextBox.
I have tried the following C# implementation but for some reason the values are not being handled by the listener.
if (conditionIsTrue) {
TextBox textField = new TextBox();
textField.TextChanged += new EventHandler(LeadingZero_Handler);
Panel.controls.Add(textField)
}
public void LeadingZero_Handler(object sender, EventArgs e)
{
int FieldLength = 10;
if((TextBox)sender.Text.Length < FieldLength)
{
(TextBox)sender.Text = (TextBox).sender.Text.PadLeft(FieldLength,'0');
}
}
Is there is a way that I could implement the event listener in JavaScript on the ASP Control, but add the JavaScript listener attribute during/when the TextBox is being dynamically generated in the C# code?
Add this to the code behind.
textField.AutoPostBack = true;
But if all you do is add some zero padding, and you are doing nothing else in LeadingZero_Handler, I would recommend a front-end approach. That saves you a PostBack.
<script type="text/javascript">
function LeadingZero(element) {
var str = element.value;
var padding = "0000000000";
if (str.length < 10) {
element.value = padding.substring(0, padding.length - str.length) + str;
}
}
</script>
And then add the script to the TextBox instead of the AutoPostBack and the TextChanged handler.
textField.Attributes.Add("onblur", "LeadingZero(this)");

why does textbox.disabled= true clears the text of the textbox?

I have a few asp:Textbox elements in my code, which I was disabling with javascript after the user clicks validate.
eg:
<asp:TextBox CssClass="dateClass" ID="fromDateE" width="100px" runat="server" Text=""></asp:TextBox>
My javascript function was :
function disableDateFields()
{
var dates = document.getElementsByClassName("dateClass");
for (var i = 0; i < dates.length; i++)
{
//console.log(dates[i]);
dates[i].disabled = true;
}
}
The problem I had was after submit the value I had inside the textbox was getting cleared.
To get around this problem I changed the JS function so instead of disabling I set the readOnly property of the text box to true :
function disableDateFields()
{
var dates = document.getElementsByClassName("dateClass");
for (var i = 0; i < dates.length; i++)
{
//console.log(dates[i]);
dates[i].readOnly= true;
}
}
I am just wondering why disabling the textbox clears out the value inside of it? Is this simply the default behavior or am I missing something?
In this case ViewState has nothing to do with this. The problem lies in the fact that disabled input controls are not part of the Form Post back to the server. But because the TextBox does still exists on the page asp.net will fill it with the values it receives from PostBack, but that one is null so the TextBox is made empty.
You can check this with the following snippet. You will see that fromDateE.UniqueID does not exists and thus fromDateE will be emptied.
if (Request.Form[fromDateE.UniqueID] == null)
{
fromDateE.Text = "Form Post was empty.";
}

JavaScript Not Working properly in ASP.NET

I am pretty new to JavaScript and got stuck at one point:
I am using asp control fileupload to upload some files and store them to database, i am using asp repeater control to show all the docs in database in front end and have associated a html checkbox to every doc:
The problem is when i check or uncheck the checkbox, the delete button enables/disables accordingly, but when i click the "Select All" button where i am calling both functions - to check all checkboxes and to enable button, somehow the delete button is not getting enabled..Please help.
Here is JavaScript Code to enable delete button:-
function EnableButton() {
var rpt = document.getElementById('<%= rptWordDoc.ClientID %>');
var chkbx = document.getElementsByTagName('input');
var x = document.getElementById("btnDelWordDoc");
for (i = 0; i <= chkbx.length; i++) {
var id = "rptWordDoc_chkWordDoc_" + i
var y = document.getElementById(id);
if (y == null) {
break;
}
if (y.checked == true) {
x.disabled = false;
break;
}
else {
x.disabled = true;
}
}
}
This is how i am calling the function:-
<asp:Button ID="btnSelectAll" runat="server" Text="Select All" OnClientClick="fnSelectAll(); JavaScript:EnableButton();" />
Through Checkbox:-
<input type="checkbox" id="chkWordDoc" runat="server" onclick="JavaScript:EnableButton();" />
You called two functions fnSelectAll(); and JavaScript:EnableButton(); may be second is not executed after executing the first one.
Finally found the cause:
Actually i was using asp: button control for Select All & Clear All features and thus it was posting back to the server and setting back the value of delete button enabled attribute to false.
I added a html control instead of asp button for Select All & clear all buttons and didn't added runat=server attribute since no server side event was required.
Thanks for your suggestions..
Cheers..:)

Enabling disabled CheckBoxList in javascript - checked items not recognized after postback

I have a CheckBoxList which can load as disabled, but might need to become enabled after some client side actions.
I am able to enable the checkboxes using jQuery, but the problem is that after submitting the page, the selected items in the ChceckBoxList are not recognized (probably because the control is not in the ViewState).
A simple example for the scenario:
<asp:CheckBoxList ID="chkList1" runat="server" Enabled="false" ClientIDMode="Static">
<asp:ListItem Value="123" />
<asp:ListItem Value="456" />
<asp:ListItem Value="789" />
</asp:CheckBoxList>
$(document).ready(function()
{
$("#divEnable").click(function()
{
var inputs = $("#chkList1").find("input");
for (var i = 0; i < inputs.length; i++)
{
inputs[i].disabled = false;
}
});
}
And then after enabling the checkboxes, selecting them and sending a postback - no selected items are recognized.
I tried disabling the items "manually", as in
chkList1.Items[0].Attributes.Add("disabled", "disabled");
But that did not work (the disabled attribute was attached to the containing span instead of the input control).
I also considered using hidden fields to keep track of the checkbox selections, but since I have multiple CheckBoxLists in a grid, that would be very inelegant.
Is there any way around this?
try this:
$(document).ready(function()
{
$("#divEnable").click(function()
{
var inputs = $("#chkList1").find("input")
.each(function(){
//if($(this).is(":disabled"))
//{
$(this).prop("disabled",true);
//}
});
});
Ref:
jQuery asp control .prop(“disabled”, “”) not enabling check box in IE 9
Unable to handle disable check box
You can use this
for (i = 0; i < document.forms[0].length; i++)
{
e = document.forms[0].elements[i];
if (e.id.indexOf("chklist") != -1)
{
e.disabled = false;
}
}
I had the same issue. The way I fixed this was to enable the checkboxlist to start, then on load of the page, disable using script. That way the controls got into the viewstate, but were still disabled to start.
var checkBoxListToChange = document.getElementById('');
var checkboxes = checkBoxListToChange.getElementsByTagName("input");
for (var x = 0; x < checkboxes.length; x++) {
checkboxes[x].disabled = true;
}

Limit the number of children in a form using Javascript

I am trying to limit the number of additional form input fields that a user can add dynamically to a file upload form to just 3. The form is loaded with one static input field and through javascript can add additional fields with an add button or remove additional form input fields with a remove button. Below is the html in it's static form.
<fieldset>
<legend>Upload your images</legend>
<ol id="add_images">
<li>
<input type="file" class="input" name="files[]" />
</li>
</ol>
<input type="button" name="addFile" id="addFile" value="Add Another Image" onclick="window.addFile(this);"/>
</fieldset>
With javascript I would like to create a function where the number of child elements are counted and if the number is equal to three then the "Add Another Image" button becomes disabled. In addition, if there are three elements in the form the user - with the remove button - removes a child then the "Add Another Image" button becomes enabled again.
I think I'm may be missing some crucial lines of code. The below javascript code only allows me to add one additional input field before the Add Another Image button becomes disabled. Removing this field with the remove file button removes the field but the Add Another Image button is still disabled. Below is where I'm currently at with the javascript.
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
}
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = nodelist.length;
for(i = 0; i < count; i++) {
if (nodelist[i] ==3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
}
}
Oh, OK, I've tested out the code now and see a couple of problems:
You're counting the number of child elements but this includes the text elements so there's actually one for the <li> and one for the text within it.
You've enclosed the true/false setting for the disabled property in quotes but it doesn't work and always set's it to false.
The remove button doesn't re-enable the add button.
I found this to work:
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
toggleButton();
}
toggleButton();
}
function toggleButton() {
var form = document.getElementById('add_images');
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = 0;
for(i = 0; i < nodelist.length; i++) {
if(nodelist[i].nodeType == 1) {
count++;
}
}
if (count >= 3) {
document.getElementById("addFile").disabled = true;
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = false;
}
}
I would suggest a slightly different approach. Create all three file input fields statically and provide a clear button. If the user chooses to leave it empty they can. If that is not elegant use your "Remove" to simply hide the field (CSS style display: none;).
I'm not sure why you're using the for loop? Shouldn't it be like this:
var nodelist = form.childNodes;
if (nodelist.length >= 3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
The last part of that function is a bit strange. Technically, when adding fields, you should only be disabling the button (i.e. you could never enable the button by adding fields). I would suggest removing the for loop and going with:
var count = form.getElementsByTagName("li").length;
if(count == 3)
document.getElementById("addFile").disabled = true;
The reason the add field button is still disabled when you remove an item is because you don't re-enable the add field button when you click remove. Try this for the remove button click handler:
rb.onclick = function () {
form.removeChild(this.parentNode);
document.getElementById("addFile").disabled = false;
}

Categories