Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am creating a random fact generator which will be written inside a <p> tag. I followed every tutorial there is and I don't see where is the problem. The function is being summoned normally (i check that with alert).
Here is the code:
HTML:
<p id="rfact" name="rndfact">random fact goes here</p>
JS:
function rfact(){
var nrfact=Math.floor(Math.random()*2)
alert(nrfact);
if (nrfact==0) document.getElementByName("rndfact").innerHTML="random fact1";
if (nrfact==1) document.getElementByName("rndfact").innerHTML="random fact2";
if (nrfact==2) document.getElementByName("rndfact").innerHTML="random fact3";
}
Your problem is that there is no function called getElementByName on document.
You want one of these:
document.getElementById('rfact');
document.getElementsByName('rndfact')[0] // notice the plural
You are using a method that does not exist. There is not such method as getElementByName.
Use either document.getElementsByName (note the plural in elements, you'll get an array), or document.getElementById (which is the right way to do it).
Solution: http://jsfiddle.net/P7wev/
Use getElementById, since the getElementByName you supplied in doesn't exist nor does the name attribute inside the P tag.
function rfact(){
var nrfact=Math.floor(Math.random()*2);
alert(nrfact);
if (nrfact==0) document.getElementById("rfact").innerHTML="random fact1";
if (nrfact==1) document.getElementById("rfact").innerHTML="random fact2";
if (nrfact==2) document.getElementById("rfact").innerHTML="random fact3";
}
Use document.getElementById("rfact").innerHTML=... instead.
this should work for ya.
<script type="text/javascript">
window.onload=function(){
rfact();
function rfact(){
var nrfact=Math.floor(Math.random()*2)
alert(nrfact);
if (nrfact==0) document.getElementById("rfact").innerHTML="random fact1";
if (nrfact==1) document.getElementById("rfact").innerHTML="random fact2";
if (nrfact==2) document.getElementById("rfact").innerHTML="random fact3";
}
}
</script>
HTML --> id="rndfact"
<p id="rndfact" name="rndfact">random fact goes here</p>
JS --> getElementById
function rfact() {
var nrfact = Math.floor(Math.random() * 3);
if (nrfact == 0) document.getElementById("rndfact").innerHTML = "random fact1";
if (nrfact == 1) document.getElementById("rndfact").innerHTML = "random fact2";
if (nrfact == 2) document.getElementById("rndfact").innerHTML = "random fact3";
}
rfact()
Use getElementById or use getElementsByName[0]
You have an id set use that instead. getElementsByName returns an array, you have to access the return as such, by using the array notation before accessing the properties like innerHTML
Using getElementById
function rfact(){
var nrfact=Math.floor(Math.random()*3)
alert(nrfact);
var element = document.getElementById("rfact");
if (nrfact==0) element.innerHTML="random fact1";
if (nrfact==1) element.innerHTML="random fact2";
if (nrfact==2) element.innerHTML="random fact3";
}
Using getElementsByName
function rfact(){
var nrfact=Math.floor(Math.random()*3)
var elements = document.getElementsByName("rndfact");
if (nrfact==0) elements[0].innerHTML="random fact1";
if (nrfact==1) elements[0].innerHTML="random fact2";
if (nrfact==2) elements[0].innerHTML="random fact3";
}
And use 3 instead of 2 in the formula to allow up to 3 facts.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
I've searched the jQuery docs and here and can't find an answer to my exact problem...
With a DRY spirit, I want to use javascript to add a character object countdown helper to any textarea element with maxlength and aria-describedby attributes.
Obviously I also need to use javascript to monitor keyup events to update the counter. I'm using jQuery 3.6.0. However, I can't seem to get the countdown method to recognize the newly-added "helper" div element. Here's what I have so far:
$(document).ready(function () {
// "characters remaining" countdown
function textCounter(field) {
var charLimit = field.attr("maxlength");
console.log("charLimit=" + charLimit);
// hack to *double-count* '\r\n' (client/DB discrepency)
var numLines = (field.val().match(/\n/g) || []).length;
var charLength = field.val().length + numLines;
console.log("charLength=" + charLength);
var charDiff = charLimit - charLength;
console.log("charDiff=" + charDiff);
if (charLength > charLimit - numLines)
field.val(field.val().substring(0, charLimit - numLines));
var count = $("#" + field.attr("aria-describedby") + " .count");
console.log(count.html());
count.html(Math.max(0, charDiff));
}
// add countdown helper div
$("textarea[maxlength]").each(function (e) {
var helpID = "#" + $(this).attr("aria-describedby");
var helpDiv = $('<div id="' + helpID + '"><span class="count"></span> characters left.</div>')
$(this).after(helpDiv);
textCounter($(this));
})
// update counter on keyup events
$("textarea[maxlength]").keyup(function () { textCounter($(this)); })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="2000" aria-describedby="content-help" id="content" name="content"></textarea>
I can confirm that:
The helper div element is getting added
Via the console.log statements, the textCounter() method is getting called, but the count object resolves to undefined (even though it is clearly there), and
If the element is hardcoded in HTML (i.e., not dynamically added) the counter works as expected.
Other searches suggest that .delegate() or .on() are part of the answer, but everything I've tried has the exact same behavior as above. :( Every other Q/A I've come across is, for example, binding a click/hover event to the newly-added element, but here it's the textarea that needs monitoring (not the new helper element, although it will be updated), if that makes sense...
Note that I want the solution to work on pages that have multiple textareas, each with potentially different maxlength attributes.
Any thoughts how to accomplish this?
The line:
var helpID = "#" + $(this).attr("aria-describedby");
means that your selector:
var count = $("#" + field.attr("aria-describedby") + " .count");
Should be:
var count = $("#\#" + field.attr("aria-describedby") + " .count");
Or you could simply not include the "#" character when creating the element, giving:
var helpID = $(this).attr("aria-describedby");
Unfortunately this is a typo question (so it will be closed as such), this answer exists only temporarily to clearly show the error.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I trying use the Javascript DOM. I need get a information (data-content), searching by class.
The html of website is:
<li class="item info-icon info-icon-phone">
<strong itemprop="telephone" class="phone-place js-expansible-text js-phone-tracker display-phone_ad" data-content="(19) 3879-1066 / (19) 3879-1066" data-style_class="clickable" data-place_id="76588JTY">(19) 3879-1066 / (19) 3879-1066</strong>
</li>
My code doesn't works:
var script = document.getElementsByClass('phone-place js-expansible-text js-phone-tracker display-phone_ad');
var script = document.getElementsByClassName('phone-place js-expansible-text js-phone-tracker display-phone_ad');
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
I believe the function you are looking for is getElementsByClassName.
What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return?
You can retrieve element attributes using the getAttribute() method.
In this instance you could use the following to get the data-content attributes:
var elements = document.getElementsByClassName('phone-place js-expansible-text js-phone-tracker display-phone_ad');
var dataContent = elements[0].getAttribute('data-content');
getElementsByClassName returns an array of matching elements, you could replace this with getElementByClassName with returns a single element, this is preferable if you're only expecting one element. In my example you will see you need to reference the first element in the array elements[0] before calling getAttribute()
Instead with getElementByClassName do the following:
var element = document.getElementByClassName('phone-place js-expansible-text js-phone-tracker display-phone_ad');
var dataContent = element.getAttribute('data-content');
A quick bin to show this in action
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am having an issue making a div a child of another div. I would like to learn how to do this in javascript.
I would like to essentially create this:
<body>
<div id = "graph">
<div id "data">
</div>
</div>
</body>
By using javascript. The end goal is to create many of these over and over again.
Here is the code I have so far:
var graph = document.createElement('div');
graph.id = "graph";
document.body.appendChild(graph);
var barWrapper = document.createElement('div');
barWrapper.id = "data";
The above works with no error. When I add:
document.getElementbyId("graph").appendChild("data");
I get "Uncaught Type Error: Undefined is not a function".
From my research this seems to be everyone's suggestion. Also, the appendChild function seems to be complete to my knowledge. What am I missing? Thank you in advance!!
Your problem (which is causing your type error) is you're attempting to append a string, not a reference to the child element itself.
var parent = document.createElement("div");
parent.id = "graph";
var child = document.createElement("div");
child.id = "data";
parent.appendChild(child);
You should be appending an object just like you were doing with body.
var parent = document.getElementById("graph");
parent.appendChild(barWrapper);
Edit:
You also dont need to call getElementById here. You should be able to append the child to parent then append the parent to body. Like this:
var graph = document.createElement('div');
graph.id = "graph";
var barWrapper = document.createElement('div');
barWrapper.id = "data";
graph.appendChild(barWrapper);
document.body.appendChild(graph);
The error is beign caused by the typo, it should be getElementById
document.getElementbyId("graph")
>TypeError: undefined is not a function
when you fix that and execute the code you will get
document.getElementById("graph").appendChild("data")
>NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
this is because you are trying to append a string and not an actual html node. you will need to grab the element first as well
document.getElementById("graph").appendChild(document.getElementById("data"));
Since you already have references to both these objects a cleaner solution would be
grap.appendChild(barWrapper);
There are a couple problems
document.getElementbyId("graph") should be document.getElementById("graph")
.appendChild("data") should be .appendChild(bargraph)
This JS works:
var graph = document.createElement('div');
graph.id = "graph";
document.body.appendChild(graph);
var barWrapper = document.createElement('div');
barWrapper.id = "data";
document.getElementById("graph").appendChild(barWrapper);
Fiddle here: http://jsfiddle.net/hatvjete/
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm trying to lookup a field's value, if it equals '1', then put the value '1' in different field, if not put a '0'.
I'm not sure why this isn't working, can anyone help?
<input type="text" name="_1_1_33_1_id" value="" onchange="checkLineManager();">
<input class="valueeditable" type="text" name="_1_1_118_1" id="_1_1_118_1" value="" >
Javascript:
function checkLineManager() {
if (document.getElementsByName('_1_1_33_1_id').value == '1') {
document.getElementById('_1_1_118_1').value = '1';
} else {
document.getElementById('_1_1_118_1').value = '0';
}
}
http://jsfiddle.net/nbren007/o9xp0efy/
Note the plural use of "elements" in the following line:
if (document.getElementsByName('_1_1_33_1_id').value == '1') {
This doesn't return an element, it returns a node list.
// To confirm that
alert(document.getElementsByName('_1_1_33_1_id').toString());
So you need to use:
if (document.getElementsByName('_1_1_33_1_id')[0].value == '1') {
There are other ways of accessing the element as well. Most notably through the form element approach.
The hint is in the method: getElementsByName returns more than one element - it returns an array of matching elements.
You need to use array notation to select the element from the array.
Change:
document.getElementsByName('_1_1_33_1_id')
To:
document.getElementsByName('_1_1_33_1_id')[0]
if (document.getElementsByName('_1_1_33_1_id')[0].value == '1') {
document.getElementById('_1_1_118_1').value = '1';
} else {
document.getElementById('_1_1_118_1').value = '0';
}
Or even neater, use a ternary statement:
document.getElementById('_1_1_118_1').value =
document.getElementsByName('_1_1_33_1_id')[0].value == 1 ? '1' : '0';
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've simple javascript function mentioned below:
<script>
function getValue(val)
{
document.getElementById('answer').value = val;
}
</script>
This function get's called on click of span and returned value gets displayed in input text.
I've three questions:
1] On click of span, if I want to append current value of varible 'val' with previous value; and return appended value to calling function. can you please suggest, how to achieve same without using jQuery?
2] There is one span which is suppose to work like Backspace. So click of span, i want to remove last character from document.getElementById('answer').value [This also without using jQuery]
3] There is one span which is suppose to work like Navigation keys [Right & Left]. So click of span [Let's say right], i want to move cursor position of the input text one character right and similarly for Left [This also without using jQuery]
Can you please suggest some pointers to achieve this?
For your question 1 I think you can do below. Code not tested
function getValue(val)
{
var currentVal = document.getElementById('answer').value
if(currentVal.length > 0 )
currentVal = parseInt(currentVal);
document.getElementById('answer').value = currentVal + val;
}
For question 2 :
Get the value and then do string operation to remove the last char. Its easy little google search for the string operations
For question 3 :
you can use event oncontextmenu for right click. Example below.
How can I capture the right-click event in JavaScript?
For moving cursor check below
Set keyboard caret position in html textbox
+= oprator appends string to existing string(not applicable in this case).
use return keyword to return updated value.
for removing last character use substring.
so try:
function getValue(val)
{
var currentText = document.getElementById('answer').value;
var updatedText = currentText.substring(0,currentText.length-2) + val;
document.getElementById('answer').value = updatedText;
return updatedText;
}