Javascript pass a variable from function call to innerHtml - javascript

Ok, this might be an easy one, im just not sure how to do it. I have a main function where it's taking in an "id". This id is unique and I want to pass it over to another function that is doing a count for me and returns that count to an innerHtml span tag.
Reason for this is because I can have 5 of these open at the same time, but they will have the same span id name "editCommentsCounter"...I want them to be like "editCommentsCounter-id"
function editCommentToggle( id )
{
theRow = document.getElementById("id"+id);
//user = theRow.cells[0].innerHTML;
//date = theRow.cells[1].innerHTML;
com = theRow.cells[2].innerText ;
comLength = theRow.cells[2].innerText.length ;
idx = 2;
maxlength = 250;
count = maxlength - comLength;
// Comment field
cell = theRow.cells[idx];
while( cell.childNodes.length > 0 ) cell.removeChild(cell.childNodes[0]);
spanTag = document.createElement("span");
spanTag.innerHTML = "You have <strong><span id='editCommentsCounter'>"+count+"</span></strong> characters left.<br/>";
cell.appendChild(spanTag);
element = document.createElement("textarea");
element.id="commentsTextArea-"+id;
element.rows="3";
element.value = com;
element.style.width = "400px";
element.maxLength = "250";
element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit('editCommentsCounter', maxlength, this);};
cell.appendChild(element);
}
Basically I want to take :
spanTag.innerHTML = "You have <strong><span id='editCommentsCounter'>"+count+"</span></strong> characters left.<br/>";
and make that into something like `span id='editCommentsCounter-' + id
so when I call this:
element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit('editCommentsCounter', maxlength, this);};
I call this above with editCommentsCounter with that id attached to it
See what Im saying?

Use:
document.getElementById("editCommentsCounter-" + id).innerHTML = someVal;
You have a lot there but it seems like that is what you're trying to do to write the innerHTML val. If not please tell me more in comments and I can suggest more.
I see you want to dynamically build a new span, then populate the content. One thing that is puzzling in the beginning you reference the element and concat "id"+id. Have to think about this one so apologies for too quick response; was just looking at your end result.
Setting the unique ID:
var spanTag = document.createElement("span");
spanTag.id = 'editCommentsCounter-' + id;
spanTag.innerHTML = 'You have ...' + count + '...';
document.body.appendChild(spanTag);
I hope this helps!

Related

User Input to Output for JS function

I'm trying to take user input from within an HTML file, convert it, and output it back to the page using <input> rather than prompt.
Here's what I have so far.
function bhedTester() {
alpha = "ABC";
bhed = "JYI";
btext = "";
i = 0;
while (i < norm.length) {
ind = alphabet.indexOf(norm.charAt(i));
btext = btext + bhed.charAt(ind);
i++;
}
btext
}
I've tested this using the prompt command and it works, but when I go to use
document.getElementById
OR
document.form_name._input_name.value
and then return that neither seems to work.
Can anyone advise?
If you're triggering this function from a DOM event you have to return btext.
function bhedTester() {
var alpha = "ABC";
var bhed = "JYI";
var btext = "";
var i = 0;
while (i < norm.length) {
var ind = alphabet.indexOf(norm.charAt(i));
btext = btext + bhed.charAt(ind);
i++;
}
return btext
}
To write to a div you will have to do:
document.getElementById("yourDiv").innerHTML= bhedTester();
And after that you will need to return a string from the function you wrote.
Right now it is not returning anything.
So your code should look like:
function bhedTester() {
alpha = "ABC";
bhed = "JYI";
btext = "";
i = 0;
while (i < norm.length) {
ind = alphabet.indexOf(norm.charAt(i));
btext = btext + bhed.charAt(ind);
i++;
}
return btext;
}
Since I don't know your norm and alphabet can't give you an exact solution.
You need to listen for when either the text is changed in the input or when the button is clicked. Your code just runs when the page loads. It does not magically run when you type text. You need to alter it to run when the user changes the text. So you need to use addEventListener to bind the event.
//bind the change event
document.getElementById("foo").addEventListener("change", function(){
var textbox = this, //reference the textbox
value = this.value; //get what the user typed
document.getElementById("bar").innerHTML = value; //set the value
});
<input type="text" id="foo" />
<div id="bar" />
Now if you want to run it when the user is typing, than use the keyup event.

Pushing info from form values to object not working

I am having trouble with getting the values of the form i have created with javascript to push into the object.
im in a project creating an addressbook and im stuck here and dont know what to do. So if anyone can help me with that!
The first part of the code is the object function I have created. And appends the contacts to li's.
The second part of the code is to create a form, and loop a form with 5 input fields.
The third and last part of the code is where I dont know what to do or how to do.
I need to get the values of the form and push is it in to the object (as arguments?) to ( contacts = []; ) but isnt working.
//Contactlist funktion
function Contact(fname, lname, address, email, phone) {
this.fname = fname;
this.lname = lname;
this.address = address;
this.email = email;
this.phone = phone;
}
//The contacts
var contacts = [];
// Appending the objects
function theContacts() {
var body = document.getElementsByTagName('body')[0],
outerUL = document.createElement('ul'),
length = contacts.length;
outerUL.className = 'contactlist';
for (var i = 0; i < length; i++) {
var cont = contacts[i],
li = document.createElement('li'),
ul = document.createElement('ul');
li.className = 'contact'; li.innerHTML = cont.fname + ' ' + cont.lname;
ul.className = 'infos';
for (var key in cont) {
var info = document.createElement('li');
info.className = key;
info.innerHTML = cont[key];
ul.appendChild(info);
}
li.appendChild(ul); outerUL.appendChild(li);
}
body.appendChild(outerUL);
}
and then I have this part...
// Calling the object
function addForms(){
var body = document.getElementsByTagName('body')[0]
var form = document.createElement("form");
var myArray = ['fnameValue', 'lnameValue', 'addressValue', 'emailValue', 'phoneValue'];
var texts = ['First Name: ', 'Last Name: ', 'Address: ', 'Email: ', 'Phone: '];
// Create a loop of 5
for(var i = 0; i < 5; i++){
var input = document.createElement('input');
var newlabel = document.createElement('label');
// newlabel.setAttribute('for', myArray[i]);
newlabel.innerHTML = texts[i];
form.appendChild(newlabel);
input.setAttribute('type','text');
input.setAttribute('id', myArray[i]);
// adds the input's to the form.
form.appendChild(input);
}
// adds the forms to the body
body.appendChild(form);
// Add Contact Button
var addContact = document.createElement('input')
addContact.setAttribute('type', 'button')
addContact.setAttribute('id', 'addContact')
addContact.setAttribute('value', 'Add Contact')
form.appendChild(addContact);
var knapp = document.getElementById('addContact');
knapp.addEventListener('click', addNewContact)
}
This is the part that i am stuck with, and well maybe i need to modify the code above too, idk..
Please help me.
function addNewContact() {
var input1 = document.getElementById('fnameValue').value;
var input2 = document.getElementById('lnameValue').value;
var input3 = document.getElementById('addressValue').value;
var input4 = document.getElementById('emailValue').value;
var input5 = document.getElementById('phoneValue').value;
contacts.push(input1, input2, input3, input4, input5);
}
document.getElementById("newButton").addEventListener("click", addForms);
I got some things sorted out, but there is still some work cut out. Anyway, I got the addNewContact() method working after attaching the event listener directly to the button:
addContact.addEventListener('click', addNewContact, false);
In the addNewContact() method I emptied the contacts array before adding any elements to it, because otherwise after the second 'addContact' button click there'll be twice as many elements in the array.
contacts.length = 0; //this empties the array
contacts.push(input1, input2, input3, input4, input5);
Alternatively, instead of doing the above, I tried directly adding a Contact object into contacts array:
contacts.push( new Contact(input1, input2, input3, input4, input5) );
Finally, like Teemu suggested I removed the infinite loop call in the addNewContact() method
After I did those things, I got theContacts() method working partly, which was called in the addNewContact() method. Fiddle

why is document.getElementsByName("name") is not returning any values?

I am creating an html element and assigning id and name values programmatically and later when i am trying to access those elements by name it is not returning any value
say for example i create a html input element and assign id = "Number_1" and name = "Name_1"
document.getElementsByName("Name_1").length is always 0
where as below code works and returns correct value
document.getElementById("Number_1" ).name = "Name_1"
why is this happening?
var count = 0;
for(var i =0;i<SomeValue;i++){
count++;
var cell = row.insertCell(i);
cell.className = "lineItemTable";
var inputElement = document.createElement("input");
inputElement.type = "text";
inputElement.id = "Number_"+count;
inputElement.name="Name_"+count;
cell.appendChild(inputElement);
}
In Internet Explorer, you can't add a "name" after creating the element:
var inputElement = document.createElement("<input name='Name_" + count + "'>");
You have to create it like that, providing the name as an attribute in the "html".
edit — OK this is rich.
At some point, Microsoft published this note in their "Compat Cookbook". Key point:
As of Windows Internet Explorer 9, the createElement triggers an "object not found" exception when you use angle brackets (< >).
That note contains a link to the documentation for the createElement method, which still insists that the "NAME" attribute can only be set by using the "eTag" text, as in my example above.
Thus it looks like what you need to do is something like this:
function makeInput( name ) {
try {
return document.createElement("<input name='" + name + "'>");
}
catch (x) {
var inp = document.createElement("input");
inp.name = name;
return inp;
}
}

function to change argument to another sign

I dynamically create this list element and information a user has typed in shows up in it when a button is clicked 'info' is text and shuld show as it is but 'grade' is a number that i want to convert to another sign with the function changeNumber() but I am new to javascript and cant figure out how to make this function, can anyone give a suggestion or point me in the right direction?
var list = $("#filmlista");
var list_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = list_array[0][1];
var element = '<li class="lista">' + list + '<span class="grade">'+ changeNumber(grade) +'</span></li>';
list.append(element);
}
should I use innerHTML? not shure I understand how it works? and how do I use the replace method if I have to replace many different numbers to the amount of signs the number is?
for example if the number is 5 it should show up as: *****, if number is 3 show up as: *** and so on
Here's some code that should do the trick:
Add this function into your script.
function changeNumber(number) {
var finalProduct = "";
for (var i = 0; i < number; i++) {
finalProduct += "*";
}
return finalProduct;
}
Replace the updateFilmsList with this code.
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = changeNumber(list_array[0][1]);
var element = '<li class="lista">' + list + '<span class="grade">'+ grade +'</span></li>';
list.append(element);
It looks like you're trying to do something like PHP's str_repeat. In that case, take a look at str_repeat from PHPJS
There are options other than a loop:
function charString(n, c) {
n = n? ++n : 0;
return new Array(n).join(c);
}
charString(3, '*'); // ***
You can use innerHTML to set the text content of an element provided none of the text might be mistaken for markup. Otherwise, set the textContent (W3C compliant) or innerText (IE proprietary but widely implemented) property as appropriate.

JavaScript Node.replaceChild() doesn't count new child's innerHtml

While creating a Firefox addon, I've run into a weird problem.
I have an array of nodes, returned by some iterator. Iterator returns only nodes, containing Node.TEXT_NODE as one or more of it's children. The script runs on page load.
I have to find some text in that nodes by regexp and surround it with a SPAN tag.
//beginning skipped
var node = nodeList[i];
var node_html = node.innerHTML;
var node_content = node.textContent;
if(node_content.length > 1){
var new_str = "<SPAN class='bar'>" + foo + "</SPAN>";
var regexp = new RegExp( foo , 'g' );
node_html = node_html.replace(regexp, new_str);
node.innerHTML = node_html;
}
Basic version looked like this, and it worked except one issue - node.innerHTML could contain attributes, event handlers, that could also contain foo, that should not be surrounded with <span> tags.
So I decided to make replacements in text nodes only. But text nodes can't contain a HTML tag, so I had to wrap them with <div>. Like this:
var node = nodeList[i];
for(var j=0; j<node.childNodes.length; j++){
var child = node.childNodes[j];
var child_content = child.textContent;
if(child.nodeType == Node.TEXT_NODE && child_content.length >1){
var newChild = document.createElement('div');
// var newTextNode = document.createTextNode(child_content);
// newChild.appendChild(newTextNode);
var new_html = child_content;
var new_str = "<SPAN class='bar'>" + foo + "</SPAN>";
var regexp = new RegExp( foo , 'g' );
new_html = new_html.replace(regexp, new_str);
newChild.innerHTML = new_html;
alert(newChild.innerHTML);
node.replaceChild(newChild, child);
}
}
In this case, alert(newChild.innerHTML); shows right html. But after the page is rendered, all <div>s created are empty! I'm puzzled.
If I uncomment this code:
// var newTextNode = document.createTextNode(child_content);
// newChild.appendChild(newTextNode);
alert also shows things right, and <div>s are filled with text (textNode adding works ok) , but again without <span>s. And another funny thing is that I can't highlight that new <div>s' content with a mouse in browser.
Looks like it doesn't take new innerHTML into account, and I can't understand why.
Do I do something wrong? (I certainly do, but what? Or, is that a FF bug/feature?)
Since you are in Firefox you can use fun stuff like TreeWalker and Range. You may even be able to get rid of the code that gives you the initial array of nodes.
var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
var range = document.createRange();
var wrapper = document.createElement('span');
wrapper.className = "wrapper";
var node;
var re = /^wrap me$/;
while (node = walker.nextNode()) {
if (re.test(node.textContent)) {
range.selectNode(node);
range.surroundContents(wrapper.cloneNode(true));
}
}
JSBin
You could tweak this so only part of the text node is wrapped by setting the range differently and TreeWalker can be filtered more.
Range / TreeWalker
That code is really odd; why are those three lines outside of the if statement?
I think it should look something like this:
var node = nodeList[i];
for(var j=0; j<node.childNodes.length; j++){
var child = node.childNodes[j];
var child_content = child.textContent;
if(child.nodeType == Node.TEXT_NODE && child_content.length >1){
var newChild = document.createElement('div');
newChild.innerHTML = '<span class="bar">' + child_content + '</span>';
node.replaceChild(newChild, child);
}
Now I can't figure out what was going on with that regex and the replacement stuff; it makes no sense to me in the code you've posted.

Categories

Resources