How to use onchange in HTML - javascript

I have two text box in html ie:
<input type="text" value="" id="a" name="a" />
<input type="text" value="" readonly="true" id="b" name="b" />
Now if i enter only a number in element id "a" then the product of inserted number by 2 will be appear in element id "b".
Like:
While i m typing a number let say 11 in element "a"
then on the same time 11*2 ie: 22 will appear in element "b"
and if enter backspace or delete any number on the same time change will appear in element "b".
To get my required result i create a function like
onchange = function totalAmount()
{
var value = $("#a").val();
if ( (value > 0) && (value != "") )
{
$("input:text[name=b]").val(2 * value);
}
else
{
$("input:text[name=getCredit]").val("");
}
};
It fulfill 80% of my requirement as it will make change in element "b" if i click on any were after insert a number.

I see that you are using jQuery. You could bind to the change event of the textbox:
$('input:text[name=a]').change(function() {
// invoked when the value of input name="a" changes
// get the new value
var value = $(this).val();
// update the value of input name="b"
$('input:text[name=b]').val(2 * value);
});
This event will be raised when the input loses focus. You could also take a look at keypress and keyup events.

i think using the onkeyup event might help
<input type="text" value="" id="a" name="a" onkeyup="calcTotalAmount()" />
<input type="text" value="" readonly="true" id="b" name="b" />
<script>
function calcTotalAmount() {
var a = document.getElementById("a");
var b = document.getElementById("b");
if (!isNaN(a.value)) {
b.value = a.value * 2;
}
}
</script>
Why onkeyup?
Onkeydown event fires when key is pressed, onkeyup event fires when key is released and the event onkeypress fires if the onkeydown is followed by onkeyup,
and in the time of onkeydown the input field does not containt the value yet.

If you want a call back on every key press you can use the onKeyPress attribute.
(If you are using a library like JQuery/prototype/etc there is probably a nice way of observing a field using the library)

Related

Listen for blank inputs and add a "disabled" attribute to a button until an input is noticed

I have a user input field that, if blank, I would like the submit button to be disabled until a key press in the input box is noticed. But, if they blank out the input box, then the button is disabled again.
So, I'd like to add the "disabled" attribute to this input button:
<input type="submit" id="mapOneSubmit" value="Submit" [add attribute "disabled" here]>
The input is from this HTML here:
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this)">
Note: I have onkeypress and oninput validation to prevent non-number inputs and allow only 2 decimal places.
I assume my JS would look like this to add the disabled attribute:
document.getElementById("mapOneSubmit").setAttribute("disabled");
My problem is, I can't find what event listener listens for "blank" inputs? Can you help me with that?
Thanks kindly!
Check this one as well.
function checkvalid(el)
{
//e.g i am preventing user here to input only upto 5 characters
//you can put your own validation logic here
if(el.value.length===0 || el.value.length>5)
document.getElementById("mapOneSubmit").setAttribute("disabled","disabled");
else
document.getElementById("mapOneSubmit").removeAttribute('disabled');
}
<input type='text' id ='inp' onkeyup='checkvalid(this)'>
<button id='mapOneSubmit' disabled>
Submit
</button>
Yet using the input event:
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this);updateSubmit(this.value)">
Then in js
function updateSubmit(val) {
if (val.trim() == '') {
document.getElementById('mapOneSubmit').disabled = true;
}
else {
document.getElementById('mapOneSubmit').disabled = false;
}
}
You can find the below code to find the blank inputs
function isNumberKey(event) {
console.log(event.which)
}
var value;
function validate(target) {
console.log(target);
}
<form>
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this)">
<input type="submit" id="mapOneSubmit" value="Submit" [add attribute "disabled" here]>
</form>
You can you set the enable/disable inside validate function.
function validate(elem) {
//validation here
//code to disable/enable the button
document.getElementById("mapOneSubmit").disabled = elem.value.length === 0;
}
Set the button disable on load by adding disabled property
<input type="submit" id="mapOneSubmit" value="Submit" disabled>
On your validate function just check if value of input field is blank then enable/disable the button
function validate(input){
input.disabled = input.value === "" ;
}
My problem is, I can't find what event listener listens for "blank" inputs?
You can disable the submit button at render, after that you can use the input event to determine whether the input value is empty or not. From there, you can set state of the submit button.
document.addEventListener('DOMContentLoaded', () => {
const textInput = document.getElementById('mapOneUserInput');
textInput.addEventListener('input', handleTextInput, false);
textInput.addEventListener('keydown', validateInput, false);
});
function handleTextInput(event) {
const { value } = event.target;
if (value) {
enableSubmitButton(true);
} else {
enableSubmitButton(false);
}
}
// Refer to https://stackoverflow.com/a/46203928/7583537
function validateInput(event) {
const regex = /^\d*(\.\d{0,2})?$/g;
const prevVal = event.target.value;
const input = this;
setTimeout(function() {
var nextVal = event.target.value;
if (!regex.test(nextVal)) {
input.value = prevVal;
}
}, 0);
}
function enableSubmitButton(isEnable) {
const button = document.getElementById('mapOneSubmit');
if (isEnable) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', '');
}
}
<input type="number" value="" id="mapOneUserInput">
<!-- Note that the input blank at render so we disable submit button -->
<input type="submit" id="mapOneSubmit" value="Submit" disabled>

JavaScript document.getElementById().value logs empty value [duplicate]

This question already has an answer here:
Why is the value of my input always empty if I store it in a variable?
(1 answer)
Closed 12 months ago.
I want the value of the text input logged to the console but when I open the page the console.log() is empty. Why is this?
<input type="text" id="word"/>
//JavaScript
var newWord = document.getElementById("word").value;
console.log(newWord);
Ensure to add an event handler.
Add an onchange event listener to input element.
function func() {
var newWord = document.getElementById("word").value;
console.log(newWord);
}
<input type="text" id="word" onchange='func()'/>
You will need to enter a value to your input or add a default value
<input type="text" id="word" value="Hello"/>
var newWord = document.getElementById("word").value;
console.log(newWord);
This will log the value
Use .addEventListener to run a function when a change event is fired - This will run your function whenever the value in the input is updated and the focus is removed from the input box
document.getElementById('word').addEventListener('change', function () {
let newWord = this.value;
console.log(newWord);
});
<input type="text" id="word"/>
Or, you could use the input event, which will fire as soon as the input is changed
document.getElementById('word').addEventListener('input', function () {
let newWord = this.value;
console.log(newWord);
});
<input type="text" id="word"/>
I cannot get your question, but according to my understanding, you need to use a function to get the value of input box, when an event occurs. here is the code something like this.
<!DOCTYPE html>
<html>
<body>
<p>A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" id="myinput" onkeypress="myFunction()">
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById('myinput').value;
document.getElementById('demo').innerHTML = x;
}
</script>
</body>
</html>

jQuery blur behaving strangely

I want to listen blur event of every input field in the form, but when I reset the form after calculation, the again when i get focus of the input field it fires blur event two times, one with empty value and one with input value.
<form id="form">
Total Ore to be Mined:
<input type="number" name="TOmined" value="0" autofocus> Tons
<br> Total Waste to be Mined:
<input type="number" name="TWmined" value="0"> Tons
<br> Number of Operating Days/Year:
<input type="number" name="OperatingDays" value="0"> Days
<br> Number of Operating Years:
<input type="number" name="OperatingYrs" value="0"> Years
<br>
</form>
<script>
var arr = {};
// {"TOmined": inputValue}
$(document).ready(function() {
$(":input").blur(function(e) {
var k = e.target.name;
var v = e.target.value;
arr[k] = v;
console.log(k, v); // **runs two times one with empty string**
// one with original value
})
});
function calculate() {
var sum = 0;
// your logic
console.log(arr);
// end logic
if (!jQuery.isEmptyObject(arr)) {
for (v in arr)
sum += parseInt(arr[v]);
console.log(sum);
}
$('#form').trigger("reset");
// $('#result').html(value to be displayed + ' tons/day');
arr = {};
}
</script>
Quickest way to spot the problem would be to add this line to your blur callback:
console.log(e.target);
... which will show you the element that was blurred. In this case, it's your <button/> element that is triggering a blur event. You're binding the blur callback to all :input elements, and :input is a jQuery extension that includes input, textarea, select, and button elements (see documentation).
To fix this, you'll just want to bind to real input elements, not the :input selector.
$('input').blur(function (e) {
// ...
});

Trying to append the textfield value to another textfield

I am doing some basic javascript where i am choosing some value from the popup and that value is appearing in the textfield. Now there is a button on the side of the textfieldfield, which when clicked will transfer its value to the another textfield as comma separated.
I mean the new textfield will have values as comma separated and not replaced.
I am doing a code like this
<input type="text" class="inputs" style="width:70px;" name="color1" id="color1" value="" maxlength="7" size="7">
<img src="icon_add.gif" alt="Add to text Box above" title="Add to text Box above" border="0">
function addtoTextField(cFieldName) {
var objTxt = document.getElementById('sta');
objTxt.appendChild(cFieldName);
}
Another text field where i need to pass value
<input type="text" name="sta" id="sta" class="inputs" />
Textbox element can't have child nodes, it only got a value. So to append value of other textbox as comma delimeted string, have this:
function addtoTextField(cFieldName) {
var oField = document.getElementById(cFieldName);
var valueToAdd = oField.value;
if (valueToAdd.length === 0)
return; //don't add empty values
var objTxt = document.getElementById('sta');
var existingValues = (objTxt.value.length === 0) ? [] : objTxt.value.split(",");
existingValues.push(valueToAdd);
objTxt.value = existingValues.join(",");
oField.value = ""; //clear textbox
oField.focus(); //bring focus back
}
Live test case.
The above will also clear the sender textbox value and re-focus it for next input.

press button and value increases in text box

So when the page loads the text box will contain a stored value. I want the user to press the '+' button and the value in the text box will increase by one. Im guessing this is done with JQuery...Any ideas on where to get started so far I have...
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
<input type="Button" value="+" onclick="AddOne(document.getElementById('BoqTextBox').value)" />
<script>
function Add(data) {
//so the current digit is passed to here, where I need to do some funky code
//where it increments the current digit by one and stores it in BoqTextBox - replacing the old digit.
//Also to note if the text box contains 124.54 for example and + is pressed
//then new value will be 125.54
}
</script>
Any assistance with this would be great.
Thank you
...something like data = data + 1, but then how do I return the value into the text box?
You can use jQuery's val() to fetch and set a value. In this case the code you need could look like this (demo):
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
<input type="Button" id='AddButton' value="+" />
<script>
$('#AddButton').on('click', function () {
var input = $('#BoqTextBox');
input.val(parseFloat(input.val()) + 1);
})
</script>
$('input[type="button"]').on('click', function() { // bind click event to button
$('#BoqTextBox').val(function() { // change input value using callback
return ++parseFloat( this.value, 10); // make value integer and increment 1
})
});
you are callin Addone function inline so that means your function should be AddOne()
try this
function AddOne(obj){
var value=parseFloat(obj) + 1;
$('#BoqTextBox').val(value);
}
$("#buttonId").click(function()
{
var txtBox = $("#boqtextbox");
if(!isNaN(txtBox.val()))
{
txtBox.val(parsFloat(txtBox.val())+1) ;
}else
{
//do validation or set it to 0
txtBox.val(0);
}|
});

Categories

Resources