Get innerHTML value from dynamically generated textbox (in javascript) - javascript

I'm using JavaScript to dynamically generate a dialogue box (it's a div element), containing a textbox and a submit button. I plan on submitting the value in the textbox to another page using AJAX.
My problem is that I can generate my textbox just fine, but I can't get the value from it. innerHTML comes back blank every time. I'm not sure what I'm doing wrong.
// Generate dialogue box using div
function create_div_dynamic()
{
//Create the div element
dv = document.createElement('div');
//unique tags
var unique_div_id = 'mydiv' + Math.random() * .3245;
var unique_textbox_id = 'mytext' + Math.random() * .3245;
//Set div id
dv.setAttribute('id',unique_div_id);
//Set div style
dv.style.position = 'absolute';
dv.style.left = '100 px';
dv.style.top = '100 px';
dv.style.width = '500px';
dv.style.height = '100px';
dv.style.padding = '7px';
dv.style.backgroundColor = '#fdfdf1';
dv.style.border = '1px solid #CCCCCC';
dv.style.fontFamily = 'Trebuchet MS';
dv.style.fontSize = '13px';
//Create textbox element
txt = document.createElement('input');
txt.setAttribute('id',unique_textbox_id);
txt.setAttribute('type','text');
txt.style.marginRight = '10px';
//Add textbox element to div
dv.appendChild(txt)
//Add the div to the document
document.body.appendChild(dv);
dv.innerHTML += '<input type="button" id="mysubmit" value="Read Textbox" onclick="javascript:alert(\'' + document.getElementById(unique_textbox_id).innerHTML + '\');" />';
}

Textarea elements don't have an innerHTML property. Just read the value property like you would with any other form element.
document.getElementById(unique_textbox_id).value

The input type="text" fields have no innerHTML, they are usually represented as self-closing tags.
Use the value attribute instead:
document.getElementById(unique_textbox_id).value

I have to create the div element, add it to the document, and THEN add the children (textbox and submit button).
No, you don't in general have to do that. What was causing your problem was this:
...'onclick="javascript:alert(\'' + document.getElementById(unique_textbox_id).innerHTML + '\');" />';
That access to document.getElementById().innerHTML is occurring at the time you create the string, that is during the execution of create_div_dynamic(), not when the button is pressed. At that point, the field has just been created and has no .value. (It also has no .innerHTML, but then it never will as it's an input element.)
Your revised code uses a proper JavaScript function which is called at onclick time, and fixes the property to value, so that's OK. This approach also doesn't die when there are apostrophes or backslashes in the value string.
dv.innerHTML += '<input ...
This serialises all the content in ‘dv’ to HTML text, then adds the string, and parses all the HTML back into DOM objects. This is really inefficient, and in the process you lose all JavaScript properties on the object, including event handlers and listeners.
“innerHTML+=” is always a mistake. Never use it.
txt.setAttribute('id',unique_textbox_id);
Don't use setAttribute(), it doesn't work for certain attributes under IE. Instead use the more readable DOM-HTML properties:
txt.type= 'text';
txt.id= unique_textbox_id;

For others in my boat, I want to show the solution. It turns out that I was adding elements in the wrong order.
I have to create the div element, add it to the document, and THEN add the children (textbox and submit button).
//DIV
dv = document.createElement('div');
dv.setAttribute('id',unique_div_id);
dv.style.position = 'absolute';
dv.style.left = xx + 'px';
dv.style.top = yy + 'px';
dv.style.width = '500px';
dv.style.height = '20px';
dv.style.padding = '7px';
dv.style.backgroundColor = '#fdfdf1';
dv.style.border = '1px solid #CCCCCC';
dv.style.fontFamily = 'Trebuchet MS';
dv.style.fontSize = '13px';
//Add div element to body
document.body.appendChild(dv);
//TEXTBOX
txt = document.createElement('input');
txt.setAttribute('id',unique_textbox_id);
txt.setAttribute('type','text');
txt.style.marginRight = '10px';
//Add textbox to div element
document.getElementById('mydiv').appendChild(txt);
var sbt = document.createElement('input');
sbt.setAttribute('id','mysubmit');
sbt.setAttribute('type','submit');
sbt.setAttribute('value','GO');
sbt.onclick = function() { alert(document.getElementById('mytext').value); };
//Add submit to div element
document.getElementById('mydiv').appendChild(sbt);
Once this is done, and I use the .value, all goes well.

$cid =$_REQUEST['cid'];
$name =addslashes($_REQUEST['name']);
$email =$_REQUEST['email'];
$comments =$_REQUEST['comments'];
$comment_type=$_REQUEST['type'];
$gstatus =(isset($_REQUEST['gstatus'])) ? $_REQUEST['gstatus'] : 'no';
$user_type =(!empty($_SESSION['user_id'])) ? 'author' : 'user';

Related

How to hide the RESET button from a record through DOM?

Can anyone tell me how to hide the RESET button using DOM?
I am trying to make a uservent script with beforeLoad function that will hide/remove RESET button from a record.
I found a solution:
var form = ctx.form;
var field = form.addField({
id: 'custpage_code',
type: 'inlinehtml',
label: 'Code'
});
field.defaultValue = '<script>' +
'document.getElementById("resetter").style.display = "none";' +
'document.getElementById("tdbody_resetter").style.display = "none";' +// removed the extra line along the button
'</script>';
The other alternative is JQuery which is already pre-loaded in NS.
var hideFld = context.form.addField({
id:'custpage_hide_buttons',
label:'not shown - hidden',
type: serverWidget.FieldType.INLINEHTML
});
var scr = "";
scr += 'jQuery("#tbl_resetter").hide();';
scr += 'jQuery("#print").hide();';
hideFld.defaultValue = "<script>jQuery(function($){require([], function(){" + scr + ";})})</script>"
You can hide almost any element with this. Just search the page source for the element ID:
The "Reset" button's element is usually a table with the ID tbl_resetter. Add multiple elements easily as above.

javascript checkbox event listener breaks if containing innerHTML is changed

I am trying to create checkboxes and insert a blank line after each one. When the checkbox is changed, I want to execute a function.
My code:
var div = document.getElementById("test");
var cb1 = document.createElement('input');
cb1.id = "cb_test1";
cb1.type = "checkbox";
cb1.defaultChecked = true;
cb1.onchange = function(){alert("hi")};
div.appendChild(cb1);
div.innerHTML += "box1<br/>";
var cb2 = document.createElement('input');
cb2.id = "cb_test1";
cb2.type = "checkbox";
cb2.defaultChecked = true;
cb2.onchange = function(){alert("hi")};
div.appendChild(cb2);
div.innerHTML += "box2<br/>";
The problem is, setting the innerHTML of the containing DIV seems to erase the event listener, so when the onchange event is fired, nothing happens.
How can I modify the innerHTML to add text and a new line without losing the event handler?
My actual code is much more dynamic and done in a loop, but the issue of the event handler getting dropped can be duplicated with the above code.
Whenever you assign (or concatenate) an innerHTML property of a container, any listeners inside that container that were attached via Javascript will be corrupted. If you want to insert HTML strings, use insertAdjacentHTML instead:
document.querySelector('#child').onclick = () => console.log('child');
document.querySelector('#container').insertAdjacentHTML('beforeend', '<div>newchild</div>');
<div id="container">
<div id="child">
child
</div>
</div>
But it would generally be better to create and append elements explicitly rather than insert strings of HTML markup that then get parsed into elements. For example, instead of
div.innerHTML += "box1<br/>";
you could
div.appendChild(document.createTextNode('box1');
div.appendChild(document.createElement('br');
const div = document.querySelector('div');
div.appendChild(document.createTextNode('box1'));
div.appendChild(document.createElement('br'));
<div>
content
</div>

On search/highlight click -> existing div becomes wrapped with existing span

I have a problem with javascript search and highlight text.
For example, there is existing span element and existing div element.
Problem is that if I click on search button for some reason div element becomes a child of span element.
To explain it better I have created JS fiddle to show the problem:
function highlightSearch() {
$('span').removeClass('highlighted');
var text = document.getElementById('query').value;
var query = new RegExp("(\\b" + text + "\\b(?!([^<]+)?>))", "gim");
var e = document.getElementById("searchText").innerHTML;
var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
document.getElementById("searchText").innerHTML = enew;
var newe = enew.replace(query, "<span class='highlighted'>$1</span>");
document.getElementById("searchText").innerHTML = newe;
}
Check problem on : JSfiddle
Well, you are removing all </span> tags from the innerHTML in this line:
var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
And therefore also the </span> of .glyphicon. This is why the element becomes wrapped.
Btw: An exception is thrown: ReferenceError: highlightSearch is not defined

how to dynamically add input elements one below the other in javascript

I have following code. The input textboxes are getting generated. Only the thing is i wanted them to be added one below the other. Here is my code:
$('.pl').on('click',function(){
var hiddenInput = document.createElement("input");
var hiddenButton = document.createElement("button");
var hiddenTextNode = document.createTextNode("Delete");
$(this).after(hiddenInput);
hiddenButton.appendChild(hiddenTextNode);
$(this).after(hiddenButton);
$(this).write("<p>hi</p>");
c=c+1;
document.getElementById("h").value = c;
hiddenInput.name = 'text'+c;
hiddenInput.class = 'form-control add-polls-container';
hiddenInput.placeholder = 'Enter Poll Option';
});
you just refer
jQuery find last input and append
$(this).after(hiddenInput); Here $(this) means click bind element so its append textbox to click element

Javascript Custom Alert Box with Image alignment

I Have created Custom Alert Box in Javascript . I Have added text with images. but It is not align proberly. It came some thing like this.
I am trying to add the correct mark and text with same line, how can I achieve this. can anyone please help me. I have added my Custom alert box Function below.
function createCustomAlert(txt, string_url,fd) {
// shortcut reference to the document object
d = document;
// if the modalContainer object already exists in the DOM, bail out.
if (d.getElementById("modalContainer")) return;
// create the modalContainer div as a child of the BODY element
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "modalContainer";
// make sure its as tall as it needs to be to overlay all the content on the page
mObj.style.height = document.documentElement.scrollHeight + "px";
// create the DIV that will be the alert
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "alertBox";
// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
if (d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
// center the alert box
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth) / 2 + "px";
// create an H1 element as the title bar
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
btn2 = alertObj.appendChild(d.createElement("img"));
btn2.id = "fd";
btn2.src = fd;
// create a paragraph element to contain the txt argument
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = txt;
// create an anchor element to use as the confirmation button.
//btn = alertObj.appendChild(d.createElement("a"));
//btn.id = "closeBtn";
//btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
//btn.href = "";
btn = alertObj.appendChild(d.createElement("img"));
btn.id = "closeBtn";
btn.src = 'new-go-next2.png';
btn.href="#ss";
//btn.height="30px";
//btn.width="30px";
//btn.href="#";
// set up the onclick event to remove the alert when the anchor is clicked
btn.onclick = function () { removeCustomAlert(); window.location = string_url; return false; }
}
well yes creating a table would be a great approach to solve your problems , btw u can also try some internal divs with proper position anf the element having correct float attribute
Rather creating div element create table with two Columns. First of which will contain 'Image' for OK and Second one will contain your 'Text'.
Check if this helps.

Categories

Resources