Set Input Value then disable and move to next empty Input - javascript

Alright, this my be a tall order, but I am not making much headway, so I decided to ask for help.
I have a random array of names, and I would like to set these names to the HTML input, disable the HTML input with the value and move to the next one. Is that possible? and my second question is, is my randomGroup going to work, I mean, is all the 14 names be called?
all the help would be appreciated. - I am still working on it.
Here is a snippet:
var randomGroup = ["Luciano", "Patrick", "SHL", "Leo", "Marilyn", "Ranbir", "Helena", "Annie", "Saikaran", "Julie", "Albert" , "Chris", "Igor", "Staci"]
Array.prototype.randomElement = function(){
return this[Math.floor(Math.random() * this.length)]
}
var myRandomElement = randomGroup.randomElement();
/*console.log(myRandomElement);*/
function appendItem(){
var inputs = document.getElementByTagName('input').value = '';
var setInputs = document.getElementByTagName('input').innerHTML = myRandomElement;
/* myRandomElement = randomGroup.randomElement();*/
if (inputs == 0) {
inputs = setInputs;
}
}
appendItem();
body{
margin: 0 auto;
text-align: center;
}
div {
display: block;
margin-bottom: -10px;
}
#group1, #group2, #group3, #group4, #group5, #group6, #group7 {
display: inline-block;
}
<div>
<p id="group1">Group 1</p>
<input type="text" />
<input type="text" />
</div>
<div>
<p id="group2">Group 2</p>
<input type="text" />
<input type="text" />
</div>
<div>
<p id="group3">Group 3</p>
<input type="text" />
<input type="text" />
</div>
<div>
<p id="group4">Group 4</p>
<input type="text" />
<input type="text" />
</div>
<div>
<p id="group5">Group 5</p>
<input type="text" />
<input type="text" />
</div>
<div>
<p id="group6">Group 6</p>
<input type="text" />
<input type="text" />
</div>
<div>
<p id="group7">Group 7</p>
<input type="text" />
<input type="text" />
</div>

I'm not entirely sure what you're trying to achieve but here are some pointers:
There is no such function as getElementByTagName, it should be getElementsByTagName
getElementsByTagName returns a HTMLCollection. To access an element in this list you could do document.getElementsByTagName('input')[0]. This would get the first input.
This does absolutely nothing: if (inputs == 0) { inputs = setInputs; }

Your Mistakes
1.getElementsByTagName is correct . getElementByTagName doesn't exist.
2.When you get a array of elements you have to loop them to process.
3.To insert a value into a input feild you have to use value not innerHTML
FIX:(Only appenItem function has issue)
PURE JS Version Example
Note:jQuery version is commented in this fiddle
function appendItem() {
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
inputs[i].value = myRandomElement
}
}
jQuery Version
function appendItem() {
var inputs = document.getElementsByTagName('input');
$('input[type=text]').each(function (index, Obj) {
$(this).val(myRandomElement)
})
}

Related

Calc two fields and set results in third

I have a problem with the script.
I am trying to count two input fields, and insert the result into the third field.
But it doesn't work, and unfortunately I can't figure out what's wrong.
function sum() {
var txtFirstNumberValue = document.querySelectorAll('#firstID > div > div > div > input').value;
var txtSecondNumberValue = document.querySelectorAll('#second > div > div > div > input').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.querySelectorAll('#third > div > div > div > input').value = result;
}
}
<div id="firstID"><div>
<label>first</label>
<div>
<div>
<input name="drts[field_first][0]" type="number" value="" maxlength="255">
</div>
</div>
</div></div>
<div id="second"><div>
<label>second</label>
<div>
<div>
<input name="drts[field_second][0]" type="number" maxlength="255">
</div>
</div>
</div></div>
<div id="third"><div>
<label>third</label>
<div>
<div>
<input name="drts[field_third][0]" type="number" value="" maxlength="255">
<div></div>
</div>
</div>
</div></div>
There are a few problems here.
Are you actually calling sum? I've added a call in the example code so you can run it.
Your query selectors are not right. There isn't actually anything in the divs with the IDs you query. I've moved the input boxes into the correct places. When debugging, you should check that you are actually finding elements in your querySelectorAll call before proceeding.
querySelectorAll doesn't have a value property. You would need to iterate over each element before getting the items. Given you specifically want one item, it would be better to use something more specific like getElementById. I've kept the original querySelectorAll but changed the IDs on the divs to classes so we can have more than one result for this example. Then, I iterate over them pulling out the value to add to result. I've moved the parseInt to the running calculation otherwise it would perform a string concatenation.
Even better than the above would be to access the input directly. There's probably no point accessing a div and drilling down to the input. I've included this example to output the result.
I've removed redundant html. It's not related to the answer but try to keep your markup clean.
function sum() {
var inputElements = document.querySelectorAll('.user-input > div > div > input');
var result = 0;
inputElements.forEach(element => {
result += element.value ? parseInt(element.value) : 0
})
document.getElementById('third').value = result
}
document.getElementById('run-button').addEventListener('click', sum)
<div class="user-input">
<label>first</label>
<div>
<div>
<input name="drts[field_first][0]" type="number" maxlength="255">
</div>
</div>
<div>
<div class="user-input">
<label>second</label>
<div>
<div>
<input name="drts[field_second][0]" type="number" maxlength="255">
</div>
</div>
<div>
<label>third</label>
<div>
<div>
<input id="third" name="drts[field_third][0]" type="number" value="" maxlength="255">
<div></div>
</div>
</div>
<div>
<button type="button" id="run-button">Run</button>
Try like this
function sum() {
let txtFirstNumberValue = document.querySelector('#firstID input').value;
let txtSecondNumberValue = document.querySelector('#second input').value;
let result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.querySelector('#third input').value = result;
} else {
document.querySelector('#third input').value = '';
}
}
<div id="firstID"><div>
<label>first</label>
<div>
<div>
<input name="drts[field_first][0]" type="number" value="" maxlength="255">
</div>
</div>
</div></div>
<div id="second"><div>
<label>second</label>
<div>
<div>
<input name="drts[field_second][0]" type="number" maxlength="255">
</div>
</div>
</div></div>
<div id="third"><div>
<label>third</label>
<div>
<div>
<input name="drts[field_third][0]" type="number" value="" maxlength="255" disabled>
<div></div>
</div>
</div>
<div>
<button id="button" onclick="sum()">Calculate</button>
</div>
</div>
</div>
const input1 = document.querySelector('#input1');
const input2 = document.querySelector('#input2');
const input3 = document.querySelector('#input3');
const storeInputs = [input1, input2];
for(let i = 0; i < storeInputs.length; i++) {
storeInputs[i].addEventListener('input', function() {
// multiply input1 and input2 with 1 for converting there values from string to number
input3.value = input1.value * 1 + input2.value * 1;
});
};
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<label for="input1">First Input</label>
<input id="input1" type="number" value="0"></input>
<label for="input2">Second Input</label>
<input id="input2" type="number" value="0"></input>
<label for="input3">Third Input</label>
<input id="input3" type="number" value="0"></input>
</body>
</html>

Custom jQuery validation for duplicated repeating fields inside each container in one form

I'm trying to check if there are duplicated values for specific input field which is repeating inside each containing element.
The filed should be considered as a "duplicate" only if has the same value with other comparing field(s) and sharing the same parent container, which means the field can have the same value in 2 or more different containers. I now it sounds a bit confusing but I will add the markup and the current jQuery code so hopefully it will be more clear.
var attendees_group = $('.attendee-accordion-group'),
inputs = attendees_group.find('input[name*="_attendeeemail"]');
inputs.change(function(e) {
//Create array of input values
var ar = inputs.map(function() {
if ($(this).val() != '') return $(this).val()
}).get();
//Create array of duplicates if there are any
var unique = ar.filter(function(item, pos) {
return ar.indexOf(item) != pos;
});
console.log(unique.length);
//if duplicates
if (unique.length != 0) {
//do something
}
});
body {
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
font-size: 14px
}
h3 {
display: block;
margin: 0 0 15px 0;
font-size: 18px;
}
h4 {
padding: 0;
margin: 0 0 15px 0;
font-size: 15px;
}
form {
padding: 20px;
}
.attendee-accordion-group {
padding: 40px;
border: 1px solid #999;
margin-bottom: 20px;
}
input {
border: 1px solid #ccc;
width: 50%;
line-height: 1;
height: 20px;
}
.button {
display: inline-block;
background: #0274be;
color: #fff;
padding: 10px 30px;
text-decoration: none;
border: none;
cursor: pointer;
margin-bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
<h3>Event Title 1</h3>
<div class="attendee-accordion-group">
<h4>Attendee 1</h4>
<div class="attendee-panel">
<p>
<label for="field_attendeename_1__1" class="">Name</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeename_1__1" id="field_attendeelastname_1__1" value="">
</span>
</p>
<p>
<label for="field_attendeeemail_1__1" class="">Email</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeeemail_1__1" id="field_attendeeemail_1__1" value="">
</span>
</p>
</div>
<h4>Attendee 2</h4>
<div class="attendee-panel">
<p>
<label for="field_attendeename_1__2" class="">Name</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeename_1__2" id="field_attendeelastname_1__2" value="">
</span>
</p>
<label for="field_attendeeemail_1__2" class="">Email</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeeemail_1__2" id="field_attendeeemail_1__2" value="">
</span>
</p>
</div>
<h4>Attendee 3</h4>
<div class="attendee-panel">
<p>
<label for="field_attendeename_1__3" class="">Name</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeename_1__3" id="field_attendeelastname_1__3" value="">
</span>
</p>
<p>
<label for="field_attendeeemail_1__3" class="">Email</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeeemail_1__3" id="field_attendeeemail_1__3" value="">
</span>
</p>
</div>
</div>
<h3>Event Title 2</h3>
<div class="attendee-accordion-group">
<h4>Attendee 1</h4>
<div class="attendee-panel">
<p>
<label for="field_attendeename_2__1" class="">Name</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeename_2__1" id="field_attendeelastname_2__1" value="">
</span>
</p>
<p>
<label for="field_attendeeemail_2__1" class="">Email</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeeemail_2__1" id="field_attendeeemail_2__1" value="">
</span>
</p>
</div>
<h4>Attendee 2</h4>
<div class="attendee-panel">
<p>
<label for="field_attendeename_2__2" class="">Name</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeename_2__2" id="field_attendeelastname_2__2" value="">
</span>
</p>
<p>
<label for="field_attendeeemail_2__2" class="">Email</label>
<span class="input-wrapper">
<input type="text" class="input-text" name="field_attendeeemail_2__2" id="field_attendeeemail_2__2" value="">
</span>
</p>
</div>
</div>
<button type="button" class="button">Next</button>
</form>
<div class="error">
</div>
OK, so, the container is a div with a class .attendee-accordion-group, and inside, each text field labeled email, should be unique. I hope this clarifies issue a bit.
I used the js code for comparing field values from this answer
Right now all the "email" fileds, no matter of container are duplicates if values are the same, I was wondering if someone can help me with this.
If I understood you correctly, you are wanting to catch duplicates of the same input values in each "group" or each "event" in your example.
Here is something I put together that does just that. It will need some more adjustments like only outputting one error message for each duplicate value, instead of two. In the linked jsFiddle example, the validation only takes place on load, and not when the "Next" button is pressed. But this should push you in the correct position.
I added comments to the code to help you understand is going on.
jsFiddle: https://jsfiddle.net/mgqucrsz/1/
// will hold all the duplicate error message
var errorMessage = '';
// loops through each "group"
$('.attendee-accordion-group').each(function() {
// will hold all input values and names of each "group"
var inputs = [];
// loops through all inputs of the current group
$(this).find('input').each(function() {
// saves the value and name of each input for the current group
var input = {'name':$(this).attr('name'), 'value':$(this).val()};
// saves the current input/name into a growing list of inputs for this current group
inputs.push(input);
});
// loops through the inputs list generated in the previous loop for this group
for (var i = 0; i < inputs.length; i++) {
// shortens the reference to the current input
var input = inputs[i];
// returns the input that is duplicated
// 1. Loops though the inputs list
// 2. If the current index of the current input does not match the index of the item being looked up; in other words this will ignore itself, since matching with itself is technically a match
// 3. If the current input value matches with the looked up input
// 4. "&& item.value" makes sure that an input value exists, since empty values technically match with other empty values
var conflict = inputs.find(function(item) {return inputs.indexOf(item) !== i && item.value === input.value && item.value;});
// if conflict is not undefined; would be undefined if no duplicates were found
if (conflict) {
// append this error message to a growing error message
errorMessage += 'Value of form name ' + input.name + ' already exists on form name ' + conflict.name + '.<br>\n';
}
}
});
// finally output the error message
$('div.error')[0].innerHTML += errorMessage;

JS - Change the text depending on the user's input

First of all, sorry if the question seems really dumb, I'm not really used to Javascript.
I'm looking for a script changing some text depending on what the user wrote. Here's what I'm looking for :
There is 3 inputs (A, B and C) for 1 Text.
The "Text" will show the addition of A, B and C.
Example : Input A is 3, B is 5, C is 10. Text = 18.
I got some script ready, but it's only the "bones" of the script..
function ShowPointsNeeded(text){
document.getElementById("result").innerHTML =text; }
#result {
height:50px;
width:50px;
border:1px solid #999;
font-size:25px;
text-align:center;
margin-left:15px;
}
<div id="text">
<input id="slide" type="text" value=""
onchange="ShowPointsNeeded(this.value);" />
</div>
<div id="result"></div>
-> It's just a basic script, showing the content of the input in a little box. Now, what I would like to have is 3 inputs and the little box to show the addition of them.
Thanks !
If want to calculate sum, of all inputs then you can use below logic :
function ShowPointsNeeded(){
//while doing calculation you have to consider all textboxes every time,
//so you have to derive a way to get all your related textboxes at once,
//e.g. : i have use name attribute to make all input boxes relate to each
//other.
var allInputs = document.getElementsByName("numbers");
var sum=0.0;
for(var i=0;i<allInputs.length;i++){
if(allInputs[i].value.length>0)
sum= sum+parseFloat(allInputs[i].value);
//parsing float because user can input decimals as well
}
document.getElementById("result").innerHTML=sum;
}
<div id="text">
<input id="slide" type="text" value="" name="numbers"
onchange="ShowPointsNeeded();" />
<input id="slide" type="text" value="" name="numbers"
onchange="ShowPointsNeeded();" />
<input id="slide" type="text" value="" name="numbers"
onchange="ShowPointsNeeded();" />
</div>
<div id="result" style="height:50px;width:50px;border:1px solid #999; font-size:25px; text-align:center; margin-left:15px;"></div>
you will need to sum all input values every time ShowPointsNeeded() is called. you can use reduce() for this.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function ShowPointsNeeded(){
document.getElementById("result").innerHTML = $('input').toArray().reduce((acc,cur) => acc + Number(cur.value), 0);
}
</script>
<div id="text">
<input id="slide1" type="text" value=""
onchange="ShowPointsNeeded();" />
<input id="slide2" type="text" value=""
onchange="ShowPointsNeeded();" />
<input id="slide3" type="text" value=""
onchange="ShowPointsNeeded();" />
</div>
<div id="result" style="height:50px;width:50px;border:1px solid #999; font-size:25px; text-align:center; margin-left:15px;"></div>
JavaScript Number() function for convert from text to number:
function ShowPointsNeeded() {
var values = [];
var elements = document.getElementsByTagName('input');
for (var i = 0; i < elements.length; i++) {
values.push(elements[i].value);
}
var sum = values.reduce(sumElements, 0);
var resultElement = document.getElementById("result");
resultElement.innerHTML = sum;
}
function sumElements(total, num) {
return Number(total) + Number(num);
}
<div id="text">
<input type="text" value="" onchange="ShowPointsNeeded(this);" />
<input type="text" value="" onchange="ShowPointsNeeded(this);" />
<input type="text" value="" onchange="ShowPointsNeeded(this);" />
</div>
<div id="result" style="height:50px;width:50px;border:1px solid #999; font-size:25px; text-align:center; margin-left:15px;"></div>
For inputs don't needs id attribute.

duplicate and clone div

sorry i do not speak english well, i want to create a tool that allows to duplicate a div thanks to an "input number" and a button and then I also want to clone this tool by reinitializing it to be able to use the tool again , Here is a piece of code:
$(function() {
$('#btn_dupliquate').on('click', function() {
var numDuplication = $('#num-duplication').val();
if (numDuplication > -1) {
var div = $('.common_preview');
$('.result').html('');
for (var i = 0; i < numDuplication; i++) {
$('.result').append(div.clone());
}
}
});
});
$(function() {
$(".heading").keyup(function() {
var heading=$(this).val();
$(".common_preview").html("<div class='bloc'><p class='model'>"+heading+"</p></div>");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toNumDuplicate">
<input type="text" class="heading" />
<br/>
<br/>
<input id="num-duplication" type="number" >
<br/>
<br/>
<button id="btn_dupliquate"> dupliquate </button>
</div>
<div id="toDuplicate">
<div class="common_preview" >
<div class="bloc">
<p class="model">test</p>
</div>
</div>
</div>
<div class="result"></div>
<button id="btn_clone">clone</button>
You could abstract your function to take dynamic selector strings for the duplicate button, duplicate number input, preview div and result div.

Check if input text is filled and display different divs

I have 3 input text and I want to display a div if one over 3 is filled, a different div if 2 input over 3 are filled and so on. How can I do it with javascript?
<input type="text" id="text1" name="text1" />
<input type="text" id="text2" name="text2" />
<input type="text" id="text3" name="text3" />
I tried this but it doesn't work
function display() {
if ($('#text').val() != '') {
document.getElementById('green').style.display = 'block';
}   
}
CSS
#a, #b, #c {
visibility:hidden;
}
HTML
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
JavaScript
var istext1filled = document.querySelector('input#text1').value.length>0;
var istext2filled = document.querySelector('input#text2').value.length>0;
var istext3filled = document.querySelector('input#text3').value.length>0;
if(istext1filled) {
document.querySelector('div#a').style.visibility = 'visible';
}
if(istext2filled) {
document.querySelector('div#b').style.visibility = 'visible';
}
if(istext3filled) {
document.querySelector('div#c').style.visibility = 'visible';
}
I think there's a misunderstanding here. #Domenico asked
I have 3 input text and I want to display a div if one over 3 is filled, a different div if 2 input over 3 are filled and so on.
If I am not misunderstanding his statement: I think he is talking about the number of inputs that were filled and not necessarily the particular input that was filled.
Hence JSFiddle:
#div_1, #div_2, #div_3{
display: none;
}
<input type="text" id="text_1" name="text1" value="" />
<input type="text" id="text_2" name="text2" value=""/>
<input type="text" id="text_3" name="text3" value="" />
<div id="div_1">Only ONE input is filled</div>
<div id="div_2">Only TWO inputs are filled</div>
<div id="div_3">All THREE inputs are filled</div>
$(document).ready(function() {
$("input[id*='text']").blur(function() {
var counter=0;
$("input[id*='text']").each(function(ind, val){
if($(val).val().trim()!==""){
counter++;
}
});
$("#div_1, #div_2, #div_3").hide();
$("#div_"+counter).show();
});
});
But if you want it the other way round, here is the solution too:
#div_1, #div_2, #div_3{
display: none;
}
<input type="text" id="text_1" name="text1" value="" />
<input type="text" id="text_2" name="text2" value=""/>
<input type="text" id="text_3" name="text3" value="" />
<div id="div_1">Input ONE is filled</div>
<div id="div_2">Input TWO is filled</div>
<div id="div_3">Input THREE is filled</div>
$(document).ready(function() {
$("input[id*='text']").blur(function() {
$("#div_1, #div_2, #div_3").hide();
$("input[id*='text']").each(function(ind, val) {
if ($(val).val().trim() !== "") {
console.log("div_"+$(val).prop("id").split("_")[1])
$("#div_"+$(val).prop("id").split("_")[1]).show();
}
});
});
});

Categories