getElementById doesn't find element after setting visibility to hidden - javascript

I'm working on an asp.net page, and I have a master page that uses a content page (my web control). In my web control, I have 4 elements. When I change the picklisttype drop down
PickListType - dropdown
UserPickList -not important
Organization - label
Body - label
Address -drop down
When I change the picklisttype dropdwon, I want to hide Body and Address, and vice versa.
When I change it hte first time, it works, but the second time, it says that it cannot find the ids of Body and Address (I set their visibility to hidden) the 2nd time. When looking through the source, it seems that these elements have 1) changed their Ids during the postback and .ClientId can't find them or 2) they just disappear.
I can't seem to figure out how to do this. Any ideas?
function DropDownChange() {
var picklist = document.getElementById("PickListTypeList");
var usercontainer = document.getElementById("ctl00_ctl00_ctl00_PageContentPlaceHolder_PageContentPlaceHolder_paneDetails_ApplicerPickListContainer");
var orgcontainer = document.getElementById("ctl00_ctl00_ctl00_PageContentPlaceHolder__C_OrganizationPickListContainer");
var addresslabel = document.getElementById("LegalBodyAddressLabel");
var addressbox = document.getElementById("ctl00_ctl00_ctl00_PageContentPlaceHolder_PageContentPlaceHolder_paneDetails_ApplicantsRadDock_C_ApplicantsControl_AddEditApplicantDock_C_AddApplicantDock_C_LegalBodyAddressComboBox");
if(picklist.value.toLowerCase() === "sometext"){
usercontainer.style.display = "none";
orgcontainer.style.display = "inline";
addresslabel.visibility = "visible";
addressbox.style.display = "inline";
}
else{
usercontainer.style.display = "inline";
orgcontainer.style.display = "none";
addresslabel.visibility = "hidden";
addressbox.style.visiblity = "none";
}
}
This is the source: i use .ClientId to dynamically find the ids, but then I changed it to static (same id's every single time) and I still cannot seem to get address and label. I am finding these elements from the parent (master) page by going into the control (controlname.nameofelementID.ClientID).

2 ideas/options
Add a class to the controls you want to access, and then use document.getElementsByClassName to retrieve them. .NET will not change classes on html tags after a postback.
OR
Wrap them in a div/span that has an id, and then document.getElementById that wrapping tag and then access its firstChild. I would recommend not doing runat="server" for this wrapper

You've 2 ways to make it work:
Use class names (.net framework does not fiddle with this)
Generate the javascript ids (using ClientId) at runtime. Since there's a postback, this is the right thing to do. Something like: document.getElementById("<%=LegalBodyAddressLabel.ClientId%>");

Related

Calling a value + style.display function?

I'm struggling to get this working because I don't know the right formatting.
What I am attempting is to get a CSS modal to display depending on what a user selects as a value in a Javascript applet.
The idea is to return .style.display = "block";
function onClick(event){
<something>.style.display = "block";
}
Where contains a value that has being saved in the format of intersects[0].object.title
So if for example I have selected "manhattan"
alert(intersects[0].object.title)
I'll get the string "manhattan" displaying correctly. That works perfectly.
But I can't get manhattan.style.display = "block"; returned and WORKING inside the function? I tried :
function onClick(event){
intersects[0].object.title.style.display = "block";
}
Also tried
function onClick(event){
(intersects[0].object.title).style.display = "block";
}
Any help would be greatly appreciated
This may not be directly what you're looking for, but it may help anyways. To make it work in your case, just change the button press to be a check for the selected value.
Rather than adjusting the CSS directly, this route modifies the element's classList to remove or add a .hidden class that contains the correct CSS.
// Loop through all modal buttons
document.querySelectorAll('.modal-button').forEach(function(element) {
// Add a click event listener to all modal buttons
element.addEventListener('click', function() {
// Toggle the target modal on click
toggleModal(element.dataset.target);
});
});
// Create the function to toggle the modals
function toggleModal(target) {
// Find the target
let targetElement = document.querySelector(target);
// Check if the target is hidden
if (targetElement.classList.contains('hidden')) {
// If it is, show it
targetElement.classList.remove('hidden');
} else {
// If it isn't, hide it
targetElement.classList.add('hidden');
}
}
.hidden {
display: none;
}
<button data-target="#modal" class="modal-button">Toggle Modal</button>
<div id="modal" class="hidden">Hey there, I'm a modal!</div>
I'm not certain from your question how the pieces of your puzzle are related to one another, and it would be helpful if you could clarify by showing more of your HTML and Javascript code, but I'll toss a couple of ideas at you in the meantime. Apologies if I'm telling you stuff you already know.
The only sort of object you would usually be able to set "style.display" on is an HTML element. To tell Javascript which HTML element you want to modify, you usually use a CSS selector like "document.getElementById('myDiv')"
It sounds like "manhattan" might be a piece of information you could use to uniquely identify the HTML element you intend to show. If so, there are four simple parts to showing the correct element:
associate the element with that particular string (eg via an id)
get the string at runtime (the same way as you did for the alert)
select the element based on the matching string
display the selected element
All together, it might look like this:
<div id="manhattan"></div>
<script>
var identifier = intersects[0].object.title;
alert(identifier) //I'm assuming this alerts "manhattan"
var elementToShow = document.getElementById(identifier);
elementToShow.style.display = "block";
</script>
Is this on the right track? If not, just provide more detail, and I'll see what else I can suggest.
Give to you div some id and then just change that:
<div id="test"></div>
document.getElementById("test").style["display"] = "block";
or
document.getElementById("test").style.display = "block";
or
document.getElementById("test").style.setProperty('display', 'block');
or
document.getElementById("test").setAttribute('display', 'block');

Add JavaScript onClick to dynamically generated asp button

Background My page creates a list of objects based on rows of an SQL Database. For each object, a DIV is dynamically generated that contains a few items including a LinkButton and a further child DIV that is initially hidden. I want the link button to toggle the child DIV's hidden property. The JavaScript is not dynamically generated and is included in the ASPX page.
Problem I don't know how to make this generated LinkButton fire JavaScript that is included in the ASPX page and pass in the correct DIV's ID.
I'm guessing I need to add an attribute to the button like so:
myButton.Attributes.Add(reference to JS function + parameter of DIV's ID)
Maybe like:
myButton.Attributes.Add("onclick", "Show_Hide_Display('"<%="' +idString+ '".ClientID%>"')");
Where the button is given an attribute of a JS onClick handler pointing to the function "Show_Hide_Display" and a parameter of a DIV's ID that is calculated as the rendered ID. This syntax is incorrect though.
How do I write this so it calls 'Show_Hide_Display' and passes the ID of the current child DIV? All of the DIVs have the same ID apart from a number that references their row number, for example '"myDiv_" + counter.ToString'
The JavaScript I am trying to add a call to on the button:
function Show_Hide_Display(divID) {
var div = document.getElementById(divID);
var style = document.defaultView.getComputedStyle(div);
var display = style.getPropertyValue('display');
if (display == '' || display == 'block') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
}
Use the following syntax ...
myButton.Attributes.Add("onclick", "Show_Hide_Display(this.id);");
the above syntax allows to call the function with id as its parameter.
suggestion:
Try to write a common function which does not depend on generated ids of controls.
If this is not useful for your requirement, please post your code which might gives me a better idea.
If you are using jQuery, you could you jQuery delegate method.
$(document).on("click", "div.parent", function(){
var subDivId = getSubDivByParent(this);
Show_Hide_Display(subDivId);
};
You need to implement getSubDivByParent according your DOM structure.
If you are not using jQuery, you need to attach event yourself. For each dynamically generated element. You need to manually add following script in your server code to register event.
... your html code ...
<script>
var elem = document.getElementById('new-created-element');
elem.addEventListener("click", function(){
var subDivId = getSubDivByParent(this);
Show_Hide_Display(subDivId);
};)
</script>
My suggestion is use jquery to achieve the functionality.
My solution works if you want to toggle the immediate div for the link.just call onclientclick method to toggle the div.
in linkbutton onclientclick="Show_Hide_Display(this)"
function Show_Hide_Display(id) {
$(id).next('div').toggle();
}
I hope this helps you .. Thanks

Read more opens 1st one all the time

I've a page with about 10 short articles.
Each of them as a "Read More" button which when pressed displays hidden text
The issues I have at the moment is when I press the "Read More" on any of the 10 button it shows the 1st articles hidden content and not the selected one.
I think I need to set a unique ID to each article.. and the read more button be linked to it.. But I don't know how to set it.
I looked at this but couldn't get it working how to give a div tag a unique id using javascript
var WidgetContentHideDisplay = {
init:function() {
if ($('#content-display-hide').size() == 0) return;
$('.triggerable').click(function(e){
var element_id = $(this).attr('rel');
var element = $('#'+element_id);
element.toggle();
if (element.is(':visible')) {
$('.readmore').hide();
} else {
$('.readmore').show();
}
return false;
});
}
}
var div = documentElemnt("div");
div.id = "div_" + new Date().gettime().toString;
$(document).ready(function(){ WidgetContentHideDisplay.init(); });
OP Edit: Sorry, the original code wasn't in caps. I kept getting errors when trying to post, so I copied the code into Dreamweaver and it made it all caps for some reason.
Instead of selecting the element to toggle with an ID (i.e. $('#'+ELEMENT_ID)) you could setup a class for your item and use the class selection (e.g. $('.DETAILED-ARTICLE)') to select the child (or the brother, etc. depending how you built the HTML page).
In theory each ID should point to a single element but each class can be put to as many elements as you want.
If you're getting errors, read the errors and see what they are. Off of a quick read of your code, here are a couple things I noticed that will probably cause issues:
"documentElemnt" is misspelled, which will render it useless. Also, documentElement is a read-only property, not a function like you're using it.
toString is a function, not a property, without the parentheses (.toString()) it isn't going to function like you want it to.
Run the code, look at the errors in the console, and fix them. That's where you start.

Tracking changes in web application

I have an application in which the user needs to see the changes that have been made during the latest edit.
By changes I mean, the changes made in all inputs like a textarea, dropdowns.
I am trying to implement this by showing a background image on the right top and then when the user clicks this background image, a popup is shown which shows the difference.
I am using prototype 1.7.0.
My First question would be:-
1. What would be the best approach to implement this functionality?
2. Can I put a onClick on the background image?
There some functions in the jQuery library that I believe would be helpful to you. If you are using prototype, I would guess that there is some similar functionality you may utilize.
I would suggest writing some code like this:
var $input = $('input').add('textarea').add('select');
$input.each(function() {
var id = $(this).attr('id');
var value = $(this).val();
var hiddenId = 'hidden' + id;
var newHiddenInput = $("<input type='hidden'").val(value).attr('id',hiddenId);
$(this).after(newHiddenInput);
});
The above code will create a new hidden input for each input, textarea, and select on your page. It will have the same value as the input it duplicates. It will have an id equivalent to prepending the id with the word 'hidden'.
I don't know if you can attach a click handler to a background image. If your inputs are enclosed inside a <div>, you may be able to get the result you want by attaching the click handler to your div.
In any case, you should now have the old values where you can easily compare them to the user's input so that you can prepare a summary of the difference.
Prototype gives us the Hash class which is almost perfect for this but lacks a way of calculating the difference with another hash, so let's add that...
Hash.prototype.difference = function(hash)
{
var result = this.clone();
hash.each(function(pair) {
if (result.get(pair.key) === undefined)
// exists in hash but not in this
result.set(pair.key, pair.value);
else if (result.get(pair.key) == pair.value)
// no difference so remove from result
result.unset(pair.key);
// else exists in this but not in hash
});
return result;
};
This is no way to tell if an element was clicked on just it's background image - you can find out the coordinates where it was clicked but that is not foolproof, especially since CSS3 adds complications like multiple backgrounds and transitions. It is better to have an absolutely positioned element to act as a button.
$('button-element').observe('click', function() {
var form_values = $H($('form-id').serialize(true));
if (old_values) {
var differences = old_values.difference(form_values);
if (differences.size()) {
showDiffPopup(differences);
}
}
window.old_values = form_values;
});
// preset current values in advance
window.old_values = $H($('form-id').serialize(true));
All that remains is to implement showDiffPopup to show the calculated differences.

Unable to get a Hidden element in ASP.NET 4 from Javascript

I need help to find a hidden button in Javascript. I am using ASP.NET 4.
I can find a "visible = True" but when i try to find a hidden element it says object not found
<script type="text/javascript">
function ShowAge()
{
var elem = document.getElementById('MainContent_chbFilter');
if (elem != null)
alert("Found 1");
else
alert("Not Found 1");
var elemc = document.getElementById('MainContent_txtMSISDN');
if (elemc != null)
alert("Found 4");
else
alert("Not Found 4");
}
</script>
I am using asp:content
Please help
In ASP.NET when you hide an element it is not rendered in the HTML at all. This is in contrast to using the hidden property in CSS, where the element is still there, just visually hidden. If you want to "hide" it server-side, but still make it available in the DOM, you should add style="display:none;" in your ASPX.
If an element has been hidden serverside (I'm assuming this is what you've done), this means that it won't get rendered onto the page, which is why Javascript won't find it in the DOM.
What you want is to assign it a CSS class (.hidden, for example) with display:none. You can then revert it back to display:block through Javascript.
If you're setting Visible=False to an element in the server-side code than it won't render to the page, so the JavaScript won't be able to access it.

Categories