Adding new element to a div removes the current values - javascript

So I have a js function :
function addNewUpload()
{
if(formNumber == 1){
displayRemove();
}
if(formNumber != 10){
var html = " <div id='u_"+(formNumber+1)+"' > ";
//html += " description : <input type='text' name='desc[]' /> <br> ";
html += " photo : <input type='file' name='file[]' /> ";
html += " </div> ";
document.getElementById('uploadHolder').innerHTML += html;
formNumber = formNumber + 1;
} else {
alert("You can only upload 10 photos.");
}
}
it works fine except that it removes the values from the fields that were already added using this function. How can I stop it from doing so?

You should be using DOM methods like appendChild and createNewElement etc.
Try something along these lines:
http://jsfiddle.net/9YHs8/ (in this example, "file" for type was changed to text for demo purposes).
function addNewUpload()
{
if(formNumber == 1){
displayRemove();
}
if(formNumber != 10){
var d = document.createElement("div");
d.id = "u_" + formNumber;
var i = document.createElement("input");
i.type = "file";
i.name = "file[]";
d.appendChild(document.createTextNode(" photo : "));
d.appendChild(i);
document.getElementById('uploadHolder').appendChild(d);
formNumber++;
} else {
alert("You can only upload 10 photos.");
}
}

It's normal
You say "take the innerhtml of my block add some content to it and then reinitialize the inner html of my block with this string"
The form's value are not in the innerhtml !
Look at this thread : Inserting HTML elements with JavaScript

Related

PHP: insert 3 input text in 1 textarea pressing one button

I Have 3 input text in a form, that i would like to joini like this after pressing a button:
TextA-TextB TextC.
I also would like that will be positioniting on th first free line of the text area.
if for eaxmple ther is this situation:
2018-12345 25.00,
i would like that inserting the datas in the 3 text, will become like this:
2018-12345 25.00
TextA-TextB TextC
I imagine that i need javascript and calling the function with event onclick on the button, but i am not into javascript, because of that i am asking for your kind help.
Thanks for the fast answer.
I tried to combine a couple of codes that i found online, but i always get error 404 when I try it on fiddle:
<script>
function fillMessage() {
var annoTA1 = document.getElementById('annoTA') + " ";
var numTess1 = document.getElementById('numTess') + " ";
var impVer1 = document.getElementById('impVer1') + " ";
msg.value = annoTA1.value + numTess1.value + impVer1.value;
var targ = event.target || event.srcElement;
document.getElementById("message").value += targ.textContent || targ.innerText;
var Message= "";
function addText(text) {
Message+= text
}
document.getElementById("message").value = Message;
} </script>
and for the onclick event I used:
<button onclick="fillMessage()">Aggiungi Nuova Tessera</button>
the original fiddle is this:
http://jsfiddle.net/qmrt7z0w/
and plus I added
var Message= "";
function addText(text) {
Message+= text to test there before.
I solved with this script:
<script>
$('#btn').on('click', function (){
var insertText = $('#annoTA').val() + " ";
insertText += $('#numTess').val() + " ";
insertText += $('#impVer').val() + " ";
if(document.getElementById("annoTAG").value == ' ')
{
$('#annoTAG').val( $('#annoTAG').val() + insertText);
}
else
{
$('#annoTAG').val( $('#annoTAG').val() + '\n' + insertText);
}
});
</script>
And for the button i had to use:
<input type="button" value="Aggiungi Nuova Tessera" id="btn" />
Otherwise is not working...
Everything works good now, just that when I am inserting. The first row, it starts with a space. I tried to adding the backspace like this:
if(document.getElementById("annoTAG").value == ' ')
{
$('#annoTAG').val( $('#annoTAG').val() + '\b '+ insertText);
}
But did not works. Any suggestions?
Thanks

html Text editor value is not getting saved

I want to use a text editor in my page.the editor that I have used is
"Responsive-WYSIWYG-Text-Editor-with-jQuery-Bootstrap-LineControl-Editor"
This my div tag on which I have applied the text editor and like this I have 5 more div tags with different id's on which I have used this editor
<div rows="" cols="" class="form-control Editor-editor" type="text" id="achievementresponsiblity" detail="industry" indus="indus" placeholder="Responsibilities And Achievements" name="Responsibility"></div>
when I am trying to save the content or text written/entered in these divs it's not saving any data. I mean it's not taking the value written in it. Json that I have created for it is as follows
$("#Projectssave").click(function () {
var remarks = 0;
jsondata = "";
if ($('[type="checkbox"][industry="project"]').prop("checked") == true) {
remarks = 1;
}
jsondata += "'ProjectTypeId':'5',"
jsondata += "'Remark':'" + remarks + "',"
jsondata += "'Responsibility':'" + $("#achievementresponsiblity").text().replace(/'/g, "&apos;").replace(/"/g, "&Double;").replace(/</g, "<").replace(/>/g, "&tg;").replace(/\\/g, """) + "',";
$.each($('input[detail="Projects"][type="text"],input[detail="Projects"][type="number"],textarea[detail="Projects"],select[detail="Projects"]'), function () {
jsondata += "'" + $(this).attr('name') + "':'" + $(this).val().replace(/'/g, "&apos;").replace(/"/g, "&Double;").replace(/</g, "<").replace(/>/g, "&tg;").replace(/\\/g, """) + "',";
});
jsondata = jsondata.substr(0, jsondata.length - 1);
jsondata = '{' + jsondata + '}';
saveindustrlial(jsondata, $(this).attr("savetype"), "Projects Details");
});
but it just save null data in it. I don't know how to deal with it I am done with trying almost everything.
You can find some documentation about the LineControl editor here: https://github.com/suyati/line-control
To get the text from the editor:
$("#achievementresponsiblity").Editor("getText");
To set the text in the editor:
$("#achievementresponsiblity").Editor("setText", "Your text value");

Dynamically generated html, document.getElementByID returns null

I am generating an html table dynamically in my code behind file
protected void PopulateMemberTable()
{
var guid = "";
string[] selectedColumns = new[] { "MEMBID", "MEMBER_NAME", "BIRTH", "IPA", "HPNAME" };
if (Session["guid"] != null)
guid = Session["guid"].ToString();
StringBuilder html = new StringBuilder();
DataTable dt = MemberSearch(guid, membFirst.Text.ToString(), membLast.Text.ToString(), membDob.Text.ToString(), membId.Text.ToString());
if (dt != null)
{
DataTable new_dt = new DataView(dt).ToTable(false, selectedColumns);
html.Append("<table class='table table-hover data-table'>");
html.Append("<thead>");
html.Append("<tr>");
foreach (DataColumn column in new_dt.Columns)
{
html.Append("<th>");
switch(column.ColumnName.ToString())
{
case "MEMBID":
html.Append("Member ID");
break;
case "MEMBER_NAME":
html.Append("Member Name");
break;
case "BIRTH":
html.Append("DOB");
break;
case "IPA":
html.Append("IPA");
break;
case "HPNAME":
html.Append("Health Plan");
break;
}
html.Append("</th>");
}
//btn column (no header)
html.Append("<th></th>");
html.Append("</tr>");
html.Append("</thead>");
html.Append("<tbody>");
var counter = 0;
foreach (DataRow row in new_dt.Rows)
{
counter++;
string btnId = "\"" + "<%btnMembGrid" + counter.ToString() + ".ClientId%>" + "\"";
html.Append("<tr onclick='document.getElementById(" + btnId + ").click()'>");
var btnValue = new StringBuilder();
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
html.Append("<td><asp:button runat='server' OnClick='selectMember' CssClass='btn btn-default' style='display:none' value = '"
+ btnValue.ToString() + "' id= 'btnMembGrid" + counter.ToString() + "'/></td>");
html.Append("</tr>");
}
html.Append("</tbody>");
html.Append("</table>");
}
else
html.Append("<div class='alert alert-danger' role='alert'>No Members Found</div>");
membTable.Controls.Add(new Literal { Text = html.ToString() });
}
The table is generated just fine, but now I am trying to call some server side code when a row is clicked
foreach (DataRow row in new_dt.Rows)
{
counter++;
string btnId = "\"" + "<%btnMembGrid" + counter.ToString() + ".ClientId%>" + "\"";
html.Append("<tr onclick='document.getElementById(" + btnId + ").click()'>");
var btnValue = new StringBuilder();
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
html.Append("<td><asp:button runat='server' OnClick='selectMember' CssClass='btn btn-default' style='display:none' value = '"
+ btnValue.ToString() + "' id= 'btnMembGrid" + counter.ToString() + "'/></td>");
html.Append("</tr>");
}
I attempted to accomplish this task by placing a hidden <asp:Button/> in each row and then adding a corresponding onclick attribute to each <tr> tag
This is how the generated html looks like in the dev console
However when I attempt to click the row I get the following error message
I am having a hard time understanding what exactly I'm doing wrong. I'd appreciate some input, or possibly even an alternative approach.
You can use jquery and use the delegation model to handle click on dynamic elements. if for example you have some html like
<div id="dynamicname'></div>
then use
the jquery code snippet
$(document).on('click','#dynamicname',function(){
//handle your event here
});
dynamic html should always be handled by delegation model. And you can use
var dynamic_name="#"+getYourDynamicRowName;//variable for dynamic id's of dynamic html element
$(document).on('click',dynamic_name,function(){
//handle your event here
});
As per my experience we can not use asp tag while you are creating dynamic HTML.
If you see your code of dev console you can see that controls are not rendered properly..rendered with asp tag..
To achieve it you can use javascript/Jquery to call server side function.
<input type="button" ID="btn" runat="server" onclick="fn();" />
And in your javascript:
fn = function(){
__doPostBack("<%=btn.ClientID%>", "");
}
And in your code:
`
protected override void btnEvent(IPostBackEventHandler source, string eventArgument)
{
//call the button event
//base.btnEvent(source, eventArgument);
if (source == btn)
{
//do some logic
}
}
After figuring out that passing an <asp:button/> as a string wasn't going to work, I took an alternative approach.
In populateMemberTable()I added an href attribute to the first column in each row
var href = true;
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
if (href)
{
href = false;
html.Append("<a href='/default.aspx?guid=" + Session["guid"] + "&membid=" + row[column.ColumnName] +"'>");
html.Append(row[column.ColumnName]);
html.Append("</a></td>");
}
else
{
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
}
And then I saved the membId as a session variable in Page_Load()
protected void Page_Load(object sender, EventArgs e)
{
//save guid (http://url.com?guid=xxxxxx) as session variable
Session["guid"] = Request.QueryString["guid"];
var membId = Request.QueryString["membid"];
if (membId != null)
{
Session["membid"] = membId;
}
}
It might not be the most elegant solution, but it got me what I needed and was straightforward to implement. Thanks for the input everyone!

How to get the value of id of innerHTML?

I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here

How do you dynamically create a radio button in Javascript that works in all browsers?

Dynamically creating a radio button using eg
var radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
works in Firefox but not in IE. Why not?
Taking a step from what Patrick suggests, using a temporary node we can get rid of the try/catch:
function createRadioElement(name, checked) {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
Based on this post and its comments:
http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html
the following works. Apparently the problem is that you can't dynamically set the name property in IE. I also found that you can't dynamically set the checked attribute either.
function createRadioElement( name, checked ) {
var radioInput;
try {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
if ( checked ) {
radioInput.setAttribute('checked', 'checked');
}
}
return radioInput;
}
Here's an example of more general solution which detects IE up front and handles other attributes IE also has problems with, extracted from DOMBuilder:
var createElement = (function()
{
// Detect IE using conditional compilation
if (/*#cc_on #*//*#if (#_win32)!/*#end #*/false)
{
// Translations for attribute names which IE would otherwise choke on
var attrTranslations =
{
"class": "className",
"for": "htmlFor"
};
var setAttribute = function(element, attr, value)
{
if (attrTranslations.hasOwnProperty(attr))
{
element[attrTranslations[attr]] = value;
}
else if (attr == "style")
{
element.style.cssText = value;
}
else
{
element.setAttribute(attr, value);
}
};
return function(tagName, attributes)
{
attributes = attributes || {};
// See http://channel9.msdn.com/Wiki/InternetExplorerProgrammingBugs
if (attributes.hasOwnProperty("name") ||
attributes.hasOwnProperty("checked") ||
attributes.hasOwnProperty("multiple"))
{
var tagParts = ["<" + tagName];
if (attributes.hasOwnProperty("name"))
{
tagParts[tagParts.length] =
' name="' + attributes.name + '"';
delete attributes.name;
}
if (attributes.hasOwnProperty("checked") &&
"" + attributes.checked == "true")
{
tagParts[tagParts.length] = " checked";
delete attributes.checked;
}
if (attributes.hasOwnProperty("multiple") &&
"" + attributes.multiple == "true")
{
tagParts[tagParts.length] = " multiple";
delete attributes.multiple;
}
tagParts[tagParts.length] = ">";
var element =
document.createElement(tagParts.join(""));
}
else
{
var element = document.createElement(tagName);
}
for (var attr in attributes)
{
if (attributes.hasOwnProperty(attr))
{
setAttribute(element, attr, attributes[attr]);
}
}
return element;
};
}
// All other browsers
else
{
return function(tagName, attributes)
{
attributes = attributes || {};
var element = document.createElement(tagName);
for (var attr in attributes)
{
if (attributes.hasOwnProperty(attr))
{
element.setAttribute(attr, attributes[attr]);
}
}
return element;
};
}
})();
// Usage
var rb = createElement("input", {type: "radio", checked: true});
The full DOMBuilder version also handles event listener registration and specification of child nodes.
Personally I wouldn't create nodes myself. As you've noticed there are just too many browser specific problems. Normally I use Builder.node from script.aculo.us. Using this your code would become something like this:
Builder.node('input', {type: 'radio', name: name})
My solution:
html
head
script(type='text/javascript')
function createRadioButton()
{
var newRadioButton
= document.createElement(input(type='radio',name='radio',value='1st'));
document.body.insertBefore(newRadioButton);
}
body
input(type='button',onclick='createRadioButton();',value='Create Radio Button')
Dynamically created radio button in javascript:
<%# Page Language=”C#” AutoEventWireup=”true” CodeBehind=”RadioDemo.aspx.cs” Inherits=”JavascriptTutorial.RadioDemo” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
<script type=”text/javascript”>
/* Getting Id of Div in which radio button will be add*/
var containerDivClientId = “<%= containerDiv.ClientID %>”;
/*variable count uses for define unique Ids of radio buttons and group name*/
var count = 100;
/*This function call by button OnClientClick event and uses for create radio buttons*/
function dynamicRadioButton()
{
/* create a radio button */
var radioYes = document.createElement(“input”);
radioYes.setAttribute(“type”, “radio”);
/*Set id of new created radio button*/
radioYes.setAttribute(“id”, “radioYes” + count);
/*set unique group name for pair of Yes / No */
radioYes.setAttribute(“name”, “Boolean” + count);
/*creating label for Text to Radio button*/
var lblYes = document.createElement(“lable”);
/*create text node for label Text which display for Radio button*/
var textYes = document.createTextNode(“Yes”);
/*add text to new create lable*/
lblYes.appendChild(textYes);
/*add radio button to Div*/
containerDiv.appendChild(radioYes);
/*add label text for radio button to Div*/
containerDiv.appendChild(lblYes);
/*add space between two radio buttons*/
var space = document.createElement(“span”);
space.setAttribute(“innerHTML”, “ &nbsp”);
containerDiv.appendChild(space);
var radioNo = document.createElement(“input”);
radioNo.setAttribute(“type”, “radio”);
radioNo.setAttribute(“id”, “radioNo” + count);
radioNo.setAttribute(“name”, “Boolean” + count);
var lblNo = document.createElement(“label”);
lblNo.innerHTML = “No”;
containerDiv.appendChild(radioNo);
containerDiv.appendChild(lblNo);
/*add new line for new pair of radio buttons*/
var spaceBr= document.createElement(“br”);
containerDiv.appendChild(spaceBr);
count++;
return false;
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Button ID=”btnCreate” runat=”server” Text=”Click Me” OnClientClick=”return dynamicRadioButton();” />
<div id=”containerDiv” runat=”server”></div>
</div>
</form>
</body>
</html>
(source)
for(i=0;i<=10;i++){
var selecttag1=document.createElement("input");
selecttag1.setAttribute("type", "radio");
selecttag1.setAttribute("name", "irrSelectNo"+i);
selecttag1.setAttribute("value", "N");
selecttag1.setAttribute("id","irrSelectNo"+i);
var lbl1 = document.createElement("label");
lbl1.innerHTML = "YES";
cell3Div.appendChild(lbl);
cell3Div.appendChild(selecttag1);
}
Quick reply to an older post:
The post above by Roundcrisis is fine, IF AND ONLY IF, you know the number of radio/checkbox controls that will be used before-hand. In some situations, addressed by this topic of 'dynamically creating radio buttons', the number of controls that will be needed by the user is not known. Further, I do not recommend 'skipping' the 'try-catch' error trapping, as this allows for ease of catching future browser implementations which may not comply with the current standards. Of these solutions, I recommend using the solution proposed by Patrick Wilkes in his reply to his own question.
This is repeated here in an effort to avoid confusion:
function createRadioElement( name, checked ) {
var radioInput;
try {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', name);
if ( checked ) {
radioInput.setAttribute('checked', 'checked');
}
}
return radioInput;}
Patrick's answer works, or you can set the "defaultChecked" attribute too (this will work in IE for radio or checkbox elements, and won't cause errors in other browsers.
PS Full list of attributes you can't set in IE is listed here:
http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html
why not creating the input, set the style to dispaly: none and then change the display when necesary
this way you can also probably handle users whitout js better.
My suggestion is not to use document.Create(). Better solution is to construct actual HTML of future control and then assign it like innerHTML to some placeholder - it allows browser to render it itself which is much faster than any JS DOM manipulations.
Cheers.

Categories

Resources