I have a Spring MVC application where I am required to capture a variable number of key value pairs based on user input. The HTML & JS part of the code to render the controls is as follows :
<tr>
<td><label>Attributes (Names & Value(s))</label></td>
<td><input id="Button1" type="button" value="Add" onclick="Button1_onclick()"/></td>
</tr>
<script language="javascript" type="text/javascript">
var NumOfRow = 1;
var attribs = {};
function Button1_onclick() {
NumOfRow++;
// get the reference of the main Div
var mainDiv = document.getElementById('MainDiv');
// create new div that will work as a container
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'innerDiv' + NumOfRow);
//create span to contain the text
var newSpan = document.createElement('span');
newSpan.innerHTML = "Attribute Type";
// create new textbox for type entry
var newTextBox = document.createElement('input');
newTextBox.type = 'text';
newTextBox.setAttribute('id', 'DimensionType' + NumOfRow);
//create span to contain the text
var newSpan2 = document.createElement('span');
newSpan2.innerHTML = "Attribute Value(s)";
// create new textbox for value entry
var newTextBox2 = document.createElement('input');
newTextBox2.type = 'text';
newTextBox2.setAttribute('id', 'DimensionValue' + NumOfRow);
// create remove button for each attribute
var newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = 'Remove';
newButton.id = 'btn' + NumOfRow;
// attach event for remove button click
newButton.onclick = function RemoveEntry() {
var mainDiv = document.getElementById('MainDiv');
mainDiv.removeChild(this.parentNode);
NumOfRow--;
}
// append the span, textbox and the button
newDiv.appendChild(newSpan);
newDiv.appendChild(newTextBox);
newDiv.appendChild(newSpan2);
newDiv.appendChild(newTextBox2);
newDiv.appendChild(newButton);
// finally append the new div to the main div
mainDiv.appendChild(newDiv);
}
}
</script>
I am not sure how to send this captured data back to my controller when the form is submitted. Please advise. Also if there is a better way to capture such data, those suggestions are most welcome as well.
What about making Capture key event in a text field you can do this :
<html>
<head>
<script language="JavaScript" type = "text/javascript">
<!--
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event)
{
if (document.all) //Checks for IE 4.0 or later
{
document.form1.text2.value = String.fromCharCode(event.keyCode);
}
else if (document.getElementById) //checks for Netscape 6 or later
{
document.form1.text2.value = String.fromCharCode(key_event.which);
}
else if (document.layers) //Checks for Netscape 4
{
document.form1.text2.value = String.fromCharCode(key_event.which);
}
}
//-->
</script>
<title>Capture Key Pressed</title>
</head>
<body>
<form name="form1">
<b>Type value in field: See what you typed:</b><br>
<input type = "text" name = "text1" onKeyPress="DisplayMsg(event)" size="20">
<input type = "text" name = "text2" onKeyPress="DisplayMsg(event)" size="20">
</form>
</body>
</html>
Related
I am generating some input fields dynamically on my page, and I want to grab inputs from them to store in localStorage if this way works if not? suggest a way around, how can this be done? also how can i add a event listener to submit button ? followings are code have a look at it and give some suggestions/improvisations.
..
HTML
<div id="warnMessage"></div>
<div class="add"></div>
<div class="inputs">
<input
type="text"
maxlength="1"
id="inputValue"
/>
<button class="btn" type="button">+</button>
</div>
javascript
const div = document.querySelector(".add");
const add = document
.querySelector(".btn")
.addEventListener("click", addingInps);
function addingInps() {
const inputValue = parseInt(document.getElementById("inputValue").value);
if (isNaN(inputValue)) {
document.getElementById("warnMessage").innerText = "Enter Again";
document.getElementById("inputValue").value = "";
} else {
const form = document.createElement("form");
form.method = "post";
form.action = "#";
for (let i = 0; i < inputValue; i++) {
const inp = document.createElement("input");
inp.type = "text";
inp.maxLength = "12";
inp.required = true;
inp.className = "inp";
const br = document.createElement("br");
form.appendChild(br.cloneNode());
form.appendChild(inp);
form.appendChild(br.cloneNode());
div.appendChild(form);
document.querySelector("#inputValue").style.display = "none";
}
const sub = document.createElement("button");
sub.className = "subButton";
sub.type = "button";
sub.value = "button";
sub.textContent = "Submit"
form.appendChild(sub);
}
}
You are loop through an input ...not an array or nodelist.
It cant work
I think it would be easier if you appended an ID with every new input field you made
for(let i=0;i < inputValue;i++){
// create your element ipt
ipt.setAttribute("id","autogenerated_" + i);
}
and grab value based on id
document.getElementById("autogenerated_x").value();
about setting an event listener, I can't think any other way of the classic
btn.addEventListener("click", function(e){
// your functionality
});
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 3 years ago.
I have the following HTML written. The idea is that I can add items to the list at the top, and then generate a field which includes a name, checkbox, and text field. The text field is to be enabled/disabled depending on the checkbox. In my javascript, the toggle function is assigned to the onclick attribute of the checkbox field, but it only works on the last item on the list. Can anyone tell why this functionality isn't being assigned to all the checkboxes? If you open the resulting html code in a browser, it shows no onclick events for any checkboxes except the last one, so it appears it isn't being added. Does it somehow get removed from the previous one when I assign it to the next? How would I fix it? Thank you.
<!DOCTYPE html>
<html>
<body onload="loadAllSettings()" }>
<script>
var genOptFields = ["genField1", "genField2"];
function loadAllSettings() {
loadSettingsList("genSet", genOptFields);
}
</script>
<h2>Options</h2>
<form>
<fieldset id="genSet">
<legend>General</legend>
</fieldset>
</form>
<script>
function loadSettingsList(parentId, optionalFields) {
var fieldset = document.getElementById(parentId);
for (fieldId of optionalFields) {
var p = document.createElement('p');
p.append(fieldId + ":");
var input = document.createElement('input');
input.type = "text";
input.disabled = true;
input.id = fieldId;
var cb = document.createElement('input');
cb.type = "checkbox";
cb.id = "cb_" + fieldId;
cb.addEventListener("click", function () {
toggleCheck(fieldId);
});
p.appendChild(cb);
p.appendChild(input);
fieldset.appendChild(p);
}
}
function toggleCheck(fieldId) {
document.getElementById(fieldId).disabled = !document.getElementById("cb_" +
fieldId).checked;
}
</script>
</body>
</html>
As explained below, your fieldId reference isnt static. As a result when calling toggle check it was always passing the last value that fieldId contained no matter what (double check this by console.logging your fieldId passed to toggle check)
function loadAllSettings() {
const genOptFields = ["genField1", "genField2"];
loadSettingsList("genSet", genOptFields);
}
function loadSettingsList(parentId, optionalFields) {
const fieldset = document.getElementById(parentId);
optionalFields.forEach(function (fieldId) {
createParagraph(fieldId, fieldset);
});
}
function createParagraph(fieldId, fieldset) {
const p = document.createElement('p');
p.append(fieldId + ":");
createCheckbox(p, fieldId);
createInputField(p, fieldId);
fieldset.appendChild(p);
}
function createInputField(p, fieldId) {
const input = document.createElement('input');
input.type = "text";
input.disabled = true;
input.id = fieldId;
p.appendChild(input);
}
function createCheckbox(p, fieldId) {
const cb = document.createElement('input');
cb.type = "checkbox";
cb.id = "cb_" + fieldId;
//set this attribute to capture value
cb.setAttribute('data-fieldId', fieldId);
cb.addEventListener("click", function () {
//use static data attribute value instead of fieldId var which isnt static
toggleCheck(this.getAttribute('data-fieldId'));
});
p.appendChild(cb);
}
function toggleCheck(fieldId) {
document.getElementById(fieldId).disabled = !document.getElementById("cb_" + fieldId).checked;
}
<!DOCTYPE html>
<html>
<body onload="loadAllSettings()" }>
<h2>Options</h2>
<form>
<fieldset id="genSet">
<legend>General</legend>
</fieldset>
</form>
</body>
</html>
Since you are generating the element using body on-load event, click event become static. That is why element is always pointing to the last child. You can simply achieve your requirement by passing element scope(this) into the click event.
Here is the working solution:
<body onload="loadAllSettings()" }>
<script>
var genOptFields = ["genField1", "genField2"];
function loadAllSettings() {
loadSettingsList("genSet", genOptFields);
}
</script>
<h2>Options</h2>
<form>
<fieldset id="genSet">
<legend>General</legend>
</fieldset>
</form>
<script>
function loadSettingsList(parentId, optionalFields) {
var fieldset = document.getElementById(parentId);
for (fieldId of optionalFields) {
var p = document.createElement('p');
p.append(fieldId + ":");
var input = document.createElement('input');
input.type = "text";
input.disabled = true;
input.id = fieldId;
var cb = document.createElement('input');
cb.type = "checkbox";
cb.id = "cb_" + fieldId;
cb.addEventListener("click", function () {
toggleCheck(this);
});
p.appendChild(cb);
p.appendChild(input);
fieldset.appendChild(p);
}
}
function toggleCheck(ele) {
ele.nextElementSibling.disabled = !ele.checked;
}
</script>
</body>
I try to generate a text field in a table:
The table gets bigger with the input of the user that's why I cant just write the
input syntax in the html document, because the cell isn´t generated from the beginning.
function tableAdd() {
var table = document.getElementById("table");
var titel = document.getElementById("Titel").value;
var description = document.getElementById("Description").value;
var row = table.insertRow();
var projectCell=row.insertCell(0);
projectCell.innerHTML = titel;
// down here is the problem
var x =row.insertCell(1);
x.innerHTML = document.createElement("INPUT")
x.innerHTML.setAttribute("type", "text");
}
The problem is that x.innerHTML is a string, not a html element. You need to set attribute on html element, not string. You can do like this:
var x =row.insertCell(1);
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
x.appendChild(y);
You are trying to assign a reference of HTMLInputElement which is returned from the call to document.createElement("input"); to the non-existent innerHTML property of a HTMLTableRowElement (newRow in my example) reference, returned by insertCell(1);.
Instead you can assign any text value to the value attribute of the HTMLInputElement(input variable in my example) and append the dynamic input to the newly created cell.
function tableAdd() {
var table = document.getElementById("table");
var titel = document.getElementById("Titel").value;
var description = document.getElementById("Description").value;
var row = table.insertRow();
var projectCell=row.insertCell(0);
projectCell.innerHTML = titel;
var newRow =row.insertCell(1);
var input = document.createElement("input");
input.type = "text";
input.value= description
newRow.appendChild(input);
}
tableAdd();
<body>
<input type="text" id="Titel" value="test"/>
<input type="text" id="Description" value="test"/>
<table id="table">
</table>
<button onclick="tableAdd()">add</button>
</body>
Here is the reference documentation:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/insertCell
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
I want to be able to copy elements with keeping everything that user entered, modified and etc.
I don't want to parse every elem like manually set value for textboxes, manually set checked for radiobuttons and etc, I need some generic way.
Is this possible?
This is what I have as example:
<html>
<head>
<title>asd</title>
<script type = "text/javascript">
function copyElement(elem_id, to_elem_id)
{
var elem = document.getElementById(elem_id);
var container = document.getElementById(to_elem_id);
if (!elem || !container)
return;
container.innerHTML = elem.outerHTML;
}
</script>
</head>
<body>
<input type = "text" id = "test_txt" />
<input type = "button" value = "copy textbox" onclick = "copyElement('test_txt', 'for_elem_paste')" />
<span id = 'for_elem_paste'></span>
</body>
</html>
I want that copied textbox to appear with text entered in original textbox.
But this not about textboxes, I need to copy any elements. I though that innerHTML and outerHTML keep things that modified by user :/
You can clone it
function copyElement(elem_id, to_elem_id) {
var elem = document.getElementById(elem_id);
var container = document.getElementById(to_elem_id);
if (elem && container) {
var clone = elem.cloneNode(true);
clone.id = "some other id to prevent id duplication";
container.appendChild(clone);
}
else return false;
}
I have a dynamic form with a select dropdown, and I want to know what select was changed, however any time that I add a new form and try to change any select the alert is the same: "origen1"
Here is my js code:
<SCRIPT language="javascript">
function addRow(divId) {
count = 0;
count++;
var etiquetas = new Array();
var origenes = new Array();
var parentDiv = document.getElementById(divId);
// create a div dynamically
var eleDiv = document.createElement("div");
eleDiv.setAttribute("name", "olddiv");
eleDiv.setAttribute("id", "olddiv");
// create a label dynamically
var etiqueta = document.createElement("input");
etiqueta.setAttribute("name", 'etiqueta' + count);
etiqueta.setAttribute("value", "etiqueta");
etiqueta.setAttribute('disabled', true);
etiquetas.push(etiqueta);
//create a select dynamically
var myarray=new Array(3)
myarray[0] = "Opt1"
myarray[1] = "Opt2"
myarray[2] = "Opt3"
var origen = document.createElement("select");
origen.setAttribute("name", 'origen' + count);
for (i=0; i<3; i++)
{
opt = document.createElement('option');
opt.value = i;
opt.innerHTML = myarray[i];
origen.appendChild(opt);
}
origen.onchange = function(){testselect(this);};
origenes.push(origen);
// create a delete button dynamically
var eleBtn = document.createElement("input");
eleBtn.setAttribute("type", "button");
eleBtn.setAttribute("value", "delete");
eleBtn.setAttribute("name", "button");
eleBtn.setAttribute("id", "button");
eleBtn.setAttribute("onclick", "deleteRow('button')");
// append new div to parent div
parentDiv.appendChild(eleDiv);
// append textbox & button to new div
eleDiv.appendChild(etiqueta);
eleDiv.appendChild(origen);
eleDiv.appendChild(eleBtn);
}
function testselect(seleccion)
{
alert(seleccion.name);
}
function deleteRow(tableID) {
var div = document.getElementById('olddiv');
if (div) {
div.parentNode.removeChild(div);
}
}
</SCRIPT>
And the html:
<form name="objForm" action="test1.php">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<div id="dataTable" width="350px">
</div>
<input type="submit" value="Submit"/>
</form>
Try inspecting the drop down using firebug. With that you might be able to get the name and ID of the selected drop down but remember the selected drop down has to be selected using firebug in order to see the ID or name used with it.
Since this is JS and the drop down is not selected properly you might not see the name or id used.
So make sure to it is properly selected