Creating a form page with java - javascript

Noob here again. I have a div id setup and the following code works for the one instance, but I need to have when they click static 3 forms areas aren't hidden any more. I know its a for loop, but I can't get they syntax right.
<script type="text/javascript">
function Protocols(val){
var element=document.getElementById('static_ip')
if(val=='pick a protocol'||val !='Static')
element.style.display='none';
else
element.style.display='block';
}
</script>

Here's an example, using querySelectorAll:
function Protocols(val){
const hideOrShow = document.querySelectorAll('#static_ip, #id2, #id3')
for (element of hideOrShow) {
if (val !== 'Static') {
element.style.display = 'none';
} else {
// resetting to empty string falls back to default value
element.style.display = '';
}
}
}
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

Got it, Its working now. Thanks for the help.
<script type="text/javascript">
function Protocols(val){
var element=document.querySelectorAll('#static_ip')
for ( i=0; i < element.length; i++) {
if(val=='pick a protocol'||val !='Static'){
element[i].style.display='none';
} else {
element[i].style.display='block';
}
}
}
</script>

Related

How to find if parent Node has no Children

I'm not sure if I am using the correct syntax, as my ELSEIF doesn't appear to be firing. Is this the correct syntax, or what is the best way to test it?
<script>
function OnLoad() {
var links = document.getElementById("<%=TreeView1.ClientID %>").getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].setAttribute("href", "javascript:NodeClick(\"" + links[i].id + "\", \"" + links[i].getAttribute("href") + "\")");
}
}
window.onload = OnLoad;
function NodeClick(id, attribute) {
var nodeLink = document.getElementById(id);
if (nodeLink.hasChildNodes)
{
eval(attribute);
}
else if (nodeLink.hasChildNodes == false)
{
alert(nodeLink.innerHTML + " clicked");
window.open("../NewFolder/addNewProduct.aspx");
}
else
{
return;
}
}
</script>
If I move the alert/open window by itself it works, so I feel that the problem lies in this line:
else if (nodeLink.hasChildNodes == false)
The syntax for hasChildNodes says it is a method .i reckon changing it to a method should solve the problem
It should be noted, hasChiildNodes() considers whitespace and comments. From the MDN docs
childNodes also includes e.g. text nodes and comments. To skip them, use ParentNode.children instead.
i.e
if (nodeLink.hasChildNodes())
{
eval(attribute);
}
else if (!nodeLink.hasChildNodes())
{
alert(nodeLink.innerHTML + " clicked");
window.open("../NewFolder/addNewProduct.aspx");
}
else
{
return;
}
Check the two fiddles to get the difference
hasChildNodes fiddle .
ParentNode.Children fiddle
parentNode.children.length;
if it is 0, then no child node at all
For example
console.log(document.getElementById('d1').children.length); //->0
console.log(document.getElementById('d2').children.length); //->3
<div id="d1"></div>
<div id="d2">
<div></div>
<div></div>
<div></div>
</div>

creating simple JS with PHP

I am trying to recreate the JS below with PHP. The reason is that the numbered classes and values are actually IDs pulled from a mysql database. I have an area where say a report is creating, the code below shows and hides rules for that report. Since different reports have different rules, it shows and hides rules dependent on the grouping, determined in the code below as #rule_who.
When trying to recreate the following I was trying to use while loops however it got pretty ridiculous. Is there a more efficient way in JavaScript or AJAX to show and hide divs that would be better suited to using a large number of divs? The 2,3,4, and so on shouldn't be an incrementing number as it would rely on IDs and thus some numbers will disappear over time as reports are deleted.
Any help would be appreciated. Thanks
<script>
//<![CDATA[
$(window).load(function(){
$(".2").hide();
$(".3").hide();
$(".4").hide();
$('#rule_who').on('change', function () {
if(this.value === "2"){
$(".2").show();
$(".3").hide();
$(".4").hide();
} else if(this.value === "3"){
$(".2").hide();
$(".3").show();
$(".4").hide();
} else if(this.value === "4"){
$(".2").hide();
$(".3").hide();
$(".4").show();
} else {
$(".2").hide();
$(".3").hide();
$(".4").hide();
}
});
});//]]>
</script>
EDIT: Thanks everyone for the help.
What I ended up using was the following:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$("#rule_who").change(function() {
$("div.specific_rules").hide();
var targetId = $(this).val();
console.log($(targetId).html());
// show the new selected one
$("#"+targetId).show();
});
});//]]>
</script>
I think you can do:
$('.' + this.value).show();
$('.' + this.value).siblings().hide();
Try this (FIDDLE EXAMPLE HERE):
$('.1, .2, .3').hide();
$(window).load(function(){
$('#rule_who').on('change', function () {
var elems = document.getElementsByTagName('div');
for (var i = 0; i < elems.length; i++) {
if (elems[i].className != this.value) {
elems[i].style.display = 'none';
} else {
elems[i].style.display = 'block';
}
}
});
});

How to hide then restore to initial state (= not always "block")?

Here's the JavaScript code you can find everywhere when you want to hide/show an element:
function sh(_id, _val) {
if (document.getElementById) {
document.getElementById(_id).style.display = _val;
}
else {
if (document.layers) {
document._id.display = _val;
}
else {
document.all._id.style.display = _val;
}
}
}
function hide(_id) {
sh(_id, 'none');
}
function show(_id) {
sh(_id, 'block');
}
The problem is the "show" function: it forces to "block". If I use a table with tr's and td's, when I want to display them I don't them to be displayed as "block" but to restore to their initial state.
How should I do?
How would you do?
If you want to restore their default display value, you can assign an empty string to it:
element.style.display = '';
If you want the one assigned through CSS for example, you have to store it somewhere, e.g. in an id -> display map or as data- attribute.
The easiest way would be to use jQuery and .show() http://api.jquery.com/show/
The second easiest way would be to wrap the table in a div.
If not I would try to store the initial value of display somewhere (if html5 the a "data-" attribute) if not in some other hidden element
If the point of your exercise is to learn more about DOM, then you may disregard this answer. But if the point is to get some UI to work, then:
My suggestion would be to use jquery. If you did, all of the code you showed would disappear altogether, and you would hide/show elements like this:
$('#' + id).hide()
$('#' + id).show()
If you want to stick with low level DOM api, then you'll have to save away the prior value (block or whatever) of style.display, so you can restore it later. And you can do that. But you'll keep having to write code like that, considering all kinds of cases, when someone has already written code that does that, and they're giving it away for free.
var previousDisplay = {};
function sh(_id, _val) {
if (document.getElementById) {
document.getElementById(_id).style.display = _val;
}
else {
if (document.layers) {
if(!previousDisplay[_id]){
previousDisplay[_id] = document._id.display;
}
document._id.display = _val;
}
else {
if(!previousDisplay[_id]){
previousDisplay[_id] = document.all._id.style.display;
}
document.all._id.style.display = _val;
}
}
}
function hide(_id) {
sh(_id, 'none');
}
function show(_id) {
var style = previousDisplay[_id];
if(!style){
style = 'block';
}
sh(_id, style );
}

Problems w/ window.location.hash

I have this content box on my site, that has different tabs on the side and when you click on one of the tabs, it uses JS to hide/show the according divs inside the content box.
I also have this in my head to give each div inside the content box it's own URL:
<script type="text/javascript">
function loadSmugInfo() {
if(window.location.hash == '#smuginfo')
document.getElementById('contentInfo').style.display = "block";
document.getElementById('contentSlideshow').style.display = "none"
}
</script>
<script type="text/javascript">
function loadFind() {
if(window.location.hash == '#find')
document.getElementById('contentMap').style.display = "block";
document.getElementById('contentSlideshow').style.display = "none"
}
</script>
<script type="text/javascript">
function loadSmugmug() {
if(window.location.hash == '#smugmug')
document.getElementById('contentSmugInfo').style.display = "block";
document.getElementById('contentSlideshow').style.display = "none"
}
</script>
<script type="text/javascript">
function loadMain() {
if(window.location.hash == '#')
document.getElementById('contentSlideshow').style.display = "block"
}
</script>
<script type="text/javascript">
function loadSlideshow() {
if(window.location.hash == '#slideshow')
document.getElementById('contentSlideshow').style.display = "block"
}
</script>
I also have it so when you a click a tab, it changes the hash.
Here is my problem.
When the page loads like normal (without a hash), the first and topmost div, is still not displaying (even though it's set to display: block in CSS).
I'm loading the functions you see above, using onLoad on an image above the content box.
Any help would be appreciated, I'm on a little bit of a tight schedule.
Let me know if you need any more information.
Thanks!
If you're doing what I understood you're doing, you'd have to use
if( (window.location.hash == '#') || (window.location.hash == '')
instead of
if(window.location.hash == '#')
since the hash is empty when the script is loading.
On a side note:
You only need one function for all of this:
function whatever()
{
if(window.location.hash == '#smuginfo')
{
case1
}
else if(window.location.hash == '#find')
{
case2
}
.
.
.
else
{
default for no hash
}
}
It would be shorter with a switch statement...
A couple of problems here.
First off, you dont show any way of calling these functions. You might want to start an interval timer to poll these functions and check them periodically. This will make sure they evaluate on page load, and each hash change.
You are also evaluating whether the hash == "#" which is the default, but will not show on initial page load. Maybe put an AND condiation to check if it == "" aswell.
Here is an example of some code i use for hash polling. Maybe it can help.
var start_hash = window.location.hash;
var recent_hash = '';
process_hash(start_hash); // Start the initial hash check
setInterval(poll_hash, 100); // Initialize our hash polling interval
function poll_hash() {
if (window.location.hash==recent_hash) { return; } // No change in URL hash
recent_hash = window.location.hash; // Set to check next time.
process_hash(recent_hash); // Changed hash, lets process
}
function process_hash(current_hash) {
// Check for defaults, then set to #home.
if(!current_hash || current_hash == '' || current_hash == '#')
{ current_hash='#home'; }
// Strip the # for the hash
var hash_id = current_hash.match(/[^#]+/g);
if(hash_id == 'home') { do something; }
}
Try this:
<script>
document.domain = 'facebook.com';
try {
try {
if (window.opener && window.opener.graphexplorer) {
window.opener.graphexplorer.authCallback(window.location.hash);
}
} catch(e) { }
} catch (e) { }
window.location.hash = '';
window.close();
</script>

How to remove a div in a site using a Chrome extension?

There's this div in a site:
<div class="section1">
....
</div>
I want to remove it using a Chrome extension... Can someone give only the javascript code alone? Thanks.
function removeElementsByClassName(names) {
var els = document.getElementsByClassName(names),
i, element;
for (i = els.count - 1; i > 0; i -= 1) {
element = els[i];
element.parentElement.removeChild(element);
}
}
removeElementsByClassName('section1');
function removeElement(parentDiv, childDiv){
if (childDiv == parentDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(childDiv)) {
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
removeElement('parent','child');
If by removing you simply mean hiding then you can run this from a content script:
document.querySelector('div.section1').style.display = 'none';
(this assumes there is only 1 section1 element on the page, otherwise you would need to use document.querySelectorAll and filter the results based on some criteria)

Categories

Resources