Javascript not making div show - javascript

I'm having trouble making a div show up using javascript.
<div class=" notification success">
x
<p>An email has been sent confirming your identity.</p></div>
<script type="text/javascript">
var notification = '.notification';
$(notification).show();
</script>
</div>
Any ideas?

Place your jquery js in a document.ready() otherwise you cant ensure that the DOM is fully loaded and ready.
Your need is just a one liner like so
$(document).ready(function()
{
$('.notification').show();
});

You need to have double or single quotes surrounding the selector if you're naming a specific element ("#id", ".class").
Best way to do this is to avoid using the variable. It's just three extra characters anyways.
Also, put your code into a $(document).ready(function(){}); function like this:
$(document).ready(funciton(){
$(".notification").show();
});
To minimize the amount of code you're putting in, you can just use this instead:
$(function(){
$(".notification").show();
});
$(function(){}); can replace $(document).ready(), as by default jQuery selects the document.

Related

Append a load() output to the same div in jQuery

A button calls a JS function that loads a different PHP page asynchronously using jQuery load, and it will put the result in a errorReturn div.
<div id='errorReturn'></div>
<button onclick='trySomething()'>Click me</button>
<script>
function trySomething() {
var url = 'otherpage.php'
$('#errorReturn').load(url)
}
</script>
All is fine.
Since I want the user to see ALL the errors if the button is clicked multiple times, I wanted to APPEND that result to the same div.
I tried both
$('#errorReturn').append.load(url)
$('#errorReturn').append(load(url))
And they didn't work. Then I found the solution:
$('#errorReturn').append($('#errorReturn').load(url))
It works. Kind of :( It fills the errorReturn div, but it doesn't append to it. It simply overwrites it, as if I simply wrote
$('#errorReturn').load(url)
I should probably just take a break, but I cannot see what's wrong :(
EDIT: Since somebody flagged this as "answered in another question", the other question was using JS while I was explicitly asking for jQuery - plus the other answer generated a lot of fuss about adding HTML with possible XSS injection and I think the accepted answer here is way nicer and simpler to understand
load() always overwrites the content of the target element. To do what you require you could make the AJAX request and append the content manually. Try this:
<div id="errorReturn"></div>
<button id="add-content">Click me</button>
jQuery($ => {
$('#add-content').on('click', e => {
$.ajax({
url: 'otherpage.php',
success: html => $('#errorReturn').append(html)
});
});
});
Make a new <div>, .load() content into it, and .append() that.
$("#errorReturn").append($("<div/>").load(url));
You can of course also add styles etc. to the <div>, like for example a top margin to separate the individual errors.

Find control where javascript is running

I have a user control named uscUserControl.ascx and a page named test.aspx.
I have used user control twice on my page. My user control looks like.
<div id="div1">
</div>
<script>
$(document).ready() (function() {$('[id$=div1]').html('Control called');} );
</script>
But it only modifies first div and second is empty. So how to make script modify the element nearest to it?
We can solve it using combination of ClientID and partial Id as below
$(document).ready() (function() {$('[id*=<%= ClientID %>][id$=div1]').html('Control called');} );

interchange html content using javascript

Good day! Newbie here. I just want to know if it's possible to change the whole content of an html using javascript? I got some codes here. (not mine but whoever did this, thank you so much!) I don't know where to put/insert all the codes of the new layout like when you click a button then the whole content will change. Thank you very much for helping me.
<script language="Javascript">
<!--
var newContent='<html><head><script language="Javascript">function Hi()</script></head><body onload="Hi();"><p id="p">hello</p></body></html>';
function ReplaceContent(NC) {
document.write(NC);
document.close();
}
function Hi() {
ReplaceContent(newContent);
}
-->
</script>
The easiest way to do this is with jQuery.
function insertHtml()
{
var newHtml = '<div><span>Hello World</span></div>';
$('body').html(newHtml);
}
Something like that will replace the entire contents of body with newHtml. You can also do this with pure javascript using the .innerHtml property but jQuery has many advantages.
EDIT: If you want to add something to the DOM rather than replacing the entire thing, use
$('body').append(newHtml)
instead. This will add the content to the end of the body. This is very often used for things like adding rows to a table.
Yes it is possible but this code is not valid unless you remove the comment tags however don't use the document.write() after page load unless you want to overwrite everything in page including the script

Getting started with jQuery -- hiding an element

Have you noticed that every 10 questions on this site is about jQuery?
Anyway...
I'm using jQuery for the first time. I don't know if I loaded it correctly. When I run this code:
<script type="text/javascript">
function allDayClicked() {
if (jQuery) alert("loaded");
var allday = document.getElementById("allDayEvent");
var start = document.getElementById("<%=startTimeSelector.ClientID%>");
$('allDayEvent').hide();
}
</script>
The alert appears, saying "loaded", but nothing else happens; the html checkbox doesn't go invisible. I get no kind of error in my javascript output.
Is it possible I haven't successfully loaded jQuery? I added a reference to it in my visual studio project and generated this by dragging it to default.aspx:
<script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
Otherwise, what's going on?
jQuery takes a css selector, not an id. If you want an id use the css form of declaring an id.
$('#allDayEvent').hide();
jQuery is loaded fine, you're just using it incorrectly. You should be doing either:
$('#allDayEvent') // recommended, the '#' means ID
Or:
$(allday) // since you already grabbed it with getElementById
jQuery can take a lot of different objects with $(). The options are listed here.
You are missing the # in your ID selector.
Change $('allDayEvent').hide();
to
$('#allDayEvent').hide();
Assuming that your checkbox has an id "allDayEvent", you just need the hash (#) in this line:
$('#allDayEvent').hide();

Javascript Replace() and innerHTML

I have this code: [it is a rough example with poor coding, but it illustrates what I want to do.]
<html>
<body>
<script type="text/javascript">
function fun()
{
var divs = document.getElementById('hi');
divs.innerHTML = divs.innerHTML.replace("cake","jump");
alert(divs.innerHTML);
}
</script>
<div id="hi">
<span onclick="fun('cake');">Mer<span onclick="fun('cake');">Mer</span></span>
</div>
<a onclick='fun()';)>Click</a>
</body>
</html>
When I click on the <a> i want to change the onclick parameter within fun() from 'cake' to 'jump'. I do not want to use the setAttribute() method as my real example has several nested tags and I want to replace 'cake' in several different places.
I want the innerHTML.replace() function to work to do this but, alas it doesn't function as I want it to. How do I replace text within innerHTML?
Forget it. Never hack around with the innerHTML, there's no guarantee it will be in any particular format, you're very likely to mess up the markup by replacing the wrong thing, and even if it works, you're serialising the document content into a string, hacking it and then recreating the entire content from the string again, instead of just replacing a particular thing you're interested in. This is slow and loses all non-serialisable data (like form field values, JS references and assigned event handlers).
In general DOM methods are much more reliable for altering page content. It's what they were designed for. Use them, and use the DOM Level 1 HTML properties in preference to setAttribute which is badly broken in IE. This goes double for event handler attributes. Trying to hack at JavaScript code inside an attribute value inside an HTML string is insanity, even if it worked.
There is no need whatsoever to replace any page content. You could implement your example much more easily with a simple variable:
<div id="hi">
<span>Mer<span>Mer</span></span>
</div>
<a id="foo">Click</a>
<script type="text/javascript">
var potato= 'cake';
document.getElementById('foo').onclick= function() {
potato= 'jump';
return false;
};
var spans= document.getElementById('hi').getElementsByTagName('span');
for (var i= spans.length; i-->0;) {
spans[i].onclick= function() {
alert(potato); // do whatever with the variable
};
}
</script>
First, you have an error in your HTML:
<a onclick='fun()';)>Click</a>
What's with the ;) outside the attribute value?
Next...
[...] method as my real example has several nested tags and I want to replace 'cake' in several different places.
This means you really, really don't want to use innerHTML and replace(). It will screw up. Use an HTML parser of sorts; walk the DOM recursively... anything other than replace.
Within the scope of your specific example, I suggest using a variable to hold the value of cake and jump instead.
Change your replace call to use the RegEx "global" flag:
divs.innerHTML = divs.innerHTML.replace(/cake/g,"jump");
That said, if you're using this for more than a quick test, you should use DOM objects to accomplish what you would like to do. Otherwise, this will get ugly really fast.
Also, it wouldn't hurt to change your <a> tag code:
<a onclick='fun(); return false;')>Click</a>
(The return false; is optional, but good practice.)
The easiest way to change the onclick parameter is to make it a variable instead of a string literal. Here I'm using a variable called food:
<script type="text/javascript">
var food = "cake";
function change()
{
food = "jump";
}
</script>
<div id="hi">
<span onclick="alert(food);">Mer<span onclick="alert(food);">Mer</span></span>
</div>
<a onclick='change()'>Click</a>

Categories

Resources