I have Input section like i want to pass this 3 value in one input value with onchange
<script type="text/javascript">
function updateInput($i){
$('updateval').val($i);
}
</script>
<input type="text" onchange="updateInput(this.value)" >
<input type="text" onchange="updateInput(this.value)" >
<input type="text" onchange="updateInput(this.value)" >
<input type="text" id="updateval" >
i want to show here the all 3 value and with a seperation
like value1:value2:value3
in my last input section
Give the 3 input id not name, eg v1,v2,v3
onchange jquery those 3 input value. $('#updateval').val( [ $('#v1').val(),$('#v2').val(),$('#v3').val()].join(':'));
You're missing the position of source input on your function.
Input without name not passed in form submitted, except you send itvia coding.
<input type="text" class='val' >
<input type="text" class='val' >
<input type="text" class='val' >
<input type="text" id="updateval" >
<script>
$(document).ready(function(){
$('.val').on('keyup',function(){
let out=''
$(".val").each(function() {
out+= $(this).val()+":";
});
$('#updateval').val(out);
})
})
</script>
fiddle
<script type="text/javascript">
function updateInput(){
var val1 = $('#value1').val();
var val2 = $('#value2').val();
var val3 = $('#value3').val();
var output = val1 + ':' + val2 + ':' + val3
$('#updateval').val(output);
}
</script>
<input id="value1" type="text" Onkeyup="updateInput(this.value)" >
<input id="value2" type="text" Onkeyup="updateInput(this.value)" >
<input id="value3" type="text" Onkeyup="updateInput(this.value)" >
<input type="text" id="updateval" value="">
Fiddle
Details commented in demo.
// Reference the first form on page
const form = document.forms[0];
/*
Register form to the input event (or change event with .onchange)
The input event will fire immediately after the user has entered any data
The change event will fire when the user has entered data then triggers a blur event by
focusing elsewhere.
*/
form.oninput = display;
/*
//A Pass Event Object
/*
B1 event.currentTarget is the tag registered to event (form)
B2 .elements.text is a collection of all the form controls [name=text] (inputs)
B3 brackets and spread operator convert collection into an array [...all input]
B4 .map() returns each input value into an array
*/
/*
//C Get output.all and assign its value to the new array then convert it into a string
delimited by colons
//D End function
*/
function display(event) {//A
let texts = [...event.currentTarget.elements.text].map(txt => txt.value);//B1-4
event.currentTarget.elements.all.value = texts.join(':');//C
return false;//D
}
:root {
font: 400 5vw/1.2 Consolas
}
input,
output {
display: block;
font: inherit
}
<form>
<input name='text'>
<input name='text'>
<input name='text'>
<output name='all'></output>
</form>
Related
I have created 5 input text boxes using HTML and made a button while clicking the button the values will print the result input text box. The first 4 fields are my inputs and the last text field is my output. unable to debug the issue. kindly find the code and help to find the issue.
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(h+w+g+t);
document.getElementById('result').innerHTML=total;
}
<h2> Calculator</h2>
<input type="text" placeholder="value1" id="h">
<input type="text" placeholder="value2"id="w">
<input type="text" placeholder="value3" id="g">
<input type="text" placeholder="value4" id="t">
<input type="text" placeholder="result" id="result">
<!--
<p
id="result">
</p>
-->
<button id="btn" onClick="JS()">Calculate</button>
There are two keys to resolving your issue:
Coerce your inputs to numbers, which I'm doing by adding a + in front of the value assignments. If you don't do this, your values may be treated like strings and concatenated rather than added like numbers.
Set the value of the input element, not the innerHTML. If you'd rather use a <p> element, which it appears you commented out in your sample code (and which I restored for completeness of my answer), consider using innerText.
See example here:
function JS() {
var h = +document.getElementById('h').value;
var w = +document.getElementById('w').value;
var g = +document.getElementById('g').value;
var t = +document.getElementById('t').value;
let p_result = document.getElementById('p_result');
var total = (h + w + g + t);
document.getElementById('result').value = total;
p_result.innerText = total;
}
<h2> Calculator</h2>
<input type="text" placeholder="value1" id="h">
<input type="text" placeholder="value2" id="w">
<input type="text" placeholder="value3" id="g">
<input type="text" placeholder="value4" id="t">
<input type="text" placeholder="result" id="result">
<br>
<p id="p_result" style="color:red;"></p>
<br>
<button id="btn" onClick="JS()">Calculate</button>
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(Number(h)+Number(w)+Number(g)+Number(t));
document.getElementById('result').value =total;
}
.value instead of .innerHTML
also, you should convert inputs values to number cause instead of making the sum will be as consider them string( for example if you type 1 , 2 , 3 , 4 without converting to number will be 1234 if you convert to number will be 10
Currently it only adds the value once. I have a list of dropdowns(per this example its just input values that u can manually change) that I change from time to time. When clicking 'add' button, it should carry those values over to the field_wrapper, while dynamically adding new input fields to carry each value.
Meaning, I want it to add each new value selected from "text" and append to each new input text field!
I set the global variables above the function. But not sure why the value only shows up one time, and doesn't add new values each time I click 'add'
I hope this makes sense!
Javascript
// Dynamically Add More Input Fields after Add Button //Add to cart
var maxNum= 20;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<div><input type="text" id="test" value=""/><img src="remove-icon.png"/></div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxNum){
x++;
var cartID = $('#cID').val(),
cartd = $('#dID').val(),
cartP = $('#price').val()
text=cartID + cartD+ cartP;
$(wrapper).append(field)
$('#test').val(text)
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
});
HTML
<input name="cID" class="form-control" type="text" id="cID" value="">
<input name="dID" class="form-control" type="text" id="dID" value="">
<input name="price" class="form-control" type="text" id="price" value="">
<div class="field_wrapper">
</div>
Nothing to do more simply interpolate the html and add text variable as value of id="test" but it is better to use class instead of id.
// Dynamically Add More Input Fields after Add Button //Add to cart
var maxNum= 20;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxNum){
x++;
var cartID = $('#cID').val(),
cartd = $('#dID').val(),
cartP = $('#price').val()
text=cartID + cartd + cartP;
$(wrapper).append(`<div><input type="text" id="test" value="${text}"/><img src="remove-icon.png"/></div>`)
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="cID" class="form-control" type="text" id="cID" value="">
<input name="dID" class="form-control" type="text" id="dID" value="">
<input name="price" class="form-control" type="text" id="price" value="">
<div class="field_wrapper">
<button class="add_button">Add</button>
</div>
I can't figure out why this function is not working. Assignment instructions call for the javascript function code to be in it's own javascript file.
Here is the html
<h2>BMI Calculator</h2>
<form>
<input type="text" id="weight" value="0" />
<label for="weight">Weight in pounds</label>
<input type="text" id="height" value="0" />
<label for="height">Height in inches</label>
<input type="text" id="Result" value="0" />
<label for="Result"> BMI Result </label>
<input type="submit" id="submit" value="Calculate BMI" />
</form>
Here is the function based on that form. It's supposed to calculate the bmi.
function calcBMI() {
var weight = parseInt(document.getElementByID("weight").value);
var height = parseInt(document.getElementByID("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result').value;
textbox.value = result;
}
document.getElementById("submit").addEventListener("click", calcBMI, false);
3 things:
getElementById must be in camel case. Not with capital D's at the end
Reference to textbox should be just var textbox = document.getElementById('Result') and not with .value at the end.
Button's type should be button otherwise the form is being posted.
Your working example:
function calcBMI() {
var weight = parseInt(document.getElementById("weight").value);
var height = parseInt(document.getElementById("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result');
textbox.value = result;
}
document.getElementById("submit").addEventListener("click", calcBMI, false);
<h2>BMI Calculator</h2>
<form>
<input type="text" id="weight" value="0" />
<label for="weight">Weight in pounds</label>
<input type="text" id="height" value="0" />
<label for="height">Height in inches</label>
<input type="text" id="Result" value="0" />
<label for="Result"> BMI Result </label>
<input type="button" id="submit" value="Calculate BMI" />
</form>
1.
At a glance it seems as though you are not preventing the default browser behaviour, you need to use event.preventDefault() to prevent the form submitting.
function [...](e) {
e.preventDefault();
[...]
}
2.
Ensure you DOM has loaded before manipulation begins by loading the JavaScript below the HTML or you can make use of the DOMContentLoaded event.
3.
A sanity check, ensure that the script has been loaded using the <script></script> tags. If it is an external file, use the src property, if it is just code, wrap it in the aforementioned tags.
4.
You need to change the usage of getElementById you have used getElementByID instead of the lowercase d in Id.
5.
When you are doing textbox.value = result; what you are actually doing is textbox.value.value = result; as you have referenced it as .value originally.
Finally,
Make use of the console as it'll have saved you from asking here as the errors are thrown in them.
There are few problems with your function:
You have a typo in document.getElementByID, it should be document.getElementById
You have to pass an event object into your function, and invoke preventDefault, so that your form won't be submitted to the server
the line:
var textbox = document.getElementById('Result').value;
it should be
var textbox = document.getElementById('Result');
So overall, your function should look like:
function calcBMI(e) {
e.preventDefault();
var weight = parseInt(document.getElementById("weight").value);
var height = parseInt(document.getElementById("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result');
textbox.value = result;
}
Use on click event, change your getElementByID to getElementById and change the type to button and not submit. Submit would post it but what you need is to call the function.
<input type="button" id="submit" value="Calculate BMI" onclick="calcBMI()"/>
In your javascript change
var textbox = document.getElementById('Result').value
To
var textbox = document.getElementById('Result').value = result;
And remove
textbox.value = result;
You made a mistake here in weight and heightIt should be in camel case only.
document.getElementById("your id")
and also why not you check in console what error it shows
I have 4 input fields next to eachother.
I'm trying to force the user to enter 1 character per input field and as soon as they entered 1 character, they need to enter the next character into the next field until the inputs finish.
However my current code is al over the place and I can't figure out what I need to do to achieve this.
This is my code:
https://jsfiddle.net/ej9tvosj/
$('.inps').keydown(function (event) {
// check for hyphen
var myLength = $(this).val().length;
if(myLength ==0){
$(this).next('.inps').focus();
}
});
if you enter something in the first one, it will jump into the next field but it will get messed up there after.
Could someone please advice on this issue?
You need to try on input listener to detect change in input instead of keyup since you need to ensure that a character is entered before changing focus.
$(document).on('input', '.inps', function (event) {
// check for hyphen
var myLength = $(this).val().trim().length;
if(myLength ==1){
$(this).next('.inps').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
You can compare the myLength value with 1 like in the code snippet below:
$('.inps').keydown(function (event) {
// check for hyphen
var myLength = $(this).val().length;
if(myLength ==1){
$(this).next('.inps').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
I have a form with a bunch of inputs. Sometimes the form will have 1 input and sometimes up to 10 inputs. When someone fills out each input I want a tag field at the bottom to be populated also. Right now I have it working but only with a set number of inputs. (3 at the moment).
Im trying to figure out how to make it work regardless of how many inputs there are on the page.
HTML
Input1 <input id="input1" name="input1" type="text" value="" />
<br/>
Input2 <input id="input2" name="input2" type="text" value="" />
<br/>
Input3 <input id="input3" name="input3" type="text" value="" />
<br/>
<p>List of inputed text</p>
<span id="allInputs"></span>
Jquery
$("#input1,#input2,#input3").change(function () {
var inputArray = [$("#input1").val(), $("#input2").val(), $("#input3").val()];
$("#allInputs").text(inputArray.join(' '));
});
A nice to have also would be putting them into another input instead of a span and adding a comma after each one except for the last one.
I know Im probably missing something very simple here.
In your example you are only allowing for 3 inputs as you have 3 input boxes, when any of those input boxes change your tags are then being transferred to the span.
Now it sounds like you wish to allow for multiple entries regardless of how many inputs. You could try something simple such as the below fiddle.
http://jsfiddle.net/K2g4z/
Html:
<div>
<strong>Enter your tag and click add</strong>
<br/>
<input type="text" id="tagEntry" />
<button id="tagAdd">Add</button>
</div>
<div>
<strong>Entered Tags</strong>
<br/>
<input type="text" id="tagsEntered" />
</div>
Javascript:
var tags = [];
$(function() {
$('#tagAdd').click(function(){
//get the tag value and trim the spaces
var tVal = $('#tagEntry').val().trim();
if(tVal == '')
return;
//reset the entry box
$('#tagEntry').val('');
//verify tag not already saved
for(var i=0;i<tags.length;i++)
if(tags[i] == tVal)
return;
//add the tag to the array
tags.push(tVal);
//set the tags entry box
$('#tagsEntered').val(tags.join(', '));
});
});
UPDATE:
The JSFiddle link http://jsfiddle.net/K2g4z/1/ now supports using multiple inputs of as many as you need. To achieve this instead of selecting on element ID we bind to a class name. Given the following Html.
<div>
<strong>Enter your tag and click add</strong>
<br/>
<strong>Tag 1</strong>
<input type="text" id="tagEntry" class="tagEntry" />
<br/>
<strong>Tag 2</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 3</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 4</strong>
<input type="text" class="tagEntry" />
<br/>
<strong>Tag 5</strong>
<input type="text" class="tagEntry" />
</div>
<div>
<strong>Entered Tags</strong>
<br/>
<input type="text" id="tagsEntered" />
</div>
All the tag input boxes have a class of tagEntry now this class will become our selector. With the following JS we can bind the blur event to every tag that has a class of tagEntry. This will now update the tags box every time any of the inputs changed.
var tags = [];
$(function() {
$('.tagEntry').blur(function(){
//get the tag value and trim the spaces
var tVal = $(this).val().trim();
if(tVal == '')
return;
//reset the entry box
$(this).val('');
//verify tag not already saved
for(var i=0;i<tags.length;i++)
if(tags[i] == tVal)
return;
//add the tag to the array
tags.push(tVal);
//set the tags entry box
$('#tagsEntered').val(tags.join(', '));
});
});
As you can see our handler binds to all the inputs, as any of the inputs receives the blur event the method of extracting the tags is executed.
$("#input1,#input2,#input3").change(function () {
var inputArray = [$("#input1").val(), $("#input2").val(), $("#input3").val()];
$("#masterinput").val(inputArray.join(' '));
});
You probably want to narrow the selector so it isn't selecting all text inputs on the page.
var inputs$ = $("input:text").change(function () {
var inputArray = [];
$.each(inputs$, function(i, v) {
inputArray.push($(v).val());
}
$("#allInputs").text(inputArray.join(' '));
});
Here you go:
var str = "";
$("input[type=text]").change(function () {
$("input[type=text]").each(function(){
str += $(this).val()+",";
};
});
$("#allInputs").html(str);