In one javascript function I am creating a textarea based on some JSON data I am grabbing from another site. I create the textarea here:
if(type == 'fill-in'){
var textField = $('<center><div id="response-text"><textarea id="test" name="test" rows="10" cols="80">Answer here</textarea></div></center>').appendTo(panel.root);
}
In another function, I need to grab the value of this textfield and send it off to another site. I have tried this in various ways using
document.getElementById("test").value
But that gives me an error, and if I use
document.getElementByName("test").value
It tells me that the value is undefined. Do text areas not automatically set their values to whatever you type into them? Is there a better way to grab what is being typed into the textarea?
EDIT:
getElementById is working now... not sure what I was doing before but I must have tried it 3-4 times. I apologize for the pointless question.
Here's my best guess as to what's actually going on in your code and why you may be getting screwed over by variable hoisting.
I imagine you're trying to dynamically add your text area and then grab a reference right after by using var test = document.getElementById("test");. Because of variable hoisting, declared variables are hoisted to the top of the current scope. This would result in the declaration happening before the text area gets added.
As it is unclear where the problem lies with the OP, I did notice that you're using getElementsByName incorrectly.
getElementByName should be getElementsByName. A subtle but significant difference. Since names do not need to be unique, the function gathers a node list of all DOM elements with a given name attribute.
getElementById on the other hand returns a reference to the element itself.
getElementsByName:
Returns a list of elements with a given name in the HTML document.
getElementById:
Returns a reference to the element by its ID.
Using getElementById works just fine. You must have something wrong with your HTML markup - perhaps another element with the id of test.
Working fiddle:
I am assuming that Teaxarea element is loaded successfully and present in the DOM. In that case, your javascript is loading & executing even before Textarea element is loaded & ready in the DOM.
Regards,
Related
I have a function that dynamically creates div elements based upon whatever input is given, and lets them choose certain items by clicking on each div. I have it so that if the div is clicked, a function (named checkToggle) is called that makes it looks like it is selected and adjusts some related variables. There is a checkbox in the div element that is toggled by this function (hence its name). Long story short, I had to jump through some hoops to get it to work, most of which I don't even remember. Please don't ask me about that.
The point of this question is this. I initially used the following JavaScript code to run the function when the checkbox was clicked. It was assigned by the main function, which created these div elements using a for loop.
document.getElementById(`${itemID}-checkbox`).onclick = function() {
checkToggle(`${itemID}-checkbox`);
};
This works, but I wanted to try to convert all of my onClick functions to JQuery. Here is the JQuery alternative I created.
$(`${itemID}-checkbox`).on(`click`, function() {
checkToggle(`${itemID}-checkbox`);
});
While the code itself seems to be fine, it does not work. It seems as if JQuery functions cannot be created like this in a for loop or something. It is applied after the element is created and put in its place, so I don't think it has anything to do with the element not being ready. I am also having the same issue with 2 other similar cases. Any idea as of why this isn't working?
Let me know if more information is needed and if so, what kind of information is needed.
You need to update the selector to Target HTML id using the # character. Simply prepend the character to the query:
$(`#${itemID}-checkbox`).on(`click`, function() { checkToggle(`${itemID}-checkbox`); });
It would also apply to DOM methods querySelector or querySelectorAll as well.
Hopefully that helps!
I'm trying to change the id 'character' to 'characterSelected'
var character = document.getElementById('character');
var characterSelected = document.getElementById('characterSelected');
function klik() {
character.innerHTML = characterSelected;
}
character.addEventListener('click', klik);
This is what I have so far but it doensn't seem to work. I want to do this using Javascript only, no jQuery.
Thanks
You tried something, it didn't work. Now is the time to look up the standard properties and functions you're using incorrectly. If guessing doesn't work, always look for reliable documentation.
A good reference would be the Mozilla Developer Network (MDN). It's a wiki-style encyclopedia about the web, its standards and current browser compatibility. If you look at the page about innerHTML, you'll find the following:
The Element.innerHTML property sets or gets the HTML syntax describing
the element's descendants.
This means that the innerHTML property is used to replace the content of a tag as if you wrote that HTML inside it. Not what you want.
What you wanted was to change the id of an element. If you search for element id, you'll land on the Element.id page. And how practical, there's an example:
var idStr = elt.id; // Get the id.
elt.id = idStr; // Set the id
However, this is not going to fix your issues. You see, you guessed wrong when trying to use the getElementById function. This function looks at the page and finds the element with that id right now. If you don't have any element with the characterSelected id at first, then this variable you set is going to be null for the rest of time. Variables won't magically update when an element with that id is placed in the page.
And finally, you have missed the purpose of the id attribute itself.
Its purpose is to identify the element when linking (using a fragment
identifier), scripting, or styling (with CSS).
The purpose of an id is to identify an element uniquely. You might think: "that's what I'm doing". No. You're using an id to represent whether or not an element is selected. This is wrong. Depending on your objective, I would say: just store the selected element inside a variable. Then whenever you need to do something with the selected element, it's in that variable. If you need specific style for that element, then you could set a class to it. But the id isn't meant for this at all - in fact, an id isn't meant to change once an element is placed.
I have two form on same page. There is a text field with same name in both of the forms.
I am tried to read the value of the text field from one of the two forms. if I am trying to read the value using below code i am getting the value . But I am not sure from which forms it is returning the value.
document.getElementById("groupId")
Now if I am trying to read the value from specific form using below code I am receiving the error.
document.forms["form1"].getElementById("groupId")
Please suggest whats wrong I am doing and how can we read the value of a control ?
I can use both javascript and jquery.
Since you're using jQuery you could do :
$('[name=form_name]').find('#field_id');
Your case e.g :
$('[name=form1]').find('#groupId');
Using pure js you could do it like :
document.form_name.getElementById("field_id");
Sample of your case :
document.form1.getElementById("groupId");
Hope this helps.
You can do the following with jquery.
var element = $(document.forms["form1"]).find('#groupId')
And to get the text value you can use the val function.
var text = element.val();
if i am trying to read the value using below code i am getting the value . But i am not sure from which forms it is returning the value.
This means you have multiple elements with same id which is a big NO. id's are supposed to be unique in your entire HTML. If for some reason you want to use same id on multiple elements to work with JavaScript be aware the same task is possible by assigning same class to the elements and accessing by class
Having said that, Change your HTML to not have duplicate id and change them to have a common class. Now with this structure you can access the element starting from your from like below
$('form[name="form1"]').find('input.ClassName').val()
Also for info purpose: If you have multiple elements with same id in your HTML and when you try to access by id the element which is placed in top parsing from top will be selected always.
The W3C standards for HTML require the id to be unique in a document.
I have a $('.textarea').val() that gets the value of said textarea upon submission, inserts it into a Mongo.Collection and then displays it through {{#each}}{{/each}} in the body.
Before the text is inserted into the collection and then returned & published again, I have a regex set up to replace all image links with <img src='said link'>
My issue is that .val() does not work with tags, only .html and .text does, which I cannot use to get the value of a textarea. Is there any clever way of going about this (replacing .val() with .html()? Perhaps a listener on the body to replace all links with the tag after the text has already been submitted, in which case, how would I go about setting it up to listen for all text change?
EDIT:
To be more precise, is there a way to perform
$('.messages').html($('.messages).html().replace(this, 'that'))
on values that are constantly changing and output by {{#each}}
after returned from a collection? Is there a way to refer to each of the messages rather than whole?
If I understand correctly you are trying to replace all the sources in a text with images. This should help you:
http://forum.jquery.com/topic/replacing-text-links-with-images
Also, read this part of the jquery documentation:
http://api.jquery.com/attr/
I think that you are on the right track: changing the .html() should work.
I have an asp:bulletedlist control, which sits inside a div tag, and I need to count the number of list items inside the control. Searching the internet, and noting the fact the html given back by the items is a list i.e. <li>, I thought I could use an example of:
var listcontrol = document.getElementById('BulletedList1');
var countItems = listcontrol.getElementByTagName('li').length;
However, when I do this, it throws and error saying that no object exists for this control.
So, my problem is, and because I must do this clientside because I want to use this to set the height of the div tag, is how do you count the number of items inside a asp:bulletedlist control with javascript?
You can't use document.getElementById like you are using it because the actual ID for an Asp.Net control when rendered is different than what you set for the ID on the control. View the source of your page and you will see what the actual ID is. You can then use that if you want and this code should work, but it would break if you ever moved the bulletedlist control, since the hierarchy would change.
Another way to do this would be to use jQuery. In your example, you could do this:
$('[id$=BulletedList1]').children('li').size()
This would select the element that ends with 'BulletedList1', gets the li children, and then returns the size of the collection.