copy text from one textbox to another based on a condition - javascript

I am working on javascript.
Consider two textboxes tb1 and tb2 respectively
The value present in tb1 should be copied in tb2 based on a condition. If the condition is true nothing needs to be copied. If the condition is false the value in tb1 should also be initialised to tb2. Is it possible..

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div>
<span>tb1:</span>
<input id="tb1" type="text" value="TextBox Value 1"/>
</div>
<div>
<span>tb2:</span>
<input id="tb2" type="text" value="TextBox Value 2"/>
</div>
<input type="button" onclick="exchange()" value="Exchange">
<script type="text/javascript">
function exchange(){
var tb1 = document.getElementById('tb1');
var tb2 = document.getElementById('tb2');
var condition = function(){
return true;
};
if(condition()){
var buf = tb1.value;
tb1.value = tb2.value;
tb2.value = buf;
}
}
</script>
</body>
</html>

Here's a function that can do what you need:
function compareAndCopy() {
var tb1 = document.getElementById("tb1");
var tb2 = document.getElementById("tb2");
if (tb1.value == "hey") {
tb2.value = tb1.value;
} else {
alert("No match");
}
}
//Add a handler
document.getElementById("tb1").onblur = compareAndCopy;
It is currently checking if tb1 equals hey on blur.
Working demo: http://jsfiddle.net/4L5pE/

yes, this is possible. You need to define when you want it to happen. onkeypress, or onblur of first text box you can call a function that validates your condition and then copies the values.
tb1.onblur(function(){ if(condition) tb2.value = tb1.value }
the code above will not work, its just a pseudo.

Related

Update a JS array value with a global variable based on checkbox (true/false) form input

I'm using a WorldPay JS function to create a payment form. This function creates a TOKEN that can be reusable or not. I need to update the 'reusable' flag based on a form input (checkbox) but I can't get the global variable (reuse) to update. I've created a function CHECKED that updates the variable but the WorldPay JS just ignores it. I think is due the window.onload status, but I don't know how to fix it. Any help would be greatly appreciated.
<?php
include('./header.php');
require_once('./init.php');
?>
<html>
<head>
<title></title>
<meta charset="UTF-8" />
<script src="https://cdn.worldpay.com/v1/worldpay.js"></script>
<script type='text/javascript'>
var reuse = false;
function Checked(){
reuse = document.getElementById('check').checked;
Worldpay.submitTemplateForm();
}
window.onload = function() {
Worldpay.useTemplateForm({
'clientKey':'ENTER CLIENT KEY',
'form':'paymentForm',
'paymentSection':'paymentSection',
'display':'inline',
'type':'card',
'reusable': reuse,
'saveButton':false,
'callback':function(obj){
if (obj && obj.token && obj.paymentMethod) {
var _el = document.createElement('input');
_el.value = obj.token;
_el.type = 'hidden';
_el.name = 'token';
document.getElementById('paymentForm').appendChild(_el);
var _name = document.createElement('input');
_name.value = obj.paymentMethod.name;
_name.type = 'hidden';
_name.name = 'customer';
document.getElementById('paymentForm').appendChild(_name);
document.getElementById('paymentForm').submit();
}
}
});
}
</script>
</head>
<body>
<form action="./test.php" id="paymentForm" method="post">
<!-- all other fields you want to collect, e.g. name and shipping address -->
<div id='paymentSection'></div>
<div>
<input type="checkbox" id='check'>
<input type="submit" value="Place Order" onclick="Checked()" />
</div>
</form>
</body>
</html>
NOTE: I've removed the client ID so the code won't run.
Have you tried to use function "checked" on window.onload like this:
window.onload = function() {
Worldpay.useTemplateForm({
//code....
)}
function Checked(){
//code....
}

How to take an input that is equal to 10 and perform a function that says awesome to the screen

I'm trying to create a function that takes a users input and if it equals 10 then perform a function that will eventually print fizzbuzz to the screen from 0-10 but for now I'm just trying to get it to say "awesome" if the input == 10. Here is the code.
<!DOCTYPE html>
<html>
<head>
<title>Fizzbuzz Input Field</title>
<script src="scripts.js"></script>
</head>
<body>
<form>
<input type="number" id="userInput"></input>
<button onclick="fizzBuzz()">Go</button>
</form>
</body>
</html>
window.onload = function() {
alert("Page is loaded");
};
var fizzBuzz = function() {
var userInput = document.getElementById("userInput");
fizzBuzz.onclick = function() {
if(userInput.value == 10) {
document.write("awesome");
};
};
}
Grab the element from the input, in this case, "userInput". grab your button by querying it, or putting an id on it etc... Don't bother with putting a function on the HTML, avoid bad practice. Add an event listener to the button, check to see if it equals 10 and append your text, preferably somewhere suitable.
var input = document.getElementById("userInput");
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click', function(a) {
if (input.value === '10') {
button.after("awesome");
}
})
<input type="number" id="userInput">
<button>Go</button>
I think what you are looking for is eval before using it, you should search the web for why eval is evil.
What you want is something like this:
var button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
// First we get the numeric value written to the input (or NaN if it's not a number)
var inputValue = parseInt(document.getElementById('userInput').value, 10);
// Define the element to which write the text (you usually want a DIV for this)
var outputElement = document.getElementById('outputDiv');
if ( ! isNaN(inputValue) ) {
outputElement.innerHTML = "awesome!";
}
else {
// The value is not a number, so just clean the result
outputElement.innerHTML = "";
}
});
Of course, for this to work, you should have at least:
<input type="number" id="userInput" />
<button id="myButton">Go</button>
<div id="outputDiv"></div>
I don't have any idea how you want the awesome to be displayed. Made it an alert. Have fun.
<script>
function fizzBuzz() {
var fizzBuzz = document.getElementById("userInput").value;
if(fizzBuzz != 10){
alert('Number is not equal to ten!');
}else {
alert('awesome');
}
}
</script>
You are setting a property 'onclick' of function 'fizzBuzz',
you should use the input event.
var userInput = document.getElementById('userInput');
userInput.oninput = function() {
if( this.value == 10 ) alert('awesome');
}

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

JavaScript Replace Method for multiple textboxes

Can anyone please tell me how I can use the replace method to replace a character if it occures in more than one textbox without having to write separate function for each textbox.
The code below is the basic way to use the replace method but it only allows for one textbox.
I'm sure I need a loop in there but I'm not sure how to use that without affecting the replace method.
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript">
function stringReplace(form) {
var replaceStr = form.textfield1.value
var pattern = /\'/g;
form.textfield1.value = replaceStr.replace(pattern, "''");
}
</script>
</head>
<body>
<form name="form1" method="post" action="JStest_redirect.asp">
<p>fname:
<input type="text" name="textfield1" size="20">
</p>
<p>lname:
<input type="text" name="textfield2" size="20">
</p>
<p>
<input onclick="return stringReplace(form)" type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>
You can do this:
function stringReplace(form) {
var $inputs = $(form).find('input:text');
var pattern = /\'/g;
$inputs.each(function () {
this.value = this.value.replace(pattern, "''");
});
return false; // Prevent the form from being submitted
}
This would find all the input type text within the form and replace their values.
If you wish to do it without jquery, you can use the getElementsByTagName() method.
function stringReplace(form) {
var pattern = /\'/g;
var inputs = form.getElementsByTagName("input");
var input;
for (var i = 0; i < inputs.length; i++) {
input = inputs[i];
if (input.type = 'text') {
var replaceStr = input.value;
input.value = replaceStr.replace(pattern, "''");
}
}
return false;
}
You seem to want
function stringReplace(form) {
$('input[type=text]').val(function(_, v) {
return v.replace(/\'/g, "''");
});
return false;
}
I added a return false at the end to prevent the form to be submitted on click. You probably want to have a separate button in your case.
I believe that fisrt you have to take all the values
function GetValue(){
var Contain = "";
$("#form1 :text").each(function(){
//add replace code here
});
}
You can add onchange function to all of you text input
function stringReplace(textField) {
var replaceStr = this.value
var pattern = /\'/g;
this.value = replaceStr.replace(pattern, "''");
}
and than you add
<input type="text" name="textfield1" size="20" onchange="stringReplace(this);">

Retrieving the value of Dynamically Created elements

i Have created a HTML form , in this form when i Click on a button it creates input text fields based on a predefined criteria , this works fine .
now when i try and retrieve the value entered in those created text fields using alert i am not able to do so .
i have two questions
What is the best way to retrieve inputs from the dynamically created text fields?
can you tell me why the code i have written does not work
HTML code
<BODY>
<FORM>
<BR/>
<div align = "center">
<br /><br />
<INPUT type="button" value="Click To Enter Values" onclick="getkeywords()"/>
</div>
<div align="center" id="d_div">
<form name="permavalues" id="d_form">
</form>
<br/> <br/>
</div>
</FORM>
THe javascript code that i am using is this :
function getkeywords() {
var index_array = new Array();
var myString = "one and a two and a three = $ and four = $ and five = $";
var splitresult = myString.split(" ");
for(i = 0; i < splitresult.length; i++)
{
if (splitresult[i] == "$" && i > 1 ) //retireving the keywords..
{
add(splitresult[i-2]);
}
}
}
The add function which is called in getkeywords:
function add(s) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", s);
element.setAttribute("name", s);
element.setAttribute("id", s);
var foo = document.getElementById("d_form");
//Append the element in page (in span).
foo.appendChild(element);
alert("Value=" + document.getElemebtById(s).value);
}
I think that i must have a mistake with element.setAtrribute("id",s);
The major problem is you can't put form inside another form. Please remove you HTML code line 2 and line 13.
Another problem is your typo, as IvanL said.
Other code are fine.
Give you fully tested work code as below.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>test</title>
<script language="javascript">
function getkeywords() {
var index_array = new Array();
var myString = "one and a two and a three = $ and four = $ and five = $";
var splitresult = myString.split(" ");
for(i = 0; i < splitresult.length; i++)
{
if (splitresult[i] == "$" && i > 1 ) //retireving the keywords..
{
add(splitresult[i-2]);
}
}
}
function add(s) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", s);
element.setAttribute("name", s);
element.setAttribute("id", s);
var foo = document.getElementById("d_form");
//Append the element in page (in span).
foo.appendChild(element);
alert("Value=" + document.getElementById(s).value);
}
</script>
</head>
<BODY>
<BR/>
<div align = "center">
<br /><br />
<INPUT type="button" value="Click To Enter Values" onclick="getkeywords()"/>
<br><br><br>
<input type="button" value="add" onclick="add('tt')">
</div>
<div align="center" id="d_div">
<form name="permavalues" id="d_form">
</form>
<br/> <br/>
</div>
</body>
</html>
What is the best way to retrieve inputs from the dynamically created
text fields?
I would use JQuery to traverse the form for all text input elements and retrieve their respective values.
Alternatively, you could give each of the text fields a common name like "txt_" and then append an incremental ID to the string (I.E. -- txt_1, txt_2, txt_3, ...) then programmatically iterate over your form fields that match until you've reached a value that represents the total number of available form fields. That value could be a javascript integer.
For example...
$("form input[type='text']").each( function()
{
// gets text value for each field in the form
var textFieldValue = this.value;
// do stuff
});
Have a look on the Jquery code for getting All Input Value.
$(document).ready(function()
{
$('form#d_form input[type="text"]').each(
function()
{
alert($(this).val());
});
});

Categories

Resources