get required form elements via DOM in javascript - javascript

To do checking on required fields and a custom method of alerting users that required fields are missing, I'm trying to get an array of elements in a form, and have been hunting but not finding a good method.
Is there some variation of
document.getElementById(form).elements;
that would return all the required elements of an array, or a way to test if a given element is required... something akin to either
var my_elements = document.getElementById(form).required_elements;
or
var my_elements = document.getElementById(form).elements;
for (var this_element in my_elements){
if (this_element.attributes["required"] == "false"){
my_elements.splice(this_element, 1);
}
}

Try querySelectorAll with an attribute selector:
document.getElementById(form).querySelectorAll("[required]")
var requiredElements = document.getElementById("form").querySelectorAll("[required]"),
c = document.getElementById("check"),
o = document.getElementById("output");
c.addEventListener("click", function() {
var s = "";
for (var i = 0; i < requiredElements.length; i++) {
var e = requiredElements[i];
s += e.id + ": " + (e.value.length ? "Filled" : "Not Filled") + "<br>";
}
o.innerHTML = s;
});
[required] {
outline: 1px solid red;
}
<form id="form">
<input required type="text" id="text1" />
<input required type="text" id="text2" />
<input type="text" id="text3" />
<input type="text" id="text4" />
<input required type="text" id="text5" />
</form>
<br>
<button id="check">Check</button>
<br>
<div id="output">
Required inputs
</div>

Related

How should I put limit inside for loop using if condition using javascript

My goal is that only 15 quantities of input elements can be accepted, once the user enters 16 it should say that only 15 input elements is allowed. However I don't know how will I do this. I tried putting condition inside for but it is not not working. I am a little bit confused on this
Here is my HTML code
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem"
required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
Here is my JS code
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
var parent = $(document.getElementById("parent"));
var value = $('#sel_control_num').val();
functionPopulate(parent);
if (isNaN(element)) {
return;
}
for (var i = 0; i < element; i++) {
if(should I do it here??){
}
value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text"
value="' + value +
'" class="form-control" name="get_Input_show[]" required>'
}
});
You can check if the element value is < 16 if yes then only add html else show error message.
Demo Code :
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
//var value = $('#sel_control_num').val();
var value = 12;
//functionPopulate(parent);
if (isNaN(element)) {
return;
}
//check if elemnt value if < 16
if (element < 16) {
$("#parent").empty() //empty div
for (var i = 0; i < element; i++) {
/* value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});*/
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text" value = "' + value + '" class="form-control" name="get_Input_show[]" required>';
}
} else {
alert("only 15") //show error
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem" required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
There are two ways in which you can restrict it
You can use maxLength property of an input tag, which will restrict the user to input the 16th character.
You can keep checking the value in the input field and show error if the length is more than 15 character. To do this you can use onkeypress event on input, like
HTML
<input type="text" id="test" onkeypress="test()" />
JS:
<script>
function test() {
alert('Hi')
}
</script>

Loading user input into an array then display

Trying to get user input from HTML form and then get it into an array in javascript. Afterwards output it back into the div tag in HTML as a list.
The code works but it outputs the text twice instead of just once.
Example: user inputs orange in HTML form, then inputs apple, then banana
My code makes it output: orange, orange, apple, orange, apple, banana
It should just output: orange, apple, banana
// global variable
var enteredStringsArray = [];
function listArray() {
"use strict";
var form;
var enteredText;
var enteredString;
var index;
form = document.getElementById("lab06");
enteredText = form.text.value;
enteredStringsArray.push(enteredText);
enteredString = document.getElementById("theOrderedList");
for (index = 0; index < enteredStringsArray.length; index++) {
enteredString.innerHTML += "<li>" + enteredStringsArray[index] + " </li>";
}
return false;
}
<form id="list" action="#" onsubmit="return listArray();">
<label>Text:</label>
<input type="text" id="textId" name="text" />
<br/>
<input type="submit" name="runForm" value="submit" />
</form>
<div id="outputDiv" class="Output">
<ol id="theOrderedList"></ol>
</div>
replace
for (index = 0; index < enteredStringsArray.length; index++) {
enteredString.innerHTML += "<li>" + enteredStringsArray[index] + "
</li>";
}
from
enteredString.innerHTML += "<li>" + enteredText + "</li>";
it will work. Add each input items one by one. no need to loop it.
You can try without forloop, just create new li element and append in your ol
// global variable
var enteredStringsArray = [];
function lab06firstArrays() {
"use strict";
var enteredText;
enteredText = document.getElementById("textId").value;
enteredStringsArray.push(enteredText);
console.log(enteredStringsArray);
var ul = document.getElementById("theOrderedList");
var li = document.createElement("li");
li.appendChild(document.createTextNode(enteredText));
ul.appendChild(li);
document.getElementById("textId").value= "";
return false;
}
<form id="lab06" action="#" onsubmit="return lab06firstArrays();">
<label>Text:</label>
<input type="text" id="textId" name="text" />
<br/>
<input type="submit" name="runForm" value="submit" />
</form>
<br/>
<div id="outputDiv" class="Output">
<ol id="theOrderedList"></ol>
</div>
EDIT:
With forloop:
// global variable
var enteredStringsArray = [];
function lab06firstArrays() {
"use strict";
var enteredText;
enteredText = document.getElementById("textId").value;
enteredStringsArray.push(enteredText);
//console.log(enteredStringsArray);
var ul = document.getElementById("theOrderedList");
for (var i= enteredStringsArray.length - 1; i < enteredStringsArray.length; i++)
{
var li = document.createElement("li");
li.appendChild(document.createTextNode(enteredText));
ul.appendChild(li);
document.getElementById("textId").value= "";
}
return false;
}
<form id="lab06" action="#" onsubmit="return lab06firstArrays();">
<label>Text:</label>
<input type="text" id="textId" name="text" />
<br/>
<input type="submit" name="runForm" value="submit" />
</form>
<br/>
<div id="outputDiv" class="Output">
<ol id="theOrderedList"></ol>
</div>

Creating input element continuing ID enumeration

I have a button that creates 4 input elements inside a DIV after click:
<div id="content"></div>
<button class="check">Check</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var num = 4;
$(".check").click(function(){
for(i=0; i<num;i++){
$("#content").append("<input id='input"+i+"' type='text'><br>");
}
});
</script>
But the problem is I want input id number continues the enumeration (like this example) instead of return to zero:
<div id="content">
<input id="input0" type="text">
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
<input id="input4" type="text">
<input id="input5" type="text">
<input id="input6" type="text">
<input id="input7" type="text">
...and continues
</div>
How can I fix it?
You can check the id of the last input. Here I am calculating start and end of for loop based on the total number of elements in #container.
var num = 4;
$(".check").click(function() {
var start = $("#content input").length;
var end = start + num;
for (i = start; i < end; i++) {
var id = 'input' + i;
$("#content").append("<input id='"+id+"' type='text' value='"+id+"'><br>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<button class="check">Check</button>
PS: Here input value is just to demonstrate the id setting to input.
You need some kind of global variable here, or use that simple one:
var getID = (function () {
var id = 0;
return function () { return ++id; }
})();
So whenever you call getID() the »internal« id will be incremented, so each call will yield an new ID.
$(".check").click(function() {
for(var i = 0; i < 4; i++) {
$('<input type="text">') //create a new input
.attr('id', 'input' + $('#content input').length) //id based on number of inputs
.appendTo('#content'); //append it to the container
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<button class="check">Check</button>
If you're asking how to have a stack of elements to begin with, and then continue enumeration from there, you simply need to set a variable to the ID of the latest element.
All you need to do is count the number of elements. This can be done with a combination of .querySelectorAll() and .length.
Then simply have your loop start at this new value instead of 0.
This can be seen in the following:
var total_desired = 20;
var start = document.querySelectorAll('#content > input').length;
console.log(start + " elements to start with");
$(".check").click(function() {
for (i = start; i < total_desired; i++) {
$("#content").append("<input id='input" + i + "' type='text'><br>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="check">Check</button>
<div id="content">
<input id="input0" type="text">
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
<input id="input4" type="text">
<input id="input5" type="text">
<input id="input6" type="text">
<input id="input7" type="text"> ...and continues
</div>
Having said that, it's unlikely that you actually need simultaneous ID <input> elements, and you may benefit from classes instead.
You can create this object:
var MyId = {
a: 0,
toString() {
return this.a++;
}
}
And concatenate it into the string. Automatically will increase the counter.
<div id="content"></div>
<button class="check">Check</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var GetID = {
a: 0,
toString() {
return this.a++;
}
}
var num = 4;
$(".check").click(function(){
for(i=0; i<num;i++){
$("#content").append("<input id='input"+GetID+"' type='text'><br>");
}
});
</script>

querySelectorAll loop "undefined"

I try to loop over few input elements in order to get each value, but for some reason I only get the last one:
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<button type="button" onclick="loop()">loop</button>
<div id="output"></div>
<script>
function loop() {
var element = document.querySelectorAll('[data-loop="true"]');
for(var i = 0; i < element.length; i++) {
console.log(element[i].length);
// or:
// document.getElementById('output').innerHTML = element[i].value + '<br>';
}
}
</script>
The console shows undefined and when I try to output the values, I only get it from the last element and not from all of them. What am I doing wrong?
Thank you very much (and please excuse my english)
You are trying to get the length of the element itself:
console.log(element[i].length);
Elements don't have a length.
I suspect you are trying to get the length of the value of the elements:
console.log(element[i].value.length);
function loop() {
// elements will be a "node list" containing any/all elements
// that match the query.
var elements = document.querySelectorAll('[data-loop="true"]');
// Because it is a node list, which is an array-like object,
// it has a "length" property:
console.log("There were " + elements.length + " elements found.");
// ...And, it can be looped through
for(var i = 0; i < elements.length; i++) {
// It's contained elements are indexed and when you do that,
// you may access properties of the elements themselves
console.log(elements[i].value);
// or:
document.getElementById('output').innerHTML += elements[i].value + '<br>';
}
}
<p>Type some text in the textboxes and then click the button:</p>
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<button type="button" onclick="loop()">loop</button>
<div id="output"></div>
try to console.log(element[i]); This is because here element will be a collection of DOM elements.
There is no length property for these elements.
Since they are input and if you want to get their value you need to log
element[i].value
What am I doing wrong?
console.log(element[i].length);
element[i] refers to an HTMLInputElement. It and non of its parent classes have a length property. Assuming you want to display the length of the value of the input element, the following would work.
var output = document.getElementById('output');
function loop() {
var element = document.querySelectorAll('[data-loop="true"]');
element.forEach( (e) => {
output.innerHTML += `${e.value}: ${e.value.length}<br>`;
});
}
function clearOutput(){
output.innerHTML = '';
}
<input type="text" name="input-loop" data-loop="true" value="one" />
<input type="text" name="input-loop" data-loop="true" value="two" />
<input type="text" name="input-loop" data-loop="true" value="three" />
<button type="button" onclick="loop()">loop</button>
<button type="button" onclick="clearOutput()">clear</button>
<div id="output"></div>

jQuery add ID increment to .html() appending on input onchange and refresh onchange value

I apologize for the wordy title but I haven't found a solution to my problem yet. I am a newbie with jQuery and web development so any guidance would be appreciated.
I have a <input> that allows user to enter a value (number) of how many rows of a set of input fields they want populated. Here's my example:
<div id="form">
<input id="num" name="num" type="text" />
</div>
<p> </p>
<div id="form2">
<form action="" method="post" class="form_main">
<div class="data">
<div class="item">
<input id="name" name="name[]" type="text" placeholder="name" /><br/>
<input id="age" name="age[]" type="text" placeholder="age" /><br/>
<input id="city" name="city[]" type="text" placeholder="city" /><br/>
<hr />
</div>
</div>
<button type="submit" name="submit">Submit</button>
</form>
My jQuery:
<script>
var itemNum = 1;
$("#num").on("change", function() {
var count = this.value;
var item = $(".item").parent().html();
//item.attr('id', 'item' + itemNum);
for(var i = 2; i <= count; i++) {
itemNum++;
$(".data").append(item);
}
})
</script>
I'm having problems adding an ID item+itemNum increment to <div class="item">... item.attr() didn't work. It doesn't append once I added that line of code.
Also, how can I get it so that once a user enters a number that populates rows of input fields, that if they change that number it will populate that exact number instead of adding to the already populated rows? Sorry if this doesn't make any sense. Please help!
Here is a DEMO
var itemNum = 1;
$("#num").on("change", function() {
$('.data div').slice(1).remove(); //code for removing previously populated elements.
var count = this.value;
console.log(count);
var item;
//item.attr('id', 'item' + itemNum);
var i;
for(i = 1; i <= count; i++) {
console.log(i);
item = $("#item0").clone().attr('id','item'+itemNum);
//prevent duplicated ID's
item.children('input[name="name[]"]').attr('id','name'+itemNum);
item.children('input[name="age[]"]').attr('id','age'+itemNum);
item.children('input[name="city[]"]').attr('id','city'+itemNum);
itemNum++;
$(".data").append(item);
}
})
Use clone() instead of html()
Try
var itemNum = 1,
item = $(".data .item").parent().html();;
$("#num").on("change", function () {
var count = +this.value;
if (itemNum < count) {
while (itemNum < count) {
itemNum++;
$(item).attr('id', 'item' + itemNum).appendTo('.data')
}
} else {
itemNum = count < 1 ? 1 : count;
$('.data .item').slice(itemNum).remove();
}
})
Demo: Fiddle

Categories