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

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.

Related

JavaScript function not working as desired

I'm working with HTML, JavaScript and CSS. The function objective is to create a border-radius attribute in a div element(id="surface"), and assign the value typed in inputs texts(class="chars_1") to it.
HTML
<div id="container">
<div class="input_wrapper" id="input_wrapper_tl">
<input type="text" id="input_tl" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_tr">
<input type="text" id="input_tr" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_br">
<input type="text" id="input_br" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_bl">
<input type="text" id="input_bl" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div id="surface">
<textarea id="code" readonly="readonly"></textarea>
<div id="options">
<input type="checkbox" checked="true" id="opt_webkit">
<label for="opt_webkit"> Webkit</label>
<input type="checkbox" checked="true" id="opt_gecko">
<label for="opt_gecko"> Gecko</label>
<input type="checkbox" checked="true" id="opt_css3">
<label for="opt_css3"> CSS3</label>
</div>
</div>
JavaScript Function
function changeSize(){
var surface = document.getElementById("surface");
var inputs = document.getElementsByClassName("chars_1");
var total = 0;
for(var x = 0; x == 3; x++){
total += Number(inputs[x].value);
}
surface.style.borderRadius = String(total)+"px";
}
First I selected both elements and assigned it to these 2 variable "surface" and "inputs". "total" being used in the "for structure" to go through every input element and select every value, and afterward convert to Number to the "total" variable.
The idea is to assign to the border-radius attribute the total variable value, which will be converted to a string so it can be recognized as a value.
Have a border
Fix the for loop for (var x = 0; x < inputs.length; x++) {
Here is an upgraded version
const changeSize = (e) => {
const tgt = e.target; // which input
if (tgt.classList.contains("chars_1")) { // ah, one of those
let total = [...document.querySelectorAll(".chars_1")].reduce(
(sum, input) => {
const val = input.value;
sum += val.trim() === "" || isNaN(val) ? 0 : +val; // only add if a number
return sum;
}, 0);
console.log(String(total) + "px")
document.getElementById("surface").style.borderRadius = String(total) + "px";
}
};
window.addEventListener("load", () => { // when page loads
document.getElementById("container").addEventListener("input", changeSize);
});
#surface {
border: 3px solid black;
}
<div id="container">
<div class="input_wrapper" id="input_wrapper_tl">
<input type="text" id="input_tl" class="chars_1" value="0">
</div>
<div class="input_wrapper" id="input_wrapper_tr">
<input type="text" id="input_tr" class="chars_1" value="0">
</div>
<div class="input_wrapper" id="input_wrapper_br">
<input type="text" id="input_br" class="chars_1" value="0">
</div>
<div class="input_wrapper " id="input_wrapper_bl ">
<input type="text" id="input_bl " class="chars_1" value="0">
</div>
<div id="surface">
<textarea id="code" readonly="readonly"></textarea>
<div id="options">
<input type="checkbox" checked="true" id="opt_webkit">
<label for="opt_webkit"> Webkit</label>
<input type="checkbox" checked="true" id="opt_gecko">
<label for="opt_gecko"> Gecko</label>
<input type="checkbox" checked="true" id="opt_css3">
<label for="opt_css3"> CSS3</label>
</div>
</div>
for(var x = 0; x == 3; x++)
that loop doesn't even execute,
change x==3 on x<3 or whatever you want to achive.
And I guess you must have border to change it's radious

How to create the below htm code dynamically

I need the below code to be generated dynamically
<div class="app" style="display:none">
<input id="application" type="radio" name="choice" value="Albert">
<label>Albert</label>
<input id="application" type="radio" name="choice" value="Huston">
<label>Huston</label>
</div>
<div class="marks" style="display:none">
<input id="subject" type="radio" name="choice" value="ten">
<label>10</label>
<input id="subject" type="radio" name="choice" value="twelve">
<label>12</label>
</div>
The class, id, value and the string between the label are to be dynamically added. I will be getting these values from a for loop, which I am iterating over the rows in a table. Please help.
Maybe like this:
var first={
class:'app',
id:'application',
values:[['Albert', 'Albert'],['Huston', 'Huston']]
};
var second={
class:'marks',
id:'subject',
values:[['ten', 10],['twelve', 12]]
};
function add_dynamic_al(_obj){
var div=$('<div/>');
div.addClass(_obj.class);
//div.hide(); //if need display:none
var lbl1=$('<label/>');
var inp1=$('<input/>');
inp1.attr({'id':_obj.id, 'type':'radio', name:'choice',}).val(_obj.values[0][0]);
lbl1.append(inp1).append(_obj.values[0][1]); //for structure '<label><input />name</label>'
div.append(lbl1);
var lbl2=$('<label/>');
var inp2=$('<input/>');
inp2.attr({'id':_obj.id, 'type':'radio', name:'choice',}).val(_obj.values[1][0]);
lbl2.append(inp2).append(_obj.values[1][1]);
div.append(lbl2);
$('body').append(div);
}
div{
display:inline-block;
border-style:solid;
border-width:2px;
border-color:gray;
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="add first element" onclick="add_dynamic_al(first);" />
<input type="button" value="add second element" onclick="add_dynamic_al(second);" />
Perhaps this is what you need:
var my_obj=[{
class:'app',
id:'application',
values:[['Albert', 'Albert'],['Huston', 'Huston']]
},{
class:'marks',
id:'subject',
values:[['ten', 10],['twelve', 12]]
}];
function create_dynamic_el_from_obj_arr(_obj_arr){
for(var key in _obj_arr){
var cur_el=_obj_arr[key];
var div=$('<div/>');
div.addClass(cur_el.class);
//div.hide(); //if need display:none
var cur_el_values=_obj_arr[key].values;
for(var kv in cur_el_values){
var lbl=$('<label/>');
var inp=$('<input/>');
inp.attr({'id':cur_el.id, 'type':'radio', name:'choice',}).val(cur_el_values[kv][0]);
lbl.append(inp).append(cur_el_values[kv][1]);
div.append(lbl);
}
$('body').append(div);
}
}
div{
display:inline-block;
border-style:solid;
border-width:2px;
border-color:gray;
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" value="add all element" onclick="create_dynamic_el_from_obj_arr(my_obj);" /><br/>

How to set paragraph to textbox text

Let us say I have an HTML form, with two textboxes, I want to add the two numbers in the two textboxes and display the result in a paragraph. How can I do that?
Change paragraph according to textbox is what I can't find!
Very simple:
document.getElementById('sum').onsubmit = add;
function add(e) {
e.preventDefault();
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var result = 'Result: ' + String(parseInt(num1) + parseInt(num2));
var p = document.getElementById('result');
p.innerHTML = result;
}
<form id="sum">
<label for="num1">First number:</label>
<br />
<input type="text" id="num1" />
<br />
<label for="num1">Second number:</label>
<br />
<input type="text" id="num2" />
<br />
<input type="submit" value="Add" />
</form>
<p id="result">Result:</p>
In the html we have a form with 3 inputs, 2 are type text and one is type submit. and also a paragraph.
In the javascript we assign to the form's onsumbit event the function add(), in the function we prevent the default so the form wont refresh the page, then we get the 2 values that were inputed, create a string that would contain the sum of those values and set the paragraph's innerHTML to it.
Create a calculator function and then you can fire it on keyup or you can assign it to a button if you'd like.
function calcTotal(){
var inputs = document.getElementsByTagName('input'),
result = 0;
for(var i=0;i<inputs.length;i++){
if(parseInt(inputs[i].value))
result += parseInt(inputs[i].value);
}
document.getElementById('total').innerHTML = 'Total: ' + result;
}
<form>
<input onkeyup="calcTotal()" type="text" />
<input onkeyup="calcTotal()" type="text" />
</form>
<p id="total"></p>
follow bellow JS code:
<html>
<head>
<title>Sum Two Number</title>
<script language="javascript">
function addNumbers()
{
var val1 = parseInt(document.getElementById("value1").value);
var val2 = parseInt(document.getElementById("value2").value);
if(val1 !== "" && val2 !== "") {
var result = val1 + val2;
document.getElementById('result').innerHTML = result;
}
}
</script>
</head>
<body>
value1 = <input type="text" id="value1" name="value1" value="0" onkeyup="javascript:addNumbers()"/>
value2 = <input type="text" id="value2" name="value2" value="0" onkeyup="javascript:addNumbers()"/>
<p>Answer = <span id="result"></span></p>
</body>
</html>
In this example, you have a form with 2 input. When you press on a button, the value of those 2 input is added inside a paragraph.
Hope this help.
function addInputContentToParagraph() {
var txtValue1 = document.getElementById('textbox1').value;
var txtValue2 = document.getElementById('textbox2').value;
document.getElementById('para').innerHTML = txtValue1 + ' ' + txtValue2;
}
a {
cursor:pointer;
border:1px solid #333;
padding:4px;
margin:10px;
display:inline-block;
}
<form id="myForm" name="myForm">
<input type="text" name="textbox1" id="textbox1" value="1">
<input type="text" name="textbox2" id="textbox2" value="2">
</form>
<a onclick="addInputContentToParagraph();">Add Input Values to Paragraph</a>
<p id="para"></p>

Set Input Value then disable and move to next empty Input

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)
})
}

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