HTML THIS statement - javascript

<head>
<script>
function copyText(str1, str2){
document.getElementById(str2).innerHTML = document.getElementById(str1).innerHTML
}
</script>
</head>
<body id="main">
<H2 id="text1">Hello World</H2>
<H2 id="text2" >No change so far</H2>
<button onclick="copyText(document.main.text1.id, document.main.text2.id)">Change</button>
</body>
I want to able pass element ids as parameters to javascript functions. Is there a way to this?

The decent cross-browser way to get elements by ID is the document.getElementById() function you already know about. So rather than this:
document.main
... you should do this:
document.getElementById("main")
... etc. But of course you are doing something redundant: get an element by ID in order to obtain its ID. It's like making a phone call to ask the receiver for its phone number. All you need is:
copyText('text1', 'text2')
IDs as just strings.

Related

HTML input into Javascript

I want to create a website which can tell the circumference of a circle when the user inputs the radius. I've done the code, but its not working. Can you tell me why?
<html>
<head>
</head>
<body>
<form id="ty">
Give radius: <input type="number" input id="radius">
</form>
<p id="sum"> htht </p>
<button type="button" onclick="my()"> Click on me</button>
<script>
Function my() {
var r= document.getElementById("radius");
var a= r*2;
document.getElementById("sum").innerHTML=a;
}
</script>
</body>
</html>
I am getting an error "NaN" when I click on the button
Working HTML demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en">
<meta charset="UTF-8">
<title>Radius to Circumference</title>
</head>
<body>
<form name="ty">
<ol>
<li>Give radius: <input type="number" name="radius"></input></li>
<li><input type="button" onClick="my();" value="convert"></input></li>
<li>Get circumference: <input type="number" name="sum"></input></li>
</ol>
</form>
<script LANGUAGE="Javascript">
function my() {
var r = document.ty.radius.value*1;
var a = r*2;
document.ty.sum.value = a;
}
</script>
</body>
</html>
when writing HTML, you should be certain to use proper semantics.
Specify a doctype, character set and language!
avoid using buttons that say things like "Click on me!" This is
redundant because the user has to read what they're going to do
before they do it. Instead, write what the button will do
on the button itself (in this case, "Convert" is what I used).
you did not include a title in your head.
and are two different elements with different
purposes. In this case, you want .
"function" should not be capitalized.
your r variable did not contain the number the user put in, but
rather, contained all the properties of the input element. You never
specified you wanted the number it contained, so instead, the
variable r contained all the information it could obtain about the
"radius" element including it's colour, it's size, and other useless
things you don't need. You are looking for it's value, hence why I
added .value on the end of that line.
I also added *1 to the end of r's line, so that if the user by
any chance did not enter a valid number, Javascript will correct that
issue (multiplying by one gives the same result but parsed into a number).
you were using the p element for the sum, but that wouldn't be a
paragraph now, would it?
I used an ordered list to add 1, 2, and 3 to the beginning of each
step.
I think you mean:
var r = document.getElementById("radius").value;
getElementByID returns the element, not its value. element*2 = NaN.
You want.
var r = document.getElementById("radius").value;
Also, you might want to parse the integer just in case:
var r = parseInt(document.getElementById("radius").value);
Very simple, from HERE you can find you need to change:
var r= document.getElementById("radius");
to
var r= document.getElementById("radius").value;
You have written whith uppercase F the function, note that the
javascript is case sensitive.
the value of the input element can get using the .value property.
in the input form element does not need twice using the input
keyword, only once on begin.
Here is a nicer way to write that, with some minor improvements.
it's preferred to write the javascript in the head.
by defining the various elements onload later you have faster&easier access to them.
also inline javascript is not suggested, don't write js inside html attributes.
Then talking about your errors:
function is not Function
document.getElementById('radius') should be document.getElementById('radius').value
<html>
<head>
<script>
var radiusBox,sumBox,button;
function my(){
sumBox.innerHTML=radiusBox.value*2
// the use of textContent is more appropiate but works only on newer browsers
}
window.onload=function(){
radiusBox=document.getElementById('radius');
sumBox=document.getElementById('sum');
button=document.getElementById('button');
button.onclick=my
}
</script>
</head>
<body>
<form id="ty">
Give radius:<input type="number" id="radius">
</form>
<p id="sum">Enter a number</p>
<button id="button">Click on me</button>
</body>
</html>
writing it this way it is compatible with every browser that supports javascript, a newer proper way would be using addEventListener to add the load and the click handler thus also allowing you to add multiple event handlers, but old ie's wouldn'ty work.also textContent could have prblems...
DEMO
http://jsfiddle.net/frma0zup/
if you have any questions just ask.

How to find active tag formats using jQuery?

I have a situation with sample code as follows:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<p>
<h1>The header</h1>
<div>
matter ia always matter matter ia <strong>bold matter</strong> matter matter <em>italics matter</em>matter ia <em><strong>bold italics matter</strong></em>lways matter
</div>
</p>
</body>
</html>
I am just trying to retrieve the specific tags like body->p->div->em->strong when I click on "bold italics matter" using jQuery. Is there any standard method to retrieve as per the click event?
If you wan to get the tag name of the element which is clicked, then you can use:
$('*').click(function(e) {
e.stopPropagation();
console.log($(this).prop('tagName'));
});
Fiddle Demo
I'm not completely sure about what you are trying to accomplish. If you are trying to retrieve the tag itself that the text is contained in, i would recommend that you put a <span> tag in around the the text in question and do an onclick="function()" or simply put the onclick right on the <strong> tag.
As far the the JQuery/Javascript goes, if you want to retrieve the content, it looks like
var foo = document.getElementById.innerHTMl("id");
However, this requires you to have an id in your tags which is probably the best, if not
'standard' method of retrieving the content that is within the tag.
After reading your comments, i am editing this post:
The best way to get the parent elements is to use the JQUery .parent() function. I'd imagine that you would just recursively state something like this:
var foo = $("nameofelement").parent();
I hope this is more of what your looking for.
Thanks for contributing everybody. At last I made it myself with the following code.
$(document.body).click(function(e){
var Tags=[], Target=e.target, stat_msg="";
Tags.push(Target.tagName);
while($(Target).parent().get(0).tagName!=="BODY")
{
Tags.push($(Target).parent().get(0).tagName);
Target=$(Target).parent();
}
Tags.push("BODY");
for(i=Tags.length;i>0;i--)
stat_msg=stat_msg+Tags[i-1]+" ";
alert(stat_msg);
});

Cannot get the hidden tag value

Here is my code:
<html>
<head>
<script type="text/javascript">
var x= document.getElementById("2").value;
document.getElementById("1").innerHtml = x;
</script>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
</body>
</html>
in this code i have a hidden tag as you can see. I want that the javascript code read text value of the p tag with an id 2 and then print the same value to other <p> tag wiht id="1". But this is not working. Earlier i even tried to use nodeValue but also this is not working and when i checked out in google developer tool then it was showing an error as following:
Cannot read property 'value/nodeValue' of null
please note:
after a quick experiment i noted that after adding a event handler <body onload="y();>" there was no error but there was no expected result!
please help!
hidden is an input element type, not a p attribute:
<input type="hidden" id="2" value="This input should be hidden." />
There are three problems:
there is no innerHtml, innerHTML is the correct syntax.
the hidden "p" does not have a value, it is not an input field. use innerHTML for accessing it.
your javascript code runs before the browser knows about paragraps, so they don't exist when you want them to be accessed. put javascript after the paragraphs or run the code after the page is loaded.
this should work:
<html>
<head>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
<script type="text/javascript">
var x= document.getElementById("2").innerHTML;
document.getElementById("1").innerHTML = x;
</script>
</body>
</html>
Don't use numbers for ID.
Try something like <p id="hello"></p>
I think you need to change your tag to then you can set a CSS class with .hidden { display:none; }.
Wrap your Javascript in a function and call it when you need to or go back to your
Also as Maaz said, try not to use numbers in your ID's.
var hiddenValue = document.getElementById('2').innerHTML;
document.getElementById('1').innerHTML = hiddenValue;
The problem with this (and if you try and style it also) is that classes and ID's should not start with (or include) numbers.
Rename your ID's to one and two and then update your javascript accordingly.
e.g
<p id="one">Some stuff</p>
Also hidden cannot be used with a p element as it's for inputs only.
You're better off using display:none; in CSS.
If you NEED to access it via css as a number, you can use
[id='1']{
/*code*/
}
but your javascript still wont work.
As James has pointed out, using numbers for ID's is perfectly valid in HTML5.

Why is my named form not being returned?

In the following code, I get an error
cannot read property "Area Sorted" of undefined
when I call the line
document.SortingForm.AreaSorted.value = Names.join("\n");
I've been over the code a hundred of times and I don't see why this is happening. I would really appreciate any help with this.
sort.html
<!doctype html>
<html>
<title>Sort</title>
<head>
<script type="text/javascript" src="sort.js">
</script>
</head>
<body>
<h1>Sorting String Arrays</h1>
<p>Enter two or more names in the field below,
and the sorted list of names will appear in the
text area.</p>
<form name=”SortingForm”>
Name:
<input type="text" name="FieldWord" size="20" />
<input type="button" name="ButtonAddWord" value="Add" onClick="SortNames();" />
<br/>
<h2>Sorted Names</h2>
<textarea name=”AreaSorted” cols=”60” rows=”10” >
The sorted names will appear here.
</textarea>
</form>
</body>
</html>
sort.js
var Names = new Array();
function SortNames()
{
Name = document.getElementsByName("FieldWord")[0].value;
Names.push(Name);
Names.sort();
document.SortingForm.AreaSorted.value = Names.join("\n");
}
You have weird speechmarks around the name of the form: ”. I'm a little suprised that using these is not valid though.
Why don't you try adding an id to the textarea and use:
document.getElementById('AreaSorted');
That should always work, regardless of the form being there.
Also the quotes before and after the form's name seem to be off, try retyping them.
I don't know where that syntax originates from, but obviously it doesn't work (any more). To get references to forms by their name, you should use document.forms.
document.forms.SortingForm.elements.AreaSorted.value = names.join("\n");
But the recommended way would be to assign an id to the input, and use document.getElementById.
AreaSorted isn't an id .. so either use
document.getElementByName('AreaSorted')[0]
or
.. give your element an id and use document.getElementById, which I would recommend.

How to return Element ID instead of [object HTMLDivElement] (Prototype.js)

I know this is simple, but I can't wrap my head around it. Currently the following code returns "[object HTMLDivElement],[object HTMLDivElement]" I'd like it to return "div1,div2". Any thoughts? Thanks guys.
<HTML>
<HEAD>
<script type="text/javascript" src="path_to/prototype.js"></script>
<script>
function linkClick ()
{
alert($$('div.basic'));
}
</script>
</HEAD>
<BODY>
<div id="div1" class="basic" onclick="linkClick();"></div>
<div id="div2" class="basic" onclick="linkClick();"></div>
</BODY>
</HTML>
I had the same problem, there is a simple solution :
If varElement is your object containing a [HTMLDivElement] (or other DOM object) simply add '.id'
e.g.
varElement.id
There's an optimization in prototype specifically for this:
$$('div.basic').pluck('id')
If I read your question right, you want a list of div IDs, rather than a string of ids separated by a comma.
var ids = $$('div.basic').collect(function(el) { return el.id; }); //array of ids
alert(ids.join(','));
collect is another name for map, which is allows you to transform the elements one type of collection into another type by applying a "selector" function to each.
alert($$('div.basic').invoke('identify').join(',');
The invoke will call a function by name. The identify function will provide the id. When called on an array it will return an array of their ids. Join turns them into a string with commas in between.

Categories