How to make two inputfields that show the same data? - javascript

So I have one input field that needs to pop up in another place when the user changes a tab and presses a button,
but I figured tossing the div around would be too much hassle,
so is it instead possible to make two input fields but have them display the same input entered by the user?
Or is there an easier way?

Try this. Of course, make sure it is on DOM .ready().
$('#input1').blur(function() {
$('#input2').val( this.value );
});
Use .blur() to run the code when the user leaves the input1.
Use .val() to set the value of input2 to the this.value of input1.
If you need to work the reverse direction as well, just assign another handler, reversing the inputs.
$('#input2').blur(function() {
$('#input1').val( this.value );
});
EDIT: To deal with multiple inputs, give them all the same class, then use paired IDs.
Like this:
Example: http://jsfiddle.net/m3q4V/
<!-- In tab 1 -->
<input type="text" class="someClass" id="address_1" />
<input type="text" class="someClass" id="city_1" />
<input type="text" class="someClass" id="zip_1" />
<!-- In tab 2 -->
<input type="text" class="someClass" id="address_2" />
<input type="text" class="someClass" id="city_2" />
<input type="text" class="someClass" id="zip_2" />
js:
$('.someClass').blur(function() {
var parts = this.id.split('_'); // separate into parts, like 'address' and '2'
var num = (parts[1] == 2) ? 1 : 2; // invert the number between 1 and 2
// build the selector with 'address' + '_' + '1'
$('#' + parts[0] + '_' + num).val( this.value );
});

See Working Example
If you want to happen that when first text box loses focus, you need to use blur event:
$('#textbox1_id').blur(function(){
$('#textbox2_id').val(this.value);
});

Related

multiple div with same template

I have a 'users page'. I would like to give a textbox for entering the no. of users. On click of submit 'n' no of user forms need to be presented to user.
User1
first name -
last name -
User2
first name -
last name -
.
.
.
UserN
first name -
last name -
I don't know the value of 'N' upfront. So it won't be a good idea to write multiple 'divs' in my html.
Requirement:Rather I want to have a user template div. And copy the template 'n' times depending on the value of 'n' in the textbox. But I would also want all the 'divs' to have different ids like 'user1', 'user2' etc.
I cannot figure out a way to do this apart from populating my html with too many 'divs'. Would need help achiving the Requirement specified.
Looking for a template like:-
<div id="user-template" class="hidden">
<label class="lbl"><b>Handle:</b></label><input type="text" id="first_name" value=""/>
</div>
And wanted to have id="user-template" change for all new divs.
You can try something like this:
You can make a template and append it to the DOM for the number entered in the input field.
$(document).ready(function() {
$("#createForms").click(function() {
var numOfForms = $("#numOfForms").val();
var template = $('#hidden-template').html();
for (var i = 0; i < numOfForms; i++) {
$('#targetDiv').append("<p>User" + (i + 1) + ":</p>");
$('#targetDiv').append(template);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="numOfForms"></input>
<input type="button" id="createForms" value="Get Fields"></input>
<div id="targetDiv"></div>
<script id="hidden-template" type="text/x-custom-template">
<div id="user-template" class="hidden">
<p>First Name:
<input type="text" name="firstName"></input>
</p>
<p>Last Name:
<input type="text" name="lastName"></input>
</p>
<br>
</div>
</script>
A simple way is to write a function that takes the n value and returns the actual dom that you can append to some parent element on your page. A simple example below:
function createNDivs(n) {
if(!n) return;
var fragment =document.createDocumentFragment();
for(var i=0;i<n;i++) {
var div = document.createElement('div');
fragment.appendChild(div);
}
return fragment;
}

clearing input text area with dynamic input id's on button click - jQuery

Although the question title gives an impression that I want to ask one question, but there are two problems I have facing at the moment.
I have gone through few similar questions on how to clear the input text area on button click, but most of them are for fixed input class or id's.
Problem 1: I am generating rows dynamically and and all the fields are being populated using JS thus the input ID's for all text boxes are different. Now if a user enter some number on "Apply to all" input field and click the button the same number should be set to all the rows which are added in the betslip.
Problem 2: After entering individual values in the betslip input boxes and if I click "clear all" button. It should clear all the inputs entered earlier in the bet slip.
Here is the HTML structure
<div id="bets">
<div id="idNo1" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_1" type="text">
</div>
</div>
<div id="idNo2" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_2" type="text">
</div>
</div>
<div id="idNo3" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_3" type="text">
</div>
</div>
</div>
JS for adding element in the individual bets
function createSingleBetDiv(betInfo) {
var id = betInfo.betType + '_' + betInfo.productId + '_' + betInfo.mpid,
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'].toFixed(2) + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field - This is where I am creating the input fields
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text" class="betInput"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
HTML for Apply to all and Clear all button
APPLY TO ALL <input type="text">
CLEAR ALL
JS where I need to implement those 2 functions
function applyToAllBetInput() {
$('.apply').change(function() {
$(this).prevAll().find('input[type=text]').val($(this).val());
});
}
function clearAllBetInput() {
$('.clearall').click(function() {
$('div.bet').find('input').val('');
});
}
The best thing to do is remove the inline event handlers from the links, like this...
APPLY TO ALL <input type="text">
CLEAR ALL
Then, assign the event handlers in your script...
$("a.button.apply").on("click", function(e) {
e.preventDefault();
applyToAllBetInput($(this).find("input").val());
});
$("a.button.clearall").on("click", function(e) {
e.preventDefault();
applyToAllBetInput("");
});
And this would apply the value to all inputs...
function applyToAllBetInput(value) {
$("#bets div[name=singleBet] .supermid input:text").val(value);
}
If you pass a parameter into applyToAllBetInput and then set the inputs with that then you only need the one function, as they both do the same thing, but with different values. Best to only have 1 bit of code if it's only doing 1 thing, then you only have to fix it once if things change in the future :)
Please replace the id's i've given with your actual button/textarea ids (give ID's to your elements).
$('#txtApplyToAll').change(function() {
$(this).prevAll().find('input[type=text]').val($(this).val());
});
$('#btnClearAll').click(function() {
$('#txtApplyToAll').prevAll().find('input[type=text].val('');
});
There are several general suggestions I'd make before even starting to write the code. First, Why are you using longhand JavaScript when you have jQuery available? For example:
inputId = divId.document.getElementById('input');
should be simply:
inputId = $(inputId).find('input');
(or something along those lines--I'm not sure what you're after with that.)
Next, you're using inline click handlers. Instead, use event listeners:
<a href="javascript: applyToAllBetInput()" ...
Should be
$('a#my-id').click(function() { ... }
Finally, you can target all your inputs for clearing with a selector like this:
$('div.bet').find('input').val('');

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>

More than 3-Way Checkbox

I want to implement an country-selection-input. In other words, I've got a form with a 25x25px flag, which I want to be clickable - say, german as default, first click changes it to netherlands, second to swiss or w/e.
The last chosen value needs to be in my POST-Array with the other values of the form.
I've tried to accomplish this using 3-Way checkboxes with javascript, but I'm going to need more than 3 options.
Any idea on how to do this? I've thought about an input select, hiding everything but the current value - but I don't know how to submit this to change to the next value.
Thanks in advance for any input, and please don't judge me for such a question - this is my first js/html/css project. :-)
You can do something like this:
HTML
<form method="POST">
<img src="german.png" onclick="switchCountry(this);"/>
<input id="country" name="country" type="hidden" value="german" />
<input type="submit" value="Submit" />
</form>
JavaScript
var countries = ['german', 'netherlands', 'swiss'];
var switchCountry = function(img) {
var input = document.getElementById('country'),
oldValue = input.getAttribute('value'),
newValue = countries[(countries.indexOf(oldValue) + 1) % countries.length];
// Switch input value that will be posted with form
input.setAttribute('value', newValue);
// Switch graphical representation of country
img.setAttribute('src', newValue + '.png');
};
Example here http://jsbin.com/alasip/1/edit

Hide and show another element onclick of a radio button, based on value

I have 4 jquery radio buttons in my form something like this
<form:radiobutton path="lcmoption" name ="lcmoptions" id ="lock" value="lock" checked="checked"/>
<fmt:message key="lcm.form.options.lock" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="unlock" value= "unlock"/>
<fmt:message key="lcm.form.options.unlock" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="terminate" value="terminate" />
<fmt:message key="lcm.form.options.terminate" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="wipe" value="wipe" />
<fmt:message key="lcm.form.options.wipe" />
<form:radiobutton path="lcmoption" name ="lcmoptions" id="other" value="other" />
<fmt:message key="lcm.form.options.other" />
onclick of the first four radio buttons I am dynamically loading the select box using an AJAX call. When the user clicks the last option, i.e, other, I need to hide the textbox and show a text area.
I tried using:
$("input:radio[name=lcmoption]").click(function() {
if(type=="other")
{
$([name="reasonsList"]).css("display",none");
$([name="otherreasonsList"]).css("display", "block");
}
else
{
// AJAX CALL to load dropdown (for other options)
}
}
But this did not work. I also tried:
$([name="reasonsList"]).hide();
$([name="otherreasonsList"]).show();
This shows both the dropdown and text area. Can anyone help me on hiding reasonsList div and show otherreasonsList div onclick of a radio button with other value?
There's all kinds of syntax errors in the code you posted.
For instance, you need to quote your selector strings as text, and an attribute value in an attribute selector ([name=something]) can be either an unquoted single word or a quoted string.
In this case, just leave it out:
$('[name=reasonsList]').show();
Also, instead of $.click(), I would use $.change(), which will detect when the radio value has changed.
$("input:radio[name=lcmoptions]").change(function(){...});
See notes in comments:
// First line looks ok, but I would use a .change() handler
// Also, I just noticed you're:
// "input:radio[name=lcmoption]"
//
// But shouldn't it be:
// "input:radio[name=lcmoptions]"
//
// See lcmoptions vs lcmoption (no s on second); it's lcmoptions
// in your template code. I don't know what path="lcmoption" means,
// but I think name="lcmoptions" is what you need to use to select.
$("input:radio[name=lcmoption]").click(function() {
// What is type? I think you mean this.value or $(this).val()
// Don't forget to lowercase the comparison, so other matches
// Other.
if (this.value.toLowerCase() == "other")
{
// The selector needs to be quoted as a string, ie:
// '[name="reasonsList"]'
//
// Also, jQuery has a shortcut method, $(sel).hide();
$([name="reasonsList"]).hide();
// The same thing here, you need to quote that string or
// alternatively, since it's a single word, leave the quotes
// out of the selector, ie:
// $('[name=otherreasonsList]')
//
// Again, jQuery has a shortcut method, $(sel).show();
$('[name=otherreasonsList]').show();
}
// Don't know if you missed this in the example, but you need });
// to close the $.click() function.
});
And your second attempt:
// Same problem as above, you need to quote the string for the
// selector, ie:
// $('[name=reasonsList]')
//
// With inner quotes, but here they're unnecessary.
$('[name="reasonsList"]').hide();
//
// Without inner quotes on name value
$('[name=otherreasonsList]').show();
For what you're wanting to do, you can:
$(document).ready(function(){
// This is called caching, which is a good practice to get
// get into, as unless you need to requery due to dynamic
// changes, selecting them only once and reusing will give
// you better performance.
var $lcmoptions = $('input:radio[name=lcmoptions]'),
$textbox = $('[name=textbox]'),
$textarea = $('[name=textarea]');
$lcmoptions.change(function(){
// Note I this.value.toLowerCase() the comparison value
if (this.value.toLowerCase() === 'other') {
$textbox.hide();
$textarea.val($textbox.val()).show();
} else {
$textarea.hide();
$textbox.val($textarea.val()).show();
}
});
});
For more information on caching, see:
Does using $this instead of $(this) provide a performance enhancement?
This is assuming your client-side markup looks something like:
<input type="radio" name="lcmoptions" id="unlock" value= "lock"/> Lock
<input type="radio" name="lcmoptions" id="unlock" value= "unlock"/> Unlock
<input type="radio" name="lcmoptions" id="terminate" value="terminate" /> Terminate
<input type="radio" name="lcmoptions" id="wipe" value="wipe" /> Wipe
<input type="radio" name="lcmoptions" id="other" value="other" /> Other
<div>
Enter text:
<input type="text" name="textbox" value="test text stuff"/>
<textarea name="textarea"></textarea>
</div>
http://jsfiddle.net/LthAs/
Have tried this mine working fine
if(document.getElementById('other').checked==true)
{
$("#txtboxID").hide(350);
$("#txtareaid").show(350);
}
try this, u can put this on change event or click event.
if ($("radio[#name='lcmoptions']:checked").val() == 'other')
$("#otherreasonsList").show();

Categories

Resources