How to use event onchange on this case javascript? - javascript

How to use event onchange on this case javascript ?
First fill data into input id="one" , And then data in input id="two" will change data like data in input id="one"
But , when data in input id="two" change , Why not call fn_2 function (why not alert) ?
http://jsfiddle.net/A4wxX/111/
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script>
function fn_1()
{
var aaa = document.getElementById('one').value;
document.getElementById("two").value = aaa;
}
</script>
<script>
function fn_2()
{
var bbb = document.getElementById('two').value;
alert(bbb);
}
</script>
<input type="text" id="one" onchange="fn_1()"/>
<input type="text" id="two" onchange="fn_2()" style="display: none"/>

What you wanted is that on change of value of first input box, get this value and set it for second input box and give alert.
In this case onchange event will not get fired. For this you need to manualy call the onchange event of the second input box.
<script>
function fn_1() {
var aaa = document.getElementById('one').value;
var second_input_elem = document.getElementById("two");
second_input_elem.value = aaa;
second_input_elem.onchange();
}
Try this fiddle http://jsfiddle.net/u09Lurvr/

Its working perfectly.
<script>
function fn_2()
{
var bbb = document.getElementById('two').value;
document.getElementById("one").value = bbb;
}
</script>

onchange does work, try clicking outside of the input box once you enter a new value...
But you probably want the value to update instantly... Using JavaScript's oninput you can accomplish this.
document.getElementById("one").onchange=function(){
document.getElementById("result_one").innerHTML = this.value;
}
document.getElementById("two").oninput=function(){
document.getElementById("result_two").innerHTML = this.value;
}
The element result_one updates whenever the status of the element changes. So focused or blurred... While the result_two element updates whenever there is new input.
Here is a JSFiddle example.
Edit: It appears I misread or misunderstood the question, but it still works regardless.
Edit 2: It seems I misunderstood the question once again...
Why is there no alert?
If you're expecting an alert when you put a value into input one and the changing value of input two, you're looking at it wrong... The onchange function is triggered when the status of an element changes (and for inputs, when the value changes + when the status changes). The onchange function is not triggered when the value itself changes... And for the reason in your example, the alert is not being fired because the status isn't changing, only the value.
But why are you doing this? You're basically creating two inputs, input two just has a value from input one... And you're binding an event on an element where you're creating the value dynamically. It just seems kinda messy... A better alternative would be to just fire the alert in input one's function...
<script type="text/javascript">
function fn_1() {
var aaa = document.getElementById('one').value;
document.getElementById("two").value = aaa;
var bbb = document.getElementById('two').value;
alert(bbb);
}
document.getElementById("one").onchange=fn_1;
</script>
<input type="text" id="one"/>
<input type="text" id="two" style="display: none"/>

onchange event will work when some text is changed in the text field and it becomes off focus.
Hope you want this that way. We are seeing, it is working in that way.
If you want a more automatic way, you can use onkeyup for id="one" field and onkeypress for id="two" field but it should be made visible in that case
e.g.
//no need to include jQuery library when you are not using it
<script type="text/javascript">
function fn_1()
{
var aaa = document.getElementById('one').value;
document.getElementById("two").value = aaa;
}
function fn_2()
{
var bbb = document.getElementById('two').value;
alert(bbb);
}
</script>
<input type="text" id="one" onkeyup="fn_1()" />
<input type="text" id="two" onkeypress="fn_2()" />
Since you have made 2nd field invisible in your example, you will never get an alert as how someone will try onchange event for it? Could you let us know how the data will be handled in 2nd field? Will data be filled into it via some JavaScript event (and thus you want onchange event) or directly by putting cursor into it and changing? If so, then it's already working.

using onchange is useful for select element, in your case it would be better if you use 'onblur':
<script>
function fn_1()
{
var aaa = document.getElementById('one').value;
document.getElementById("two").value = aaa;
fn_2();
}
function fn_2()
{
var bbb = document.getElementById('two').value;
alert(bbb);
}
</script>
<input type="text" id="one" onblur="fn_1()"/>
<input type="text" id="two" onblur="fn_2()" style="display: none"/>

Related

How to make data input readonly, but showing calendar?

I can't find any solution for this anywhere. I would like to allow user to see calendar when clicking on my input, but when user will try to change the value, it shouldn't change (or immediately change back for value, what was at the beggining).
Readonly attribute removes calendar, so I was trying to do it different ways like use onchange/onclick functions to restore my value after event, but the value was changing anyway.
So for now my input looks like this:
<input class='test' type='date' value='2020-06-04' onkeydown='return false' >
So at least user can't change value of my input using keyboard. Could you help me?
You might try to set a time limit
<html>
<body>
<input type="date" value="2020-06-04">
<input type="date" value="2020-06-04" min="2020-06-04" max="2020-06-04">
</body>
</html>
If I understood correctly, this is what you want.
HTML
<input class='test' type='date' value='2020-06-04' />
JavaScript
const date = "2020-06-04";
const input = document.querySelector('.test');
input.onkeydown = function(e) {
return false;
}
input.onchange = function(e) {
this.value = date;
}
Check out this JSFiddle
EDIT
function preventInputChange(input, staticValue) {
input.onchange = function(e) {
this.value = staticValue;
}
}

alerting the value of an input type number

Here is the code that I am having problems with. Below it I'll add an explanation:
$(function() {
var $input = $("#input");
var input = $input.val();
var $go = $("#go");
$go.click(function() {
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
The code above is a dummie example to represent my actual question, no more background is needed.
So I have one input type="number" id="input" in which you input a number, and a button type="button" id="go".
In my jQuery, I first declare $input which holds the element #input, then input which holds the value of the element #input, and finally $go which holds the element #go.
Below that I have a function, that says that when I click on #go, I should be able to alert(input).
Now, this code does not do that. In my head this makes perfect sense, but apparently it doesn't work.
That is because you are declaring input outside the click function, which means the value (simply an empty string) is set at runtime and will not be updated. You should define input within your click event handler:
$(function() {
var $input = $("#input");
var $go = $("#go");
$go.click(function() {
var input = $input.val();
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
First of all, StackOverflow seems to block alerts origination from the code snippet, it will be much easier to output them to the console instead so you can keep track of things.
Your code can be simplified way down without the need for many variables.
But your main problem was the fact that the input value was not getting reset when the click event happened but was getting picked up on page load, meaning it would be stuck at ''.
$(function() {
$("#go").click(function() {
var input = $("#input").val();
console.log(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>

Javascript run onChange not onLoad

I have a very simple piece of Javascript that works perfectly onLoad, but I need it to work onChange.
My script;
<form action="" method="post" name="product_search">
<p><strong>Existing Part Number:</strong>
<input name="v_prodref" type="text" id="v_prodref" size="25" maxlength="25" onChange="searchValue()">
<input type="text" name="prodref" id="prodref">
<input type="submit" name="search_Submit" id="search_Submit" value="Submit">
</p>
<div>
<%=(rs_ProductCheck.Fields.Item("prodref").Value)%>
// <%=(rs_ProductCheck.Fields.Item("proddesc").Value)%></div>
<script>
function searchValue() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref');
if(c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add) }
else {
n_ProdRef = c_ProdRef.replace(/GST/i,"NWGST") }
document.getElementById("prodref").value = n_ProdRef;
}
</script>
</form>
So, I enter a part number in the first text box, and I want my javascript to run and enter the new value in the second text box, but it doesn't seem to work.
What am I missing?
search does not exist on an HTMLInputElement. You need to use c_ProdRef.value.search.
(Actually, since you're using it in many places as a string, and never as an input, you probably intended to define c_ProdRef as var document.getElementById('v_prodref').value)
You would've seen this error on load as well.
you want onkeyup if it works perfectly onLoad, and you want to start typing in something in textbox 1 and the javascript to run, you dont want onchange
onchange triggers after blur of focused element
onkeyup triggers after you release a keyboard input
Thanks to everyone for their help. After a little tweaking I have managed to get my code working.
function myFunction() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref').value;
if (c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add)
} else {
n_ProdRef = c_ProdRef.replace(/GST/i, "NWGST")
}
document.getElementById("prodref").value = n_ProdRef;
}
Along with #indubitablee suggestion of onKeyup and specifying the .value of my first text field it all works.

Javascript change hidden field on submit

Hi I am trying to install a merchant facility onto my website and it needs to submit a value $vpc_Amount which is the amount purchased in cents.
What I need to do is multiply the amount entered by the user ($amount) by 100 to get $vpc_Amount.
I tried the following but it isn't working.
<input type="text" ID="A1" name="amount"onkeypress="process1()">
<input type="hidden" id="A2" name="vpc_Amount">
And then the javascript
function process1() {
f1 = document.getElementById("A1").value;
total = f1*1000;
document.getElementById("A2").value = total;
}
What is happening is it is occasionally working but most of the time it doesn't. I know there is something wrong with the script so hence asking here.
Try to use onkeyup function -
<input type="text" id="A1" name="amount" value="" onkeyup="process1();" />
<input type="hidden" id="A2" name="vpc_Amount" />
javascript function -
function process1() {
var f1 = document.getElementById("A1").value;
var total = (f1 * 100);
document.getElementById("A2").value = total;
}
Use Jquery. http://jquery.com/
$(function() {
$('#form_id').submit(function(){
$('#form_id').find('#A2').val('New value');
return true;
});
});
Have you tried to use onkeyup event? It might be so that onkeypress event is triggered before the character is added to text field.
<input type="text" ID="A1" name="amount" onkeyup="process1()">
Also, I would suggest that you try to convert the value of the textfield to integer and add other input handling too. Users might enter any kind of data there and it can crash your javascript code.
This code should work:
document
.getElementById('A1')
.addEventListener('keyup', function (e) {
document.getElementById('A2').value = parseInt(this.value) * 1000;
})
keypress event triggers before value changes in text field and keyup after value has changed.
Basically event trigger in order:
keydown (onkeydown)
keypress (onkeypress)
keyup (onkeyup)
Force value to be integer or you will get NaN in some cases.
I will suggest to use onblur this is the best way if you want to use the build in attribute listener if you don't use jquery. Here is example:
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
And url to the example in w3 school :) http://www.w3schools.com/jsref/event_onblur.asp
First of all, I think you should use onkeypup event and not onkeypress
<input type="text" id="A1" name="amount" onkeyup="process1()" value="" />
<input type="hidden" id="A2" name="vpc_Amount" value="" />
Javascript code -
function process1() {
var f1 = parseFloat(document.getElementById("A1").value);
var total = f1*100; //you said 100 so, I changed to 100
document.getElementById("A2").value = total;
}
jQuery code for the same -
jQuery(document).ready(function($){
$("#A1").keyup(function(){
var total = parseFloat($("#A1").val()) * 100;
$("#A2").val(total);
});
});
Your code can be simplified by making use of the fact that form controls are available as named properties of the form baed on their name. This removes the requirement to add IDs to form controls that must have a name anyway.
Pass a reference to the control in the listener:
<input type="text" name="amount" onkeyup="process1(this)">
<input type="hidden" name="vpc_Amount">
Then use the passed reference to get the form and other controls:
function process1(element) {
element.form.vpc_Amount.value = element.value * 100;
}
You may wish to use the change event instead to save updating the hidden field unnecessarily while the user is typing and also to catch changes that aren't based on key presses (e.g. pasting from the context menu).
You should also do some validation of the values entered so the user doesn't attempt to send the form with invalid values (noting that you must also do validation at the server as client side validation is helpful but utterly unreliable).

Keyup function into form element

I have a script I am using to copy a field into another input field using keyup blur paste. This script works, however I need to modify it to also go into two different form elements which are named data-cost="" and debt="", instead of the <div id="viewer">
This is the script as I have it now :
$(function () {
$('#account_balance1').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("#viewer").text(str.replace(/^\$/, ''));
}, 0);
});
$("#viewer").text($('#Website').val().replace(/^\$/, ''));
});
This is the html :
<!--This where I get the value from -->
<input type="text" class="balance" id="account_balance1" name="cardb" value=""/>
<!--the first 2 elements are where I need the values to go -->
<input data-cost="" debt="" value="" type="checkbox" name="f_2[]"/>
if you need the two attributes (data-cost and debt) to be each set to your value you need:
$("input[data-cost][debt]").attr('data-cost',str.replace(/^\$/, ''));
$("input[data-cost][debt]").attr('debt',str.replace(/^\$/, ''));
Just use that selector then
$("input[data-cost][data-debt]")
I think you're maybe having a fundamental misunderstanding of what the data attributes are for? You're aware that they will not be posted with the form? I think what you're looking for is the data function which will allow you to set the data attributes http://api.jquery.com/data/.
Perhaps you want data-cost and data-debt?
So if your input looks like this:
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" id="checkboxId" />
Then you can set the values in your javascript like this:
var value1="some value";
var value2="another value";
$('#checkboxId').data('cost', value1);
$('#checkboxId').data('debt', value2);
I don't believe having an attribute named simply "debt" as you have it above is valid.
I'd do it this way (setTimeout was useless) :
$(function () {
$('#account_balance1').on('keyup blur paste', function () {
var self = this;
var nextCheckbox = $(self).next("input[type='checkbox']");
var str = $(self).val();
$("#viewer").text(str.replace(/^\$/, ''));
nextCheckbox.data({
cost: str,
debt: str
});
/*
You won't be able to see changes if you inspect element,
so just check in console
*/
console.log(nextCheckbox.data());
});
});
And your html markup must be slightly modified :
<!--This where I get the value from -->
<input type="text" class="balance" id="account_balance1" name="cardb" value="" />
<!--the first 2 elements are where I need the values to go -->
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" />
<!--I added the viewer to check if everything works properly -->
<div id="viewer"></div>

Categories

Resources