javascript creat div or section from the input form - javascript

I have a form that i enter the number of element then the text then the type div or section
and i click create i should remove the older div or section and create the new one
/*get the number of element the text and the type*/
let element = document.querySelector("[name='elements']");
let text = document.querySelector("[name='texts']");
let type = document.querySelector("[name='type']");
let result = document.querySelector(".results");
document.forms[0].onsubmit = function (e) {
let validElement = false;
let validText = false;
let validType = false;
document.querySelectorAll(".results .box").forEach((box) => box.remove());
if (element.value !== "" && text.value !== "" && type.value !== "" && element.value > 0) {
for (let i = 0; i < element.value; i++) {
myBox = document.createElement(type.value);
myBox.className = "box";
myBox.id = `id-${i+1}`;
myBox.title = "Element";
myText = document.createTextNode(text.value);
myBox.appendChild(myText);
result.appendChild(myBox);
}
validElement = true;
validText = true;
validType = true;
}
if (validElement === false || validText === false || validType === false) {
e.preventDefault();
}
};
<form action="">
<input type="number" name="elements" class="input" placeholder="Number Of Elements" />
<input type="text" name="texts" class="input" placeholder="Elements Text" />
<select name="type" class="input">
<option value="Div">Div</option>
<option value="Section">Section</option>
</select>
<input type="submit" name="create" value="Create" />
</form>
<div class="results"></div>
The problem is that the div or section appear but than disappear quickly i'm checking if the field are empty and if the field element number > 0 than i create the element that should appear in the result div
how can i solve this problem

The problem with your code is that you aren't preventing the <form> from refreshing the page.
if (validElement === false || validText === false || validType === false) {
e.preventDefault();
}
You use the above if statement to prevent the <form>'s default behaviour, but you set all those variables to true after creating your elements.
validElement = true;
validText = true;
validType = true;
So your script basically creates the elements and then the form refreshes the page.
Moving e.preventDefault(); outside of its if block would fix your immediate problem.
I would personally call e.preventDefault(); regardless of whether the users put in valid data, as a page refresh seems unneccesary in either case.
As for how to clear your results div, here is an elaborate post describing several ways of doing it.
/*get the number of element the text and the type*/
let element = document.querySelector("[name='elements']");
let text = document.querySelector("[name='texts']");
let type = document.querySelector("[name='type']");
let result = document.querySelector(".results");
document.forms[0].onsubmit = function (e) {
let validElement = false;
let validText = false;
let validType = false;
document.querySelectorAll(".results .box").forEach((box) => box.remove());
if (element.value !== "" && text.value !== "" && type.value !== "" && element.value > 0) {
// Clear the Results Container
while (result.firstChild) {
result.removeChild(result.lastChild);
}
// Repopulate the Results Container
for (let i = 0; i < element.value; i++) {
myBox = document.createElement(type.value);
myBox.className = "box";
myBox.id = `id-${i+1}`;
myBox.title = "Element";
myText = document.createTextNode(text.value);
myBox.appendChild(myText);
result.appendChild(myBox);
}
validElement = true;
validText = true;
validType = true;
}
e.preventDefault();
};
<form action="">
<input type="number" name="elements" class="input" placeholder="Number Of Elements" />
<input type="text" name="texts" class="input" placeholder="Elements Text" />
<select name="type" class="input">
<option value="Div">Div</option>
<option value="Section">Section</option>
</select>
<input type="submit" name="create" value="Create" />
</form>
<div class="results"></div>

Related

How to allow one specific word into text field in form using javascript?

I have input number field which is from 1000 to 10000 range but I also want to allow one only word 'All' into this field if user enter any word then show error. I have not written any JavaScript code for this because I do not have any idea how to do this. can anyone help me out please? Thanks
<input type="text" class="form-control" id="validationCustom02" min="1000" max="10000" required>
Here is my javascript solution: It uses a single If statement to check if the string is a number or ALL. Technically you don't need the isNaN function in there so if you want to remove it, the if statement will still work.
var _input = document.querySelector(".validate-num");
var _min= 1000;
var _max = 10000;
_input.addEventListener("input",function(){
var _valid = ((isNaN(this.value) && this.value.toLowerCase() == "all") || (!isNaN(this.value) && (this.value >= _min && this.value <= _max)));
if(!_valid){
var error = document.getElementById("error");
error.innerHTML = "Value Must be 1000 to 10000 or ALL";
}
});
<input type="text" class="validate-num form-control" id="validationCustom02" required>
A number type can't have strings into it, you will have to have a text input with an Event listener which does the validation job For You. Here, I have added a blur listener, it would trigger once you move away from the input.
const inputElem = document.querySelector('#validationCustom02required');
inputElem.addEventListener('blur', (e) => {
const val = e.target.value;
let showError = false;
if (isNaN(val)) {
if (val.toLowerCase() !== 'all') {
showError = true;
}
} else {
const numVal = +val;
if (val < 1000 || val > 10000) {
showError = true;
}
}
const errorElem = document.querySelector('#error');
if (showError) {
errorElem.innerText = 'Invalid; Value!';
} else {
errorElem.innerText = '';
}
})
<input type="text" class="form-control" id="validationCustom02required">
<div id="error"></div>

The simplest way to enable form submit button when text input is not empty

I would like to disable the submit button until all text inputs are filled. My code example below isn’t working.
What is the simplest and most idiomatic way to achieve this and what am I missing?
const form = document.forms[0]
const inputs = form.querySelector("fieldset > *")
const submit = form.querySelector("[type=submit]")
inputs.addEventListener("change", () => {
if (!inputs.length) {
submit.disabled = true
} else {
submit.disabled = false
}
})
<form>
<fieldset>
<input type="text" placeholder="John Doe" id="name"><br>
<input type="email" placeholder="john#example.com" id="email"><br>
<textarea placeholder="Lorem ipsum dolor sit amet." id="message"></textarea>
</fieldset>
<input type="submit" value="Submit">
</form>
I'm aware that there are numerous questions and answers on Stack Overflow about this, but most are needlessly complicated.
Probably similar to the other solutions, I tested this in JSFiddle so I know it works at least.
const form = document.forms[0];
const inputs = form.querySelectorAll("fieldset > input, fieldset > textarea");
const submit = form.querySelector("[type=submit]");
for (i in inputs) {
var _input = inputs[i];
if (typeof _input == 'object') {
_input.addEventListener("change", () => {
submit.disabled = false;
for (i in inputs) {
var _input = inputs[i];
if (typeof _input == 'object') {
if (_input.value == '') {
submit.disabled = true;
break;
}
}
}
});
}
}
https://jsfiddle.net/un1m5jgq/13/
You can make a function to check if the inputs are empty. Then just make that function the callback for the form inputs.
EDIT:
If you have an array of inputs you can use for loops and replace all the individual input variables.
let form = document.forms[0]
let nameInp = document.getElementById('name');
let emailInp = document.getElementById('email');
let messageInp = document.getElementById('message');
let submit = form.querySelector("[type=submit]")
function checkInputs() {
if (nameInp.value != "" && emailInp.value != "" && messageInp.value != "") {
submit.disabled = false;
} else if(!(nameInp.value != "" && emailInp.value != "" && messageInp.value != "")){
submit.disabled = true;
}
}
nameInp.addEventListener("change",checkInputs);
emailInp.addEventListener("change",checkInputs);
messageInp.addEventListener("change",checkInputs);
<form>
<fieldset>
<input type="text" placeholder="John Doe" id="name"><br>
<input type="email" placeholder="john#example.com" id="email"><br>
<textarea placeholder="Lorem ipsum dolor sit amet." id="message"></textarea>
</fieldset>
<input type="submit" value="Submit" disabled>
</form>
You should have select all inputs/textareas inside fieldset by querySelectorAll and loop for each values.
You should try below code to get what you want. You can use Jquery to make it much simple.
const form = document.forms[0]
var inputs = form.querySelectorAll("fieldset > input, fieldset > textarea"),result;
const submit = form.querySelector("[type=submit]")
console.log(inputs);
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('change', function() {
for (var j = 0; j < inputs.length; j++) {
if (!inputs[j].value.length) {
submit.disabled = true
return;
} else {
submit.disabled = false
}
}
});
}
<form>
<fieldset>
<input type="text" placeholder="John Doe" id="name"><br>
<input type="email" placeholder="john#example.com" id="email"><br>
<textarea placeholder="Lorem ipsum dolor sit amet." id="message"></textarea>
</fieldset>
<input type="submit" value="Submit" disabled>
</form>

How correctly check if input is not equal zero

I have simple code, in input user inputs number and it must print the numbers until the input is not equal to zero.
And the problem is when i submit value, page stops responding
Here is how my code looks like:
window.onload = function() {
var btn = document.getElementsByClassName('btn')[0];
function printInput() {
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
while(input !== 0) {
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input+'<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="text" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>
The value property of input is a string.
You must compare with the correct type:
while (input !== '0')
or
while (input != 0)
----- edit -----
Consider changing the while to an if, otherwise it will print any number different of 0 indefinitely.
window.onload = function() {
var btn = document.getElementsByClassName('btn')[0];
function printInput() {
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
if(input !== '0') {
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input+'<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="text" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>
You need to make two changes
Change type attribute from text to number
Change from while to if
Demo
window.onload = function()
{
var btn = document.getElementsByClassName('btn')[0];
function printInput()
{
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
if (input !== 0)
{
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input + '<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="number" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>

Angularjs devade tags when user put comma

I have a case in which I need to divide tags when the user put a comma separation, for the moment the user can only add tags one by one, what I want to do is allows user to enter more than one tag in the input separated by a comma:
This is what I have now :
this is what I want to do :
what I have so far :
<div class="form-group">
<label>Mes centres d'intérêt</label>
<div class="input-group" style="margin-bottom: 8px;">
<input id="tagInsert" type="text" name="newTag" ng-model="newTag" ng-model-options="{debounce: 100}" typeahead="tag for tag in getTags($viewValue)" class="form-control" typeahead-loading="loadingTags" ng-keydown="addInterestOnEvent($event)" ng-disabled="interestLimit" autocomplete="off">
<span class="input-group-btn"><span class="btn btn-primary" ng-click="addInterest()" analytics-on="click" ng-disabled="interestLimit" analytics-event="Ajout Interet" analytics-category="Profil">Ajouter</span></span>
</div>
<p class="form__field__error" ng-show="interestLimit">Vous avez atteint la limite de 10 centres d'intérêt.</p>
<ul class="tags">
<li class="tag" ng-repeat="name in user.interests track by $index">{{ name }} <i class="icon-close" ng-click="removeInterest($index)" analytics-on analytics-event="Supprimer Interet" analytics-category="Profil"></i></li>
</ul>
</div>
My controller :
$scope.getTags = function (name) {
return $http.get('/api/tags/' + name.replace('/', '')).then(function (result) {
var tags = result.data;
for (var i = tags.length; i--; ) {
var tagName = tags[i].name;
if ($scope.user.interests.indexOf(tagName) !== -1) tags.splice(i, 1);
else tags[i] = tagName;
}
return tags;
});
};
$scope.removeInterest = function (id) {
$scope.interestLimit = false;
$scope.user.interests.splice(id, 1);
}
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value;
if (value.length) {
element.value = '';
if ($scope.user.interests.indexOf(value) === -1) {
$scope.user.interests.push(value);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
};
$scope.addInterestOnEvent = function (event) {
if (event.which !== 13) return;
event.preventDefault();
$scope.addInterest();
};
$scope.remove = function () {
$scope.confirmModal = Modal.confirm.delete(function () {
User.remove(function () {
submit = true;
Auth.logout();
$location.path('/');
});
})('votre compte');
};
You should split value with comma and do for loop.
Change "addInterest" function like this:
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value.split(',');
if (value.length) {
element.value = '';
for (var i = 0; i < value.length; i++) {
if ($scope.interestLimit) break;
if ($scope.user.interests.indexOf(value[i]) === -1) {
$scope.user.interests.push(value[i]);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
}
};
As far as I understand , you want to split text into string array by comma
Try this code please
<input id='tags' type="text" />
<input type="button" value="Click" onclick="seperateText()" />
<script>
function seperateText(){
var text= document.getElementById("tags").value;
var tags = text.split(',');
console.log(text);
console.log(tags);
}
</script>

this parameter not passing expected element

I have a dynamic set of input fields being generated. They all get named sequentially and each has an onFocus() handler. Just before each Input element is a div with a corresponding Id where I grab a dollar value from.
<input type="hidden" name="balance" value="2500.0" />
<div id="invoiceAmount0">$500.00</div>
<input type="text" size="8" id="invoiceBalance0" name="invoiceBalance0" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount1">$500.00</div>
<input type="text" size="8" id="invoiceBalance1" name="invoiceBalance1" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount2">$500.00</div>
<input type="text" size="8" id="invoiceBalance2" name="invoiceBalance2" value="" onfocus="setBalance(this)" />
The JS onFocus handler is as follows:
function setBalance(e) //e should be an input field element
{
var balance = document.PaymentForm.balance.value;
var remainder = balance;
var index = 0;
var paymentField = document.getElementById('invoiceBalance'+index); //get the first input payment element
while (paymentField != null && paymentField != e) //start with the first field and calculate the remaining balance
{
var paymentApplied = paymentField.value.replace(/[^0-9\.]+/g,"");
remainder = remainder - paymentApplied;
index++;
paymentField = document.getElementById('invoiceBalance'+index);
}
while (e == paymentField) //set the selected elements value
{
var invoiceBalance = document.getElementById('in'+index).innerHTML.replace(/[^0-9\.]+/g,"");
if (parseFloat(remainder) > parseFloat(invoiceBalance))
e.value = parseFloat(invoiceBalance).toFixed(2).toLocaleString();
else
e.value = parseFloat(remainder).toFixed(2).toLocaleString();
index++;
paymentField = document.getElementById('invoiceBalance'+index);
}
while (paymentField != null) //blank out the rest of the input fields
{
paymentField.value = '';
index++;
paymentField = document.getElementById('invoiceBalance'+index);
}
e.select();
}
The concept here is to calculate the remaining balance and set the input field's value as the user focuses the fields.
The problem is that The "this" parameter is always set to the first Input element "invoiceBalance0". I'm expecting it to be set to the element referring to it in it's onFocus handler.
What am I not seeing?
I'm unable to duplicate the error you describe, but I did notice what appears to be a typo:
var invoiceBalance = document.getElementById('in'+index).innerHTML.replace(/[^0-9\.]+/g,"");
looks like it should be
var invoiceBalance = document.getElementById('invoiceAmount'+index).innerHTML.replace(/[^0-9\.]+/g,"");
function setBalance(e) //e should be an input field element
{
var balance = document.querySelector('[name="balance"]').value;
var remainder = balance;
var index = 0;
var paymentField = document.getElementById('invoiceBalance' + index); //get the first input payment element
while (paymentField != null && paymentField != e) //start with the first field and calculate the remaining balance
{
var paymentApplied = paymentField.value.replace(/[^0-9\.]+/g, "");
remainder = remainder - paymentApplied;
index++;
paymentField = document.getElementById('invoiceBalance' + index);
}
while (e == paymentField) //set the selected elements value
{
var invoiceBalance = document.getElementById('invoiceAmount' + index).innerHTML.replace(/[^0-9\.]+/g, "");
if (parseFloat(remainder) > parseFloat(invoiceBalance))
e.value = parseFloat(invoiceBalance).toFixed(2).toLocaleString();
else
e.value = parseFloat(remainder).toFixed(2).toLocaleString();
index++;
paymentField = document.getElementById('invoiceBalance' + index);
}
while (paymentField != null) //blank out the rest of the input fields
{
paymentField.value = '';
index++;
paymentField = document.getElementById('invoiceBalance' + index);
}
e.select();
}
<input type="hidden" name="balance" value="2500.0" />
<div id="invoiceAmount0">$500.00</div>
<input type="text" size="8" id="invoiceBalance0" name="invoiceBalance0" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount1">$500.00</div>
<input type="text" size="8" id="invoiceBalance1" name="invoiceBalance1" value="" onfocus="setBalance(this)" />
<div id="invoiceAmount2">$500.00</div>
<input type="text" size="8" id="invoiceBalance2" name="invoiceBalance2" value="" onfocus="setBalance(this)" />
It's work after changing this line :
var invoiceBalance = document.getElementById('in'+index).innerHTML.replace(/[^0-9\.]+/g,"")
To :
var invoiceBalance = document.getElementById('invoiceBalance'+index).innerHTML.replace(/[^
0-9\.]+/g,"");
that because you don't have an id like in[index] but this form invoiceBalance[index], hope that will help See
Working Fiddle.

Categories

Resources