Populate multiple fields with javascript - javascript

I am new to javascript and I can't populate many fields with one click.
<script>
function addTxt(txt, field)
{
var myTxt = txt;
var id = field;
document.getElementById(id).value = myTxt;
}
</script>
<input type="text" name="xx" id="info" autofocus="required">
<p>x</p>
I've got 3 more fields.
Thanks.

You can use
function addTxt(txt, ids)
{
for (var i=0, l=ids.length; i<l; ++i) {
document.getElementById(ids[i]).value = txt;
}
}
And call it like
addTxt('Some text', ['id1', 'id2', 'id3']);

You can populate multiple fields. I have shared a jsfiddle link. You can populate multiple fields using this code.
function addTxt(_val, _id,_no)
{
var _myTxt = _val;
var _id = _id;
for(var i=1;i<=_no;i++){
document.getElementById(_id+i).value = _myTxt;
}
}
Click here to see DEMO

I think you don't need a function to do this.
Just use
document.getElementById('id1').value
= document.getElementById('id2').value
= document.getElementById('id3').value
= 'Some text';
Or, if you think document.getElementById is too long, use a shortcut:
var get = document.getElementById;
/* ... */
get('id1').value = get('id2').value = get('id3').value = 'Some text';

Try getting the elements by tagName or by className instead of by id, then using a for loop to iterate through each one.

Related

How do I get the id of a element in a form?

I need to get the id of an element within a form so I can tag the element as "false" or "true". Or, alternately, I need a way to associate a name with an element that can I pull in javascipt so I can change the associated value.
var form = document.getElementById("myForm");
form.elements[i].value
Those lines of code is what I tried but it doesn't seem to work.
Edit:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm").elements;
for(var i = 0; i < 1 ; i++){
var id = form.elements[i].id;
sessionStorage.setItem(id,"false");
}
localStorage.setItem("run", true);
}
}
So basically when I run the page, I want a localStorage item attached to all the buttons on the screen. I want this to run once so I can set all the items to false. Problem is I don't know how to get the ids so I have a value to attach to the button. Any idea of how to accomplish a task like this.
Edit2:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm");
var tot = document.getElementById("myForm").length;
for(var i = 0; i < tot ; i++){
sessionStorage.setItem(form.elements[i].id,"false");
}
localStorage.setItem("run", true);
}
}
This is the new code. It mostly seems to work but for some reason only the first value is getting set to false. Or maybe it has to do with this function, I'm not sure.
function loader(){
var form = document.getElementById("myForm");
var tot = 5;
for(var i = 0; i < 5 ; i++){
if(sessionStorage.getItem(form.elements[i].id) === "true"){
document.getElementById(form.elements[i].id).style.backgroundColor = "green";
return ;
}else{
document.getElementById(form.elements[i].id).style.backgroundColor = "red";
return false;
}
}
}
Anyways, I'm running both of these at the same time when the page is executed so they are all set to false and turn red. But when a button is properly completed, the color of the button turns green.
It's available via the id property on the element:
var id = form.elements[i].id;
More on MDN and in the spec.
Live Example:
var form = document.getElementById("myForm");
console.log("The id is: " + form.elements[0].id);
<form id="myForm">
<input type="text" id="theText">
</form>
You're already storing all the elements in the form so it must be :
var form = document.getElementById("myForm").elements;
var id = form[i].id;
Or remove the elements part from the form variable like :
var form = document.getElementById("myForm");
var id = form.elements[i].id;

Append List of <select> Elements

I am trying to create a button that calls a function which creates new list items with selection boxes. The code below create a select element however, the button disappears and it doesn't create one list item after another. Any idea how I can persist the button and add one select element after another?
<button type="button" onclick="createTable()">Add Item</button>
function createTable()
{
var itemName = "Selections: ";
document.write(itemName);
for (var i=0;i<7;i++)
{
var myTable = " ";
myTable+="<select name='test' id='mySelect"+i+"' style='font-size:10px' onchange='Calculate()'>";
myTable+="<option value='zeroPoint'>0</option>";
myTable+="<option value='halfPoint'>1/2</option>";
myTable+="<option value='onePoint'>1</option>";
myTable+="</select>";
document.write(myTable);
}
}
I made some changes to the documnet.write way you have. However, I would strongly recommend dynamically creating html dom nodes. I added another method, createTable2, which does the required. It will also be easier for you to preserve the html content you have, which can be easily written over with document.write way.
Edit:
I added one more method, createTable2, to allow adding multiple selects. There is a model you can pass in with the select and option information you have. There is a flag, empty, which is set to true if you would like to empty the div before adding new selects; i.e. createTable3(true).
function createTable()
{
var itemName = "Selections: ";
var selectElement = document.getElementById("render");
for (var i=0;i<7;i++)
{
var myTable = " ";
myTable+="<select name='test' id='mySelect"+i+"' style='font-size:10px' onchange='Calculate()'>";
myTable+="<option value='zeroPoint'>0</option>";
myTable+="<option value='halfPoint'>1/2</option>";
myTable+="<option value='onePoint'>1</option>";
myTable+="</select>";
selectElement.innerHTML = myTable;
}
}
function createTable2(){
var myDiv = document.getElementById("render");
//Create array of options to be added
var array = ["zeroPoint","halfPoint","onePoint"];
var texts = ["1","1/2","1"];
var selectList = document.createElement("select");
selectList.id = "mySelect";
selectList.style.fontSize = "10px";
selectList.onChange = 'Calculate()';
myDiv.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = texts[i];
selectList.appendChild(option);
}
}
function createTable3(empty){
var myDiv = document.getElementById("render");
if(empty){
myDiv.innerHTML = "";
}
let model = {
"select1": [{value: "zeroPoint", label: "1"},
{value: "halfPoint", label: "1/2"},
{value: "onePoint", label: "1"}],
"select2": [{value: "zeroPoint1", label: "11"},
{value: "halfPoint1", label: "11/22"},
{value: "onePoint1", label: "11"}]
};
Object.keys(model).forEach(function(key){
let entry = model[key];
var selectList = document.createElement("select");
selectList.id = key;
selectList.style.fontSize = "10px";
myDiv.appendChild(selectList);
//Create and append the options
for (var i = 0, item; item = entry[i]; i++) {
var option = document.createElement("option");
option.value = item.value;
option.text = item.label;
selectList.appendChild(option);
}
});
}
<button type="button" onclick="createTable3()">Add Item</button>
<div id= "render"/>
If you use document.write("") the entire web page content will be replace by the content you pass inside the document.write function. Instead create a div element under button element like
<div id="list"></div>
then in the javascript file change as
function createTable()
{
var itemName = "Selections: ";
var selectElement = document.getElementById(list);
for (var i=0;i<7;i++)
{
var myTable = " ";
myTable+="<select name='test' id='mySelect"+i+"' style='font-size:10px' onchange='Calculate()'>";
myTable+="<option value='zeroPoint'>0</option>";
myTable+="<option value='halfPoint'>1/2</option>";
myTable+="<option value='onePoint'>1</option>";
myTable+="</select>";
selectElement.innerHTML = myTable;
}
}
I am unsure what you are exactly trying to achieve, but having DOM elements in strings and then modifying an elements innerHTML or using document.write is just a hack. You need to leverage the DOM apis.
While that means my code is maybe double or triple the the size of your code. Its the more maintainable version long term.
function createTable() {
var selectMenu = document.querySelector('#selectionsContainer');
// Array of options elements
var myTable = [];
// Pushing some elements to our my table array
//
myTable.push(
createOption('zeroPoint', 0),
createOption('halfPoint', 0.5),
createOption('onePoint', 1)
)
// Looping through all elements and adding them to the //selections container
//
myTable.forEach( element => {
selectionsContainer.appendChild(element);
});
}
/** Creates an option element and returns it for usage */
function createOption(value, label) {
var option = document.createElement('option');
option.value = value;
option.innerText = label;
return option;
}
function Calculate(value) {
console.log('do whatever you want to with the value: ', value);
}
select {
font-size:10px
}
<button type="button" onclick="createTable()">Add Item</button>
<label for="selectionsContainer">
Selections
<label>
<select id="selectionsContainer" onchange='Calculate(this.value)'>
<option value=5> 5 </option>
<select>
All the answers so far are pointing that OP might be doing something wrong by not creating select dynamically. But we don't know his requirements.
Also everybody already explained document.write will write on you entire document thus deleting everything, you don't want that.
document.write --> https://developer.mozilla.org/en-US/docs/Web/API/Document/write
appendChild should be used but you wanted a string and appendChild expect Node not string.
appendChild --> https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
node --> https://developer.mozilla.org/en-US/docs/Web/API/Node
So the only way to solve this is by using innerHTML and summing up inner Html by adding new ones.
Or by creating node from sting, which requires some more logic, see here --> Creating a new DOM element from an HTML string using built-in DOM methods or prototype
innerHTML --> https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
const selectTamplate = (selectId, onChangeCallbackName) => {
return `
<select name='test' id='mySelect${selectId}' style='font-size:10px' onchange='${onChangeCallbackName}()'>
<option value='zeroPoint'>0</option>
<option value='halfPoint'>1/2</option>
<option value='onePoint'>1</option>
</select>
`
};
const appendStringHtml = (elementTargetHtml, elemenAppend) => {
elemenAppend.innerHTML += elementTargetHtml;
}
const doSomethingOnChange = () => {
console.log('I am the KING!');
};
const placeToAppend = document.querySelector('.append-selects-here');
const buttonAppender = document.querySelector('.btn-append');
let selectID = 1;
buttonAppender.addEventListener('click', ()=>{
const selectHTML = selectTamplate(selectID, 'doSomethingOnChange');
appendStringHtml(selectHTML, placeToAppend);
selectID ++;
});
<button class="btn-append">Add Selects</button>
<div class="append-selects-here"></div>
see the working code here --> https://codepen.io/nikolamitic/pen/PEpEbj
I used template string so that interpolation is possible, little bit more clear. And separate the logic while still keeping yours.

Add validations on dynamically created form with Javascript

I created a form dynamically with javascript. Now I have to add validations on the form (only mandatory validations) on click of the button which is also dynamically created. Now the issue I am facing is that whenever I try to add addEventListener on the button exactly after creating it, it is giving me error.
(
function init() {
console.log("div created");
// create a new div element
var newDiv = document.createElement("div");
newDiv.id = "registration_form";
var createForm = document.createElement("form");
newDiv.appendChild(createForm);
var heading = document.createElement("h2");
heading.innerHTML = "Registration Form";
createForm.appendChild(heading);
var linebreak = document.createElement('br');
createForm.appendChild(linebreak);
createElement(createForm, 'label','','','Name: ');
createElement(createForm, 'text', 'dname', '','');
createSpanTag(createForm,'nameError');
breakTag(createForm);breakTag(createForm);
createElement(createForm, 'label','','','Email: ');
createElement(createForm, 'email', 'email', '','');
createSpanTag(createForm,'emailError');
createElement(createForm, 'button','Validate','Validate','');
document.getElementsByTagName('button')[0].addEventListener('click',validate());
document.getElementsByTagName('body')[0].appendChild(newDiv);
}
)();
function createElement(formElement,type,name,value, placeholder) {
if(type=='label'){
var element=document.createElement(type);
if(name!='' && value!=''){
element.setAttribute('name',name);
element.setAttribute('value',value);
}
element.innerHTML=placeholder;
formElement.appendChild(element);
} else {
var element=document.createElement('input');
if(type!=''){
element.setAttribute('type',type);
}
if(name!=''){
element.setAttribute('name',name);
}
if(value!=''){
element.setAttribute('value',value);
}
if(placeholder!=''){
element.setAttribute('placeholder',placeholder);
}
formElement.appendChild(element);
}
}
function breakTag(createForm){
createForm.appendChild(document.createElement('br'));
}
function validate(){
}
function createSpanTag(createForm, id){
var element=document.createElement('span');
element.setAttribute('id',id);
createForm.appendChild(element);
}
The second argument of addEventListener needs to be a function.
Change ...
document.getElementsByTagName('button')[0].addEventListener('click',validate())
to ...
document.getElementsByTagName('button')[0].addEventListener('click',validate);
Since your tag name is input, not button. So use input in parameter of the function getElementsByTagName() and then loop through all nodes and find node with type = button.
Try change this line:
document.getElementsByTagName('button')[0].addEventListener('click',validate());
to:
var nodeList = document.getElementsByTagName("input");
for (var i = 0; i < nodeList.length; i++)
{
if (nodeList[i].getAttribute("type") == "button") {
{
nodeList[i].addEventListener('click',validate);
}
}

How to get element by name with $key

PHP
//Here is my html for qty
<p>Qty : <input type="number" value="" name="qty<?php echo $key ?> onChange="findTotal()"/>
JS function
function findTotal() {
var arr = document.getElementsByName('qty');
...
document.getElementById('result').value = decimalPlaces(tot, 2);
}
My qty name needs key for post array. How do I get name inside js function to calculate quantities?
You can use
document.querySelector("input['name^='qty']").value
if you don't have jQuery.
This will select an input with name attribute starting with "qty". If you have multiple inputs which match the criteria you can select them all using
document.querySelectorAll("input[name^='qty']")
which will return a NodeList. You can read more about this here.
You can do something like this
var myVar = document.getElementsByTagName("somename");
//do something else
If you are using jquery
value = $( "input[name^='qtd']" ).val();
//it will pick the input wich name starts with 'qtd'
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'qty' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('qty') == 0) {
eles.push(inputs[i]);
}
}
Don't query the element by the name attribute's value. I'm not sure what's the purpose of the key and why you need it in the findTotal method, but here's an example:
<p>Qty : <input type="number" value="" name="qtyMyKey" onChange="findTotal(event)" /></p>
<script>
function findTotal(e) {
var inputEl = e.target,
inputName = inputEl.getAttribute('name'),
myKey;
if (typeof inputName === 'string') {
myKey = inputName.replace('qty', '');
}
console.log(myKey);
//var arr = document.getElementsByName('qty');
//document.getElementById('result').value = decimalPlaces(inputEl.value(), 2);
}
</script>
Here's the jsFiddle demo.

Remove node function on parent element

I'm new to JS. I'm trying to delete the parent node with all the children by clicking a button. But the console tells me that undefined is not a function. What am I missing?
Fiddle:
http://jsfiddle.net/vy0d8bqt/
HTML:
<button type="button" id="output">Get contacts</button>
<button type="button" id="clear_contacts">clear contact</button>
<div id="output_here"></div>
JS:
// contact book, getting data from JSON and outputting via a button
// define a JSON structure
var contacts = {
"friends" :
[
{
"name" : "name1",
"surname" : "surname1"
},
{
"name" : "name2",
"surname" : "surname2"
}
]
};
//get button ID and id of div where content will be shown
var get_contacts_btn = document.getElementById("output");
var output = document.getElementById("output_here");
var clear = document.getElementById("clear_contacts");
var i;
// get length of JSON
var contacts_length = contacts.friends.length;
get_contacts_btn.addEventListener('click', function(){
//console.log("clicked");
for(i = 0; i < contacts_length; i++){
var data = contacts.friends[i];
var name = data.name;
var surname = data.surname;
output.style.display = 'block';
output.innerHTML += "<p> name: " + name + "| surname: " + surname + "</p>";
}
});
//get Children of output div to remove them on clear button
//get output to clear
output_to_clear = document.getElementById("output_here");
clear.addEventListener('click', function(){
output_to_clear.removeNode(true);
});
You should use remove() instead of removeNode()
http://jsfiddle.net/vy0d8bqt/1/
However, this also removes the output_to_clear node itself. You can use output_to_clear.innerHTML = '' if you like to just delete all content of the node, but not removing the node itself (so you can click 'get contacts' button again after clearing it)
http://jsfiddle.net/vy0d8bqt/3/
You want this for broad support:
output_to_clear.parentNode.removeChild(output_to_clear);
Or this in modern browsers only:
output_to_clear.remove();
But either way, make sure you don't try to remove it after it has already been removed. Since you're caching the reference, that could be an issue, so this may be safer:
if (output_to_clear.parentNode != null) {
output_to_clear.remove();
}
If you were hoping to empty its content, then do this:
while (output_to_clear.firstChild) {
output_to_clear.removeChild(output_to_clear.firstChild);
}
I think using jQuery's $.remove() is probably the best choice here. If you can't or don't want to use jQuery, The Mozilla docs for Node provides a function to remove all child nodes.
Element.prototype.removeAll = function () {
while (this.firstChild) { this.removeChild(this.firstChild); }
return this;
};
Which you would use like:
output_to_clear.removeAll();
For a one-off given the example provided:
while (output_to_clear.firstChild) { output_to_clear.removeChild(output_to_clear.firstChild); }

Categories

Resources