Javascript GetElementById Set Value To Input - javascript

I am trying to set value to my input but I want to do this while my data ends. As you know id must be unique in html. So i created an 'element' variable and I am increasing it.
I want to make my input text my model's CustomerName.
That's my code.
var element = 0;
var HTML = "";
while (element !== 5) {
HTML += "<input id=senderName" + element + " class=senderNameText type=text>";
document.getElementById("senderName" + element).value = "#Html.DisplayFor(model => model.CustomerName)";
element++;
}
div.innerHTML = HTML;
document.body.appendChild(div);
When I check it at console in Chrome it is written as "Cannot set property 'value' of null".
What should I do.
Thanks.

Your code should be like the following (note the quotes ' in creation of he new inputs are necessary) :
var element = 0;
var HTML = "";
while (element !== 5) {
div.innerHTML = "<input id='senderName" + element + "' class='senderNameText' type='text'>";
document.body.appendChild(div);
document.getElementById("senderName" + element).value = "#Html.DisplayFor(model => model.CustomerName)";
element++;
}
Now the problem come when you try to select new elements from the document and you're not yet append them so you get the message error that mean JS can't find any elements by the ids you're given.
So you should append the new HTML to the DOM inside loop.
Hope this helps.

Related

Passing argument to on click event of dynamically generated element

I am trying to pass arguments to onclick event of dynamically generated element. I have already seen the existing stackoveflow questions but it didn't answer my specific need.In this existing question , they are trying to access data using $(this).text(); but I can't use this in my example.
Click event doesn't work on dynamically generated elements
In below code snippet, I am trying to pass program and macroVal to onclick event but it doesn't work.
onClickTest = function(text, type) {
if(text != ""){
// The HTML that will be returned
var program = this.buffer.program;
var out = "<span class=\"";
out += type + " consolas-text";
if (type === "macro" && program) {
var macroVal = text.substring(1, text.length-1);
out += " macro1 program='" + program + "' macroVal='" + macroVal + "'";
}
out += "\">";
out += text;
out += "</span>";
console.log("out " + out);
$("p").on("click" , "span.macro1" , function(e)
{
BqlUtil.myFunction(program, macroVal);
});
}else{
var out = text;
}
return out;
};
console.log of out give me this
<span class="macro consolas-text macro1 program='test1' macroVal='test2'">{TEST}</span>
I have tried both this.program and program but it doesn't work.
Obtain values of span element attributes, since you include them in html:
$("p").on("click" , "span.macro" , function(e)
{
BqlUtil.myFunction(this.getAttribute("program"),
this.getAttribute("macroVal"));
});
There are, however, several things wrong in your code.
you specify class attribute twice in html assigned to out,
single quotes you use are not correct (use ', not ’),
quotes of attribute values are messed up: consistently use either single or double quotes for attribute values
var out = "<span class='";
...
out += "' class='macro' program='" + program + "' macroVal='" + macroVal + ;
...
out += "'>";
depending on how many times you plan to call onClickTest, you may end up with multiple click event handlers for p span.macro.

HTML is coming out as plaintext

I am trying to add some text to an element, however it is all coming out as plaintext, even when there is an HTML element included.
for (i = 0; i < restext.length; i++) {
var p = document.createElement("p");
p.innerHTML = "<p>" + restext[i].innerHTML + "</p>";
document.getElementById("registererrors").appendChild(p);
}
However with this, it prints out the tag:
The name <em class="placeholder">name</em is already taken.
How do I make it so that it processes this tag too?
Change
p.innerHTML = "<p>" + restext[i].innerHTML + "</p>";
to
p.innerHTML = restext[i].innerHTML;
The problem is that after you create p element with document.createElement you add <p></p> inside of it. And inside of the inner p tag you insert other HTML code, which automatically gets escaped.

edit (append?) a string stored in a jquery variable

I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);

Javascript - Regex : How to replace id in string with the same id plus number?

I have a string with multiple elements with id's like below:
var data = "<div id='1'></div><input type='text' id='2'/>";
Now I'm using this regex to find all the id's in the string:
var reg = /id="([^"]+)"/g;
Afterwards I want to replace all those id's with a new id. Something like this:
data = data.replace(reg, + 'id="' + reg2 + '_' + numCompare + '"');
I want reg2, as seen above, to return the value of the id's.
I'm not too familiar with Regular Expressions, so how can I go about doing this?
Instead of using regex, parse it and loop through elements. Try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = document.createElement("div"),
i, cur;
div.innerHTML = data;
function updateId(parent) {
var children = parent.children;
for (i = 0; i < children.length; i++) {
cur = children[i];
if (cur.nodeType === 1 && cur.id) {
cur.id = cur.id + "_" + numCompare;
}
updateId(cur);
}
}
updateId(div);
DEMO: http://jsfiddle.net/RbuaG/3/
This checks to see if the id is set in the first place, and only then will it modify it.
Also, it is safe in case the HTML contains a comment node (where IE 6-8 does include comment nodes in .children).
Also, it walks through all children of all elements. In your example, you only had one level of elements (no nested). But in my fiddle, I nest the <input /> and it is still modified.
To get the get the updated HTML, use div.innerHTML.
With jQuery, you can try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = $("<div>"),
i, cur;
div.append(data);
div.find("[id]").each(function () {
$(this).attr("id", function (index, attr) {
return attr + "_" + numCompare;
});
});
DEMO: http://jsfiddle.net/tXFwh/5/
While it's valid to have the id start with and/or be a number, you should change the id of the elements to be a normal identifier.
References:
.children: https://developer.mozilla.org/en-US/docs/DOM/Element.children
.nodeType: https://developer.mozilla.org/en-US/docs/DOM/Node.nodeType
jQuery.find(): http://api.jquery.com/find/
jQuery.attr(): http://api.jquery.com/attr/
jQuery.each(): http://api.jquery.com/each/
Try using
.replace(/id='(.*?)'/g, 'id="$1_' + numCompare + '"');
Regex probably isn't the right way to do this, here is an example that uses jQuery:
var htmlstring = "<div id='1'></div><input type='text' id='2'/>";
var $dom = $('<div>').html(htmlstring);
$('[id]', $dom).each(function() {
$(this).attr('id', $(this).attr('id') + '_' + numCompare);
});
htmlstring = $dom.html();
Example: http://jsfiddle.net/fYb3U/
Using jQuery (further to your commments).
var data = "<div id='1'></div><input type='text' id='2'/>";
var output = $("<div></div>").html(data); // Convert string to jQuery object
output.find("[id]").each(function() { // Select all elements with an ID
var target = $(this);
var id = target.attr("id"); // Get the ID
target.attr("id", id + "_" + numCompare); // Set the id
});
console.log(output.html());
This is much better than using regex on HTML (Using regular expressions to parse HTML: why not?), is faster (although can be further improved by having a more direct selector than $("[id]") such as giving the elements a class).
Fiddle: http://jsfiddle.net/georeith/E6Hn7/10/

"document.getElementById" return null after a "document.write"

I am using a javascript code to write on my document :
nr = Math.floor(Math.random()*99999999999);
document.write('<div class="wads-content-' + nr + '" id="flashcontent' + nr + '">'+ flashrequired +'</div>');
var flashcontent = document.getElementById('flashcontent' + nr);
In my page, i execute this script twice. The first time everything works, but the second time, flashcontent is null, but i know it's wrong because I just write the element before the :
document.getElementById
Any idea what is happening?
Instead of document.write, do (good ol' JavaScript)
var div = document.createElement("div");
div.className = "wads-content-" + nr;
div.id = "flashcontent";
div.innerHTML = flashrequired;
The jQuery way of doing things:
$("<div/>").addClass("wads-content" + nr).attr("id", "flashcontent" + nr);
var flashcontent = $("#flashcontent" + nr);
I can only assume that the second call of document.write() occurs after the document has been loaded. The document is overwritten by the call then, as the output stream has been closed. See also W3C DOM Level 2 HTML.
My solution was to use this code :
var div = document.createElement("div");
div.innerHTML = flashrequired;
//Add the flash HTML (embed) in my div
addFlash(div);
var el = '<div class="wads-content-' + nr + '" id="flashcontent' + nr + '">'+ div.innerHTML +'</div>';
document.write(el);
So i don't have to find the element in my dom, i create it in javascript and just write it in my document.

Categories