Giving elements new id - javascript

I want to add ids to inputs dynamicly using javascript.How can I do that.I wrote a function but it wouldn't work.
html
<form>
element 0_0 <input type = "text" class = "elements"></input>
element 0_1 <input type = "text" class = "elements"></input>
element 1_0 <input type = "text" class = "elements"></input>
element 1_1 <input type = "text" class = "elements"></input>
<input type = "button" onclick = "giveId('elements')"></input>
</form>
javascript
function giveId(className){
var array = document.getElementsByClassName(className)
for(var i = 0;i < array.length; i++){
array[i].id = "A" + i;
}
}

inputs are self closing:
<form>
element 0_0 <input type="text" class="elements" />
element 0_1 <input type="text" class="elements" />
element 1_0 <input type="text" class="elements" />
element 1_1 <input type="text" class="elements" />
<input type="button" onclick="giveId('elements')" />
</form>
and className is an element propery in javascript, so you should use a different name:
function giveId(cName) {
var arr = document.getElementsByClassName(cName)
for (var i = 0; i < arr.length; i++) {
arr[i].id = "A" + i;
}
}
FIDDLE

I tested your code and it works fine.
Have you tried selecting your new IDs?
<form>
element 0_0 <input type = "text" class = "elements"></input>
element 0_1 <input type = "text" class = "elements"></input>
element 1_0 <input type = "text" class = "elements"></input>
element 1_1 <input type = "text" class = "elements"></input>
<input type = "button" onclick = "giveId('elements')"></input>
</form>
<script>
function giveId(classname){
var array = document.getElementsByClassName(classname)
for(var i = 0;i < array.length; i++){
array[i].id = "A" + i;
}
}
</script>

Related

How to use HTML form input as JS variable

I am trying to make some element change color according to the number received from the form.
e.g. When a player types 2 in the form, there should be 2 colors from the 'color' array.
function intro() {
var num = document.getElementById('quant').value;
var color = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"];
var i;
for (i = 1; i <= 42; i++) {
document.getElementById('s' + i).style.backgroundColor = color[getRndInteger(0, num)];
}
}
<form id="tion" action="" method="get">
Player (between 2 and 6):
<input type="number" name="quant" min="2" max="6">
<input type="button" value="start" onclick="intro()">
</form>
Because you're not showing relevant parts of your code, I've simplified it. Your input was missing an id="quant" which I added.
function colorTheDiv() {
const color = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"];
document.getElementById('colorMe').style.backgroundColor = color[parseInt(document.getElementById('quant').value)];
}
<label for="quant">Player (between 2 and 6)</label>
<input type="number" name="quant" id="quant" min="2" max="6" onchange="colorTheDiv()">
<hr />
<div id="colorMe">colorMe</div>
I've also replaced the button and execute the colorTheDiv function whenever the value of quant changes (if you prefer you can still keep the button instead).
Start by giving your field an ID of quant.
You are missing 42 elements too
I assume you ACTUALLY meant this
var color = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"];
function getRndInteger(max) {
return Math.floor(Math.random() * max);
}
function intro() {
var container = document.getElementById("container");
container.innerHTML = "";
var num = document.getElementById('quant').value;
if (!num) {
alert("Give a value")
return;
}
for (var i = 1; i <= 42; i++) {
var col = color[getRndInteger(num)];
var span = document.createElement("span");
span.innerText = i;
span.id = "s" + i;
span.style.backgroundColor = col;
container.appendChild(span)
}
}
<form id="tion" action="" method="get">
Player (between 2 and 6):
<input type="number" id="quant" min="2" max="6">
<input type="button" value="start" onclick="intro()">
</form>
<div id="container"></div>
you need to give your field an ID of "quant" not just a name, otherwise getElementByID will return null

Replace all occurrences of "<", ">" inside value attribute

I have the requirement to replace all occurrences of "<" and ">" characters that are found inside the value attribute. I want to replace "<" and ">" characters with ""
This is my sample html:
<form name="form1">
<input type="text" value="<first set><second set><third set>" />
<input type="text" value="<fourth set><fifth set><sixth set>" />
</form>
I tried using javascript replace method but no luck.
You could use this pure JavaScript function:
function removeLessGreaterThan(html) {
// Use the DOM API to change the value attribute values:
var span = document.createElement('span');
span.innerHTML = html;
var inputs = span.querySelectorAll('input[type=text]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute('value', inputs[i].value.replace(/[<>]/g, ''));
}
return span.innerHTML;
}
// Sample data:
var html = '<form name="form1"> <input type="text" value="Here is a >test<." /> <input type="text" value="And another >test<." /> </form>';
html = removeLessGreaterThan(html);
console.log(html);
const FORM_NAME = "form1";
var fields = document.getElementsByName(FORM_NAME)[0].getElementsByTagName("input");
for(var i = 0; i < fields.length; i++) {
fields[i].value = fields[i].value.replace(/[<>]/g, "");
}
I think you are expecting this way. Please go through the code.
function ReplaceMyValues()
{
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
if(inputs[i].type=="text")
{
var currentValue=inputs[i].value.replace(/[<>]/g, "");
inputs[i].value = currentValue;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<form name="form1"> <input type="text" value="<first set><second set><third set>" /> <input type="text" value="<fourth set><fifth set><sixth set>" />
<input id="Test" type="button" value="Replace" onclick="ReplaceMyValues();"></input>
</form>
You can use jquery
$(".yourInput").val($(".yourInput").val().replace('<', '').replace('>', ''))

Adding input fields to a HTML form

I want to dynamically add form input fields to a form using the javascript below by clicking on the add button:
var i = 0;
function increment() {
i += 1;
}
function addfieldFunction() {
var r = document.createElement('div');
var y = document.createElement("INPUT");
var z = document.createElement("INPUT");
y.setAttribute("class", "dash-input");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "University");
z.setAttribute("class", "dash-input");
z.setAttribute("type", "text");
z.setAttribute("placeholder", "Course");
increment();
y.setAttribute("Name", "a_level[ + i ][0]");
r.appendChild(y);
z.setAttribute("Name", "a_level[ + i ][1]");
r.appendChild(z);
document.getElementById("form-div").appendChild(r);
}
<form class = "dash-form" method = "POST" action = "/" >
<div id = "form-div">
<input class = "dash-input" type = "text" name = "a_level[+i][0]" value = "" placeholder = "University"/>
<input class = "dash-input" type = "text" name = "a_level[+i][1]" value = "" placeholder = "Course"/>
</div>
<div class = "dash-submit">
<input class = "dash-submit-button" type = "submit" value = "Submit"/>
</div>
</form>
<div class = "dash-add">
<button class = "dash-add-button" onclick = "addfieldFunction()">ADD</button>
</div>
The function returns an i instead of incrementing and returning an integer as shown below:
<div id = "form-div">
<input class = "dash-input" type = "text" name = "a_level[0][0]" value = "" placeholder = "University"/>
<input class = "dash-input" type = "text" name = "a_level[0][1]" value = "" placeholder = "Course"/>
</div>
Concatenate variable i using +(concatenation operator) operator
The concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
var i = 0;
function increment() {
i += 1;
}
function addfieldFunction() {
var r = document.createElement('div');
var y = document.createElement("INPUT");
var z = document.createElement("INPUT");
y.setAttribute("class", "dash-input");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "University");
z.setAttribute("class", "dash-input");
z.setAttribute("type", "text");
z.setAttribute("placeholder", "Course");
increment();
y.setAttribute("name", "a_level[ " + i + " ][0]"); //Keep attribute in lower case
r.appendChild(y);
z.setAttribute("name", "a_level[ " + i + "][1]");
r.appendChild(z);
document.getElementById("form-div").appendChild(r);
}
<form class="dash-form" method="POST" action="/">
<div id="form-div">
<input class="dash-input" type="text" name="a_level[+i][0]" value="" placeholder="University" />
<input class="dash-input" type="text" name="a_level[+i][1]" value="" placeholder="Course" />
</div>
<div class="dash-submit">
<input class="dash-submit-button" type="submit" value="Submit" />
</div>
</form>
<div class="dash-add">
<button class="dash-add-button" onclick="addfieldFunction()">ADD</button>
</div>
You need to concatenate it like this:
y.setAttribute("name", "a_level[" + i +"][0]");
As Rayon pointed out: keep attributes in lower case although the HTML5 standard does not require lower case attribute names (see here). W3C recommends it though and XHTML validation would fail using uppercase letters.

javascript: changing the name attribute dynamically

I have this script I'm working on and there's no errors on it but I want to add some functions on it like when I click the button it adds but I want the name attribute of the input text to be changed too.
Here's my script:
javascript:
var a = 1;
function add() {
var fContent = document.getElementById('1');
var sContent = document.getElementById('2');
if (a <= 10) {
a++;
var objTo = document.getElementById('m');
var divtest = document.createElement("div");
divtest.innerHTML = (sContent.innerHTML + a + fContent.innerHTML);
alert(divtest.innerHTML);
objTo.appendChild(divtest);
}
}
html:
<input type="button" onclick="add();" value="+" />
<div id="m">
<div id="1">
<input type="text" name="f">
<input type="text" name="l">
<input type="text" name="m">
</div>
<div id="2"></div>
</div>
OUTPUT:
2
<input type="text" name="f">
<input type="text" name="l">
<input type="text" name="m">
EXPECTED OUTPUT:
2
<input type="text" name="f2">
<input type="text" name="l2">
<input type="text" name="m2">
and so on...
You're not doing anything to change the name attributes. Trying to make those changes with html concatenation will get you into trouble. This will get you started:
(function() {
var a = 1;
// get a reference to the container
var container = document.getElementById("m");
// get a reference to the first row of input
var base = container.children[0];
document.querySelector("button").addEventListener("click", function(e) {
if(++a > 10) return;
// clone the first row of input
var clone = base.cloneNode(1);
// change the number text by setting the span's textContent
clone.children[0].textContent = a;
// set the names of the input fields
clone.children[1].name = "f" + a;
clone.children[2].name = "l" + a;
clone.children[3].name = "m" + a;
// add the new row to the container
container.appendChild(clone);
console.log(clone);
});
})();
<button type="button">+</button>
<div id="m">
<div><span>1</span><input type="text" name="f1"><input type="text" name="l1"><input type="text" name="m1"></div>
</div>
If you'd rather create the elements from scratch...
(function() {
var a = 1;
// get a reference to the container
var container = document.getElementById("m");
var input;
var span;
var div;
document.querySelector("button").addEventListener("click", function(e) {
if(++a > 10) return;
// create our div
div = document.createElement("div");
// create and append our span
span = document.createElement("span");
span.textContent = a;
div.appendChild(span);
// create and append inputs
["f","l","m"].forEach(function(n){
input = document.createElement("input");
input.name = n + a;
div.appendChild(input);
});
// append our div
container.appendChild(div);
console.log(div);
});
})();
<button type="button">+</button>
<div id="m">
<div><span>1</span><input type="text" name="f1"><input type="text" name="l1"><input type="text" name="m1"></div>
</div>

Get the element name attribute in JavaScript

How can I get the element name attribute in JavaScript?
HTML :
<input class="so" name="Name" value="bob"></input>
<input class="so" name="LastName" value="Feyzi"></input>
<input class="so" name="Email"></input>
<input class="so" name="Address"></input>
<input type="submit"></input>
JavaScript :
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
var elname = document.getElementByClassName('.so')[i].getAttribute('name');
//var eln = document.getElementsByTagName("input")[i].getAttribute("name");
var vala = document.querySelectorAll('.so')[i].value;
//alert(vala);
alert(elname);
}
After I run the script I want the person object to be set with this data:
person {
Name: "bob",
LastName: "Feyzi",
Email: "",
Adderss: ""
}
JSFiddle
Use the collection that you've already found with querySelectorAll to get the values of the value and name attributes :
var person = {}
var cars = document.querySelectorAll(".so")
for (i = 0; i < cars.length; i++) {
person[cars[i].name] = cars[i].value
}
console.log(person)
JSFiddle
Because getElementByClassName does not exist (also it would have no use in your script). Use this:
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
alert(cars[i].name)
}
Firstly, use cars variable instead of calling querySelectorAll every time.
Secondly, use addEventListener to execute code on click.
Fiddle: http://jsfiddle.net/guyavunf/3/
Code:
// HTML
<input class="so" name="Name" value="bob"></input>
<input class="so" name="LastName" value="Feyzi"></input>
<input class="so" name="Email"></input>
<input class="so" name="Address"></input>
<input class="submit" type="submit"></input>
// JS
document.querySelector('.submit').addEventListener('click', function() {
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
var name = cars[i].name;
var value = cars[i].value;
alert(name + ': ' + value);
}
});

Categories

Resources