Write to a text field and simultaneously copy to another textfield - javascript

I have 2 textfield with different ids. what I want to achieve is that when I write to textfield1 that content is immediately copied to the second one and if I edit the second one the first one remains unchanged, but also if I go back to first one and edit it, the content is just appended to the second one.
<input type="text" name="field1" id="f1" />
<input type="text" name="field2" id="f2" />
Code :
<script type="text/javascript">
$(document).ready(function(){
$("#f1").keyup(function(){
$('#f2').val($('#f1').val());
});
});
</script>

Try this,
$(document).ready(function () {
$("#f1").keypress(function (e) {
var val = $('#f2').val();
var code = e.which || e.keyCode;
$('#f2').val(val+(String.fromCharCode(code)));
});
});
Live Demo

you can write like this
<script type="text/javascript">
$(document).ready(function(){
$("#f1").keyup(function(){
var f2Text = $('#f2').val() + $(this).val();
$('#f2').val(f2Text );
});
});
</script>

you can also use the Angular JS which is more efficient and easy to use.
AngularJS
Angular JS will help you to develop SPA(Single Page Application).

Related

Set to true state a checkbox in a different page(javascript)

Here's the Script.
javascript
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
$('#website-design').attr('checked',true);
window.location.href = "/contact";
}
}
}
I want to check my checkboxes when I click the button with an id=website-design-check.
Here is my HTML.
first.html
<a href="/contact" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
Here's the second HTML file where checkbox is.
second.html
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
Now how can I achieve what I want base on the description given above. Can anyone help me out guys please. I'm stuck here for an hour. I can't get any reference about getting a checkbox state from another page.
To do this, you can modify your button link and add in additional parameters that you can then process on the next page.
The code for the different pages would be like:
Edit: I changed it to jQuery, it should work now.
Script
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
window.location.href = "second.html?chk=1";
}
}
second page
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script type="text/javascript">
var url = window.location.href.split("?");
if(url[1].toLowerCase().includes("chk=1")){
$('#website-design').attr('checked',true);
}
</script>
since your checkbox is in another html page, so it's totally normal that you can't get access to it from your first html page!
what I can offer u is using the localstorage to keep the id and then use it in your second page to check if it's the ID that u want or not.
so change your function to this :
function linkPageContact(clicked_id){
localStorage.setItem("chkId", "clicked_id");
window.location.href = "/contact";
}
then in your second page in page load event do this :
$(document).ready(function() {
var chkid = localStorage.getItem("chkId");
if(chkid === 'website-design-check'){
$('#website-design').attr('checked',true);
});
You can't handle to other sites via JavaScript or jQuery directly. But there's another way. You can use the GET method to achive this.
First you need to add to the link an attribute like this in your first.html:
/contact?checkbox=true
You can change the link as you want with JavaScript.
Now it will refer to the same page but it can be now different. After that you can receive the parameter with this function on the second.html.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
I got it from this post thanks to Bakudan.
EDIT:
So here is an short theory.
When the user clicks the button on the first page, then you change the link from /contact to /contact?checkbox=true. When the user get forwarded to second.html then you change the checkbox depending on the value, which you got from the function findGetParameter('checkbox').
As all have mentioned you need to use session/query string to pass any variable/values to another page.
One click of the first button [first page] add query string parameter - http://example.com?chkboxClicked=true
<a href="secondpage.html?chkboxClicked=true>
<button>test button</button>
</a>
In the second page- check for the query string value, if present make the checkbox property to true.
In second page-
$(document).ready(function(){
if(window.location.href.contains('chkboxClicked=true')
{
$('#idOfCheckbox').prop('checked','checked');
}
})
Add it and try, it will work.
Communicating from one html file to another html file
You can solve these issue in different approaches
using localStorage
using the query parameters
Database or session to hold the data.
In your case if your application is not supporting IE lower versions localStorage will be the simple and best solution.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<a href="contact.html" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
<script>
function linkPageContact(clicked_id) {
localStorage.setItem("chkId", clicked_id);
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script>
$(document).ready(function () {
var chkid = localStorage.getItem("chkId");
if (chkid === 'website-design-check') {
$('#website-design').attr('checked', true);
}
});
</script>
</body>
</html>

External JavaScript file issues

Now this is just for reference for a future project but I am trying to call a function that reads in a string but displays a float after. So I first check the string then display a random number. The problem I am having, I think, is with the document.getElementById part. Any suggestions??
HTML File:
<html>
<body>
<input type="text" id="letter" value=""/><br/>
<input type="button" value="LETS DO THIS!" onclick="floatNum();"/></br>
<script type="text/javascript" src="letNum.js"></script>
</body>
</html>
External JS File:
function floatNum()
{
var val1 = document.getElementById("letter");
if (isNaN(val1)
{
alert(Math.random())
}
}
the following code is working:-
in your code,you missed closing parenthesis ")" near to "if condition"
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>demo</title>
<script type="text/javascript">
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value))// using input fields value not the whole object
{
alert(Math.random());
}
}
</script>
</head>
<body>
<input type="text" id="letter" value="" /><br />
<input type="button" value="LETS DO THIS!" onclick="floatNum();" />
</body>
</html>
Yes, you want to pass in the element in the function, like so:
<input type="button" value="LETS DO THIS!" onclick="floatNum(document.getElementById('letter'))"/></br>
And in your JS
function floatNum(el)
{
if (isNaN(el)
{
alert(Math.random())
}
}
In case of a reusable function - try not to make it dependent on your DOM. Think about what would happen if you rename your element or want to use this function again. You couldn't before - now you can.
The problem is on this line:
var val1 = document.getElementById("letter");
It should be:
var val1 = document.getElementById("letter").value;
The first sets val1 to the DOM element representing the input tag, the second sets it to the text value of the input tag (its contents).
You need to process the value of input field not the input field itself.
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value) // using input fields value not the whole object
{
alert(Math.random())
}
}
You don't grab the value of the input, but the input itself.
Correct code would be :
var val1 = document.getElementById("letter").value;

JQuery not working through Google's CDN

For a few hours I've been trying to understand what's wrong. My purpose is to enable a button after textfields are filled. Code seems fine according to my test at JSFiddle but it's still not working on my server. Am'I missing something or is this a server problem (which is hard to believe since javascript is client-side)?
PS: I'm not expert at HTML, so I don't know how to identate it's syntax; if it's not that readable I'm sorry and would appreciate an edit-help. thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
</script>
</head>
<body>
<section class="container">
<div class="OpenKore">
<div id="absolute">
<form method="GET" action="generate.php">
<fieldset>
<legend><h1>OpenKore Automatic Config:</h1></legend>
LOGIN:
<p><input type="text" id="id_login" name="login_value" value="" placeholder="Login"></p>
SENHA:
<p><input type="text" id= "id_senha" name="senha_value" value="" placeholder="Senha"></p>
PIN:
<p><input type="text" id="id_pin" name="pin_value" value="" placeholder="PIN"></p>
<input id="apply" type="submit" name="commit" disabled value="Gerar Configurações">
</fieldset>
</form>
</div>
</div>
</section>
</body>
</html>
When the browsers reads your HTML page, it reads top to bottom. When it gets to your <script> tags it runs them. Now it us doing this before it has got to the rest of the page, i.e. before it even knows about any body or form or input:text tags, so even though you code will run, it will simply not do anything because none of the elements on the page exist yet.
JavaScript 101, make the code run after the page has loaded, if you need to access elements on the page. How do you do that? either put the code at the bottom of the page (move your <script> tags to just before the </body> tag), or wrap your code in a function that is executed after the browser has finished loading the page. Now jQuery has a very helpful way of doing this for you, pass a function to jQuery and it will be executed after the page is loaded.
jsFiddle does this automatically for you, hence the drop down in the top left corner saying 'onLoad'
i.e. your code
$(); //this is the jQuery function
//This is your code wrapped in a function called 'yourCode'
function yourCode() {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
}
$(yourCode); //this is passing the jQuery function a function,
//this will now be execute once the page is loaded
//or what most people do, pass in as an anonymous function
//which eliminates a step
$(function () {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
});
as suggested by #j08691 I would suggest reading about the document ready in jQuery here

How to pass Variable from External JavaScript to HTML Form

I have been trying to pass a value from an external javascript file to an HTML form with no luck. The files are rather large so I am not sure I can explain it all but ill try.
Basically a user clicks a link then a js file is initiated. Immediately after a new HTML page loads.
I need this value passed to the HTML page in a form field.
Javascript:
var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };
document.getElementById('adcode').value = divElement();
Afterwards it should be passed to this Form field
HTML Form Field:
<p>Ad Code:<br>
<input type="text" name="adcode" id="adcode"/>
<br>
</p>
Thanks for any help!
Your HTML file needs to reference the JavaScript js file. Have a function in your JavaScript that returns the value that you need. Use JavaScript (I like jQuery) to set the form field to what you need.
JS file:
<script>
var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };
document.getElementById('adcode').value = divElement();
function GetDivElement() {
return divElement();
}
</script>
HTML file:
<p>Ad Code:
<br />
<input type="text" name="adcode" id="adcode"/>
<br />
</p>
<script src="wherever that js file is" />
<script>
window.onload = function() {
document.getElementById('adcode').value = GetDivElement();
}
</script>
Although, really, this might do what you want (depending on what you are trying to do):
<p>Ad Code:
<br />
<input type="text" name="adcode" id="adcode"/>
<br />
</p>
<script src="wherever that js file is" />
<script>
window.onload = function() {
GetDivElement();
}
</script>
Can it be this?:
function divElement(divCode){
return divCode;
}
divElement(document.getElementById('adcode').value);

jQuery Input Mask Not Working

I am trying to set up a donations page for people to give money to a non-profit and allow them to specify the uses of the money. I have it set up that it totals the amounts the giver puts in each field as they enter amounts. I am trying to add an input mask in each field, but it is just making my JavaScript crash and not do anything. Here is the code I currently have that works perfectly before any masks:
<script src="/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready( function() {
var calcTot = function() {
var sum = 0;
$('.toTotal').each( function(){
sum += Number( $(this).val() );
});
$('#giveTotal').val( '$' + sum.toFixed(2) );
}
calcTot();
$('.toTotal').change( function(){
calcTot();
});
});
</script>
'toTotal' is the class name given to all the input boxes that need to be added up; that is also the class that needs a mask. 'giveTotal' is the id of the total field.
I have tried several variations I have found on StackOverflow and other sites.
Full Code:
<html>
<head>
<script src="/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready( function() {
//This is one of the masking codes I attempted.
$('.toTotal').mask('9.99', {reverse: true});
//other options I have tried:
//$('.toTotal').mask('9.99');
//$('.toTotal').mask('0.00');
//$('.toTotal').inputmask('9.99');
//$('.toTotal').inputmask('mask', {'mask': '9.99'});
var calcTot = function() {
var sum = 0;
$('.toTotal').each( function(){
sum += Number( $(this).val() );
});
$('#giveTotal').val( '$' + sum.toFixed(2) );
}
calcTot();
$('.toTotal').change( function(){
calcTot();
});
//I have tried putting it here, too
});
</script>
<title>Addition</title>
</head>
<body>
<input type="text" class="toTotal"><br />
<input type="text" class="toTotal"><br />
<input type="text" class="toTotal"><br />
<input type="text" id="giveTotal">
</body>
</html>
There is no masking library script referenced in the sample code. You need to download the Digital Bush Masked Input Plugin Script and copy it into your JS folder.
Then add following script reference after 'jquery.js' line:
<script src="/js/jquery.maskedinput.min.js"></script>

Categories

Resources