live validation with javascript - onchange only triggered once - javascript

So I'm just testing something with js, basically the number in the first input has to be bigger than the number in the second input for the submit button to be activated.
The button get's disabled just right, but if I change the number it won't activate again
<!DOCTYPE HTML>
<html>
<body>
<input type='number' id='first' onchange="validateNumber()"/><br>
<input type='number' id='second' onchange="validateNumber()"/><br>
<script type="text/javascript" >
function validateNumber()
{
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
if(first > second){
document.getElementById('sub').disabled=false;
}else{
document.getElementById('sub').disabled=true;
}
}
</script>
<input type="submit" id="sub"/>
</body>
</html>
Edit:
The arrows of the number input trigger onchange it seems, that caused the problem

You have to add the onclick and onkeyup event in order to respond to mouse interactions and to inserts from the clipboard:
http://jsfiddle.net/wzvvN/1
<input type='number' id='first' onkeyup="validateNumber()" onclick="validateNumber()" onchange="validateNumber()" />
<input type='number' id='second' onkeyup="validateNumber()" onclick="validateNumber()" onchange="validateNumber()" />

Try binding the onfocus and onblur events to.
<input type='number' id='first' onchange="validateNumber()" onfocus="validateNumber()" onblur="validateNumber()"/><br>
<input type='number' id='second' onchange="validateNumber()" onfocus="validateNumber()" onblur="validateNumber()"/><br>

You may want to use onkeyup(), since onchange() gets called only when you switch focus to another element.
Also, your function is currently comparing strings. Use parseInt to convert to an integer and then compare. The following code works for me:
<html>
<body>
<input type='number' id='first' onkeyup="validateNumber()"/><br>
<input type='number' id='second' onkeyup="validateNumber()"/><br>
<script type="text/javascript" >
function validateNumber()
{
var first = parseInt(document.getElementById('first').value, 10);
var second = parseInt(document.getElementById('second').value, 10);
if(first > second){
document.getElementById('sub').disabled=false;
} else {
document.getElementById('sub').disabled=true;
}
}
</script>
<input type="submit" id="sub" disabled="disabled" />
</body>
</html>

Related

Focusing subsequent fields with a single JavaScript Function

Noob here..I am trying to auto-focus fields based on a criterion that when a field contains a predefined length of input, it must automatically focus the next field.
<html>
<body>
<input type="number" id="box1" autofocus="autofocus" onkeyup='checkInput()'> - <input type="number" id="box2"onkeyup='checkInput()'> - <input type="number" id="box3"onkeyup='checkInput()'>
<script type="text/javascript">
function checkInput(){
if(parseInt(document.getElementById('box1').value.length) == 3)
document.getElementById('box2').focus();
}
</script>
</body>
</html>
I can always write that many functions and manually pick the next field. But is there a way to do it with just JS function, by passing this.id to as the argument to that function?
Pass the id of the current input element to the checkInput() function and As you are doing it in plain javaScript and not using jQuery, You can use the nextElementSibling property to get the next element and then focus on it using .focus() as shown below :
function checkInput(id) {
if (parseInt(document.getElementById(id).value.length) == 3)
var nextSibling = document.getElementById(id).nextElementSibling;
if (nextSibling) {
nextSibling.focus();
}
}
<html>
<body>
<input type="numbers" id="box1" autofocus="autofocus" onkeyup='checkInput("box1")'>-
<input type="numbers" id="box2" onkeyup='checkInput("box2")'>-
<input type="numbers" id="box3" onkeyup='checkInput("box3")'>
</body>
</html>
Use jquery to select all inputs and then select the next input when length greater than 3.
$(document).ready(()=>{
$('input').on('keyup',(event)=>{
console.log(event.target.value.length);
if(event.target.value.length == 3){
$(event.target).next().focus();
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<input type="numbers" id="box1" autofocus="autofocus" > - <input type="numbers" id="box2"> - <input type="numbers" id="box3">
</body>
</html>

JS document.getElementById execute on Button click

I am extremely new to JavaScript, so bear with me.
I have the following code:
<input id="test" name="test" type="text" value="" />
<input id="test" type="button" value="Go!" />
<script type="text/javascript">
window.location.href="http://www.thenewendurancefitness.com/" + document.getElementById('test').value;
</script>
I would like the code to only be executed upon a button click. The function is to add the user input data to the end of the url and then upon the button click, load that url.
As of now, when I load the page, it automatically executes and goes to the url.
You have two input fields with the same ID, that's a no go!
Change the second one to something different!
Put your current javascript code into a function
function clickHandler(event) {
// Your code...
}
Attach an event listener to your container
var myContainer;
// assign element from DOM
myContainer = document.getElementById(ID_OF_CONTAINER);
// attach event handler
myContainer.addEventListener('click', clickHandler);
That should do the trick
<input id="test" name="test" type="text" value="" />
<input id="test2" type="button" onclick="fnc()" value="Go!" />
<script type="text/javascript">
function fnc(){
window.location.href="http://www.thenewendurancefitness.com/" + document.getElementById('test').value;
}
</script>
You need to wrap your code in a function, and then call the function based on an event. Here, the onclick event of the button. NOTE that IDs must be unique. Change your code to:
<input id="test" name="test" type="text" value="" />
<input id="test2" type="button" value="Go!" onclick="foo()" />
<script type="text/javascript">
function foo(){
window.location.href="http://www.thenewendurancefitness.com/" + document.getElementById('test').value;
}
</script>
jsFiddle example
Note that ID's are unique, and that you would use an event listener for that
<input id="test" name="test" type="text" value="" />
<input id="button" type="button" value="Go!" />
<script type="text/javascript">
document.getElementById('button').addEventListener('click', function() {
var val = document.getElementById('test').value;
window.location.href="http://www.thenewendurancefitness.com/" + val;
}, false):
</script>
<form onsubmit="return submit()">
<input id="test" name="test" type="text" value="" />
<input id="submit" type="submit" value="Go!" />
</form>
<script type="text/javascript">
function submit() {
location.href="http://www.thenewendurancefitness.com/"+document.getElementById('test').value;
}
</script>

How to set sum value on text feild when second value is set text?

This is my demo cord.
<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="text" id="total" />
<input type="button" value="Add Them Together" onclick="doMath();" />
<script type="text/javascript">
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
// Add them together and display
var sum = parseFloat(my_input1) + parseFloat(my_input2);
document.getElementById('total').value=sum;
}
I want to work this function when my_input2 is enter it's value. Just like onclick method for button is there any event to set value to total tetxfeild after key release event?
<script type="text/javascript">
$(document).ready(function () {
$("#my_input2").blur(function () {
var sum = parseInt($("#my_input1").val()) + parseInt($("#my_input2").val());
$("#total").val(sum);
});
});
</script>
<div>
<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="text" id="total" />
<input type="button" value="Add Them Together" />
</div>
And also u should frame ur question correctly bcz u have added code in button click and asking us it should work after leaving textbox
Put onkeyup() on second input field this will fire your function.
Something like that:
<input type="text" id="my_input2" onkeyup="doMath();" />
try this
<input type="text" id="my_input2" onchange="doMath();" />

Input value hidden

I have this input:
<input id="tag1" type="text" name="tags" class="tags" value="#Model.list" />
and I want to get this input value in a hidden input, so I used this:
<input type="hidden" name="tag" value="tags" />
Instead of getting the true value of the first input, I only get the string "tags"! Can you please tell me how to obtain the true value of the first input in my hidden input? Thanks!
EDIT: Actually it's a submit page, the user enters tags in the #tag1 and when he clicks on submit I want to send these tags to my controller, that's why I'm using the hidden input...
My full code:
<form>
<p>
<input id="tag1" type="text" name="tags" class="tags" value="#Model.list" onblur="setValue()"; /></p>
<script>
$('#tag1').tagsInput({
// my parameters here
});
</script>
<style>
#wrapper {
margin: 20px;
}
</style>
<p>
<input type="submit" value="Create" />
<input type="hidden" name="taggg" id="tag2" />
<script type="text/javascript">
function setValue() {
document.getElementById("tag2").value = document.getElementById("tag1").value;
}
window.onload = setValue;
</script>
</p>
</form>
I don't understand why you would want to copy the value of one input field to another (albeit, hidden). But if that is what you want to do, try using the below code.
The function attached to the onblur event of the input field would set the value of the input field to the hidden field whenever it loses focus.
The window.onload = setValue will do the same on page load.
HTML
<input id="tag1" type="text" name="tags" class="tags" value="#Model.list" onblur="setValue();" />
<input type="hidden" name="tag" value="tags" id="tag1_hidden" /> <!-- Note the addition of an id attribute -->
JavaScript
function setValue() {
document.getElementById("tag1_hidden").value = document.getElementById("tag1").value;
}
window.onload = setValue;
Try this
<input id="tag1" type="text" name="tags" class="tags" value="#Model.list" />
<input type="hidden" name="tag" value="tags" id="tag2" />
Jquery:
$("#tag2").val($("#tag1").val());
or
$("#tag1").blur(function() {
$("#tag2").val($(this).val());
});
You can do like this (and you will need javascript for this).
Give a id to your hidden input also like:
<input type="hidden" id="hidden_input" name="tag" value="tags" />
and then use/paste this code when you need it:
var input_value = document.getElementById('tag1').value;
document.getElementById('hidden_input').value = input_value;

Can I recalculate a form field without a reload?

When a field in my form gets focus, I'd like a javascript function to be called that
calculates a value for that field without my putting in a specific button to do that.
Is this possible without causing the form to reload?
I have thought about making the Amount field read-only, and some other ways of doing this, but I'm looking to see if changing the Quantity field could cause the Amount field to change either using onchange in the Quantity field or onfocus in the Amount field.
Purchase Tickets<br>
<script type="text/javascript" language="JavaScript1.2">
<script type="text/javascript" language="JavaScript1.2">
document.write(
'<form name="InvGenPayTickets" action="'+PostURL+'"
onsubmit="return validateForm();" method=GET>');
</script>
<input type=hidden name="TplURL" value="GenPayCCInfo.html">
<input type=hidden name="CancelURL" value="Ooopsie.html">
<input type=hidden name="SuccessURL" value="Joanie.html">
<input type='hidden' name='TransDesc' id='TransDesc'
value="$_POST['TransDesc']; ?>" />
<input type='text' name='Quantity' id='Quantity' /> <br />
Amount<br />
$<input type='text' name='Amount' id='Amount' />
<input type="submit" value="Next">
<br>
</form>
Edit:
Here is the function that won't update. It is called if I use
<input type='text' name='Quantity'
id='Quantity' onchange="return retTotalAmt();" />
but the Amount field does not update. I am not able to update using a calc button either.
<script type="text/javascript" language="JavaScript1.2">
function retTotalAmt()
{
alert("Got here.");
var total_amt
= (document.getElementById('Quantity').value * ticketCost)
+ DonationAmount;
document.getElementById('Amount').value = total_amt;
}
</script>
Per request in comments:
<input type='text' name='Quantity'
id='Quantity' onchange="return retTotalAmt();" />
Edit -- Show Problem
<script type="text/javascript" language="JavaScript1.2">
var ticketCost = 40.00;
function EnterPage()
{
var currentTotalAmount = DonationAmount + ticketCost;
//DonationAmount moved up to ticketCost's scope fixed problem.
var DonationAmount = <?php echo($_POST['DonationAmount']); ?>;
document.getElementById('DonationAmountField').value = DonationAmount.toFixed(2);
document.getElementById('Quantity').value=1;
document.getElementById('Amount').value = currentTotalAmount.toFixed(2);
return;
}
Without using jquery:
<input type='text' name='Amount' id='Amount' onfocus="amountOnFocus();" />
Javascript:
function amountOnFocus() {
amountField = document.getElementById('Amount');
//Do calculations
amountField.value = resultOfCalculations;
}
If you wanted, you could also put a change event listener on the Quantity input so it will calculate when the value of that textbox changes.
EDIT: This onchange event works for me:
Markup:
<input type="text" id="txtChangeMe" onchange="txtChangeMeOnChange();" />
Javascript:
<script type="text/javascript">
function txtChangeMeOnChange() {
alert('changed');
}
</script>
I'm not quite sure what additional information you need, as you seem to be aware of all the ingredients for making this happen: You know that you want to detect an event, you know that you need to call a function, so I'm hoping I haven't missed something about what you're asking. I'm going to assume that you just need to know how to tie all these parts together.
The simplest example might be:
<input type="text" id="Quantity" value="10" onchange="document.getElementById('Amount').value = parseInt(document.getElementById('Quantity').value,10) * 10.0;" />
$<input type="text" id="Amount" value="100" />
though it's worth noting that this does not follow best-practices, which would involve binding an event listener separately.
On the off-chance that you accidentally typed "button" when you meant "field", I will also mention that you can update any other element's innner HTML with the ''innerHTML'' attribute, eg:
<input type="text" id="Quantity" value="10" onchange="document.getElementById('Amount').innerHTML = parseInt(document.getElementById('Quantity').value,10) * 10.0;" />
$<span id="Amount">100</span>
Of course, you can define the actual logic elsewhere, and just use ''onchange="yourFunction();"'' instead of putting everything inline, as well.
I know you mentioned "onchange" and "onfocus", though personally I tend to prefer "onkeyup", so that values will change as the user is typing.
Apologies if I've completely missed the point in your question.
Sure. Use something like this which will fire when quantity change:
$("#Quantity").change(function(){
// perform your calculations here
};
This requires the jQuery framework.
function calcPrice()
{
....
}
<input type='text' name='Quantity' id='Quantity' onchange='calcPrice();'/>
<input type='text' name='Amount' id='Amount' onfocus='calcPrice();'/>
Do you have access to jQuery? If not then you would have to bind an change event to your "quantity" input element to listen for a change of its input. Then you would simply need to modify the contents of the "amount" input.
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
var el = document.getElementById("Amount");
el.addEventListener("change", changeAmount);
function changeAmount(){
var quantity = document.getElementById("Quantity");
quantity.value = "SET YOUR VALUE";
}
Try this solution
Html
<div class="form-group row">
<label for="inputQty" class="col-sm-4 col-form-label">Quantity</label>
<div class="col-sm-8">
<input onkeyup="CalculateItem();" onkeydown="CalculateItem();" onchange="CalculateItem();" onfocus="CalculateItem();" value="1" type="number" step="1" min="1" max="9999999" class="form-control" id="inputQty" required>
</div>
</div>
<div class="form-group row">
<label for="inputPrice" class="col-sm-4 col-form-label">Price</label>
<div class="col-sm-8">
<input onkeyup="CalculateItem();" onkeydown="CalculateItem();" onchange="CalculateItem();" onfocus="CalculateItem();" type="number" step="0.1" min="1" max="9999999" class="form-control" id="inputPrice" required>
</div>
</div>
<div class="form-group row">
<label for="inputPriceNoVat" class="col-sm-4 col-form-label">Price (no VAT)</label>
<div class="col-sm-8">
<input readonly type="text" class="form-control" id="inputPriceNoVat">
</div>
</div>
JS
<script type="text/javascript">
function CalculateItem()
{
try {
let inputPriceNoVat = $('#inputPrice').val() * $('#inputQty').val();
$('#inputPriceNoVat').val(inputPriceNoVat);
} catch (e) {
$('#inputPriceNoVat').val(0);
}
}
</script>

Categories

Resources