Trigger jquery function on input when clicking other input - javascript

I'm creating a dinamically added input form. I want to make it so when an input loses the focus, its value get .00 appended to it. So far I tried this:
$(".money-input").on("click", function(e) {
e.stopPropagation();
});
$(document).on("click", function (e) {
$(".money-input").each(function() {
var valTemp = $(this).val();
if ((valTemp.indexOf(".00") < 0) && (valTemp != "")) {
valTemp += ".00";
$(this).val(valTemp);
}
});
});
My problem is, it only works when I click on other divs but inputs. Additionally what I also want to achieve is when I edited something on one input then switch focus to other input, the previous input value got appended by .00.
Any help appreciated! :)

Use
$(".money-input").live('blur', function() {
var valTemp = $(this).val();
if ((valTemp.indexOf(".00") < 0) && (valTemp != "")) {
valTemp += ".00";
$(this).val(valTemp);
}
});
blur is your 'lost-focus' event. With using live it will attach this event to elements that exists now and in the future (since you are dynamically adding a form).

The requested behavior is odd...use the step attribute instead:
<input type='number' step='01'>
The minimum requirements to have a floating point value in an input is to have: type="number" and step attributes. In the following Demo there are 3 forms with 2 inputs each for a total of 6 inputs.
The first 2 inputs have no step attribute.
The second pair are dynamically created. The first input has no step attribute whilst the second one does.
The last pair of inputs have the step attribute.
I modified the styles so when an input has the step attribute, its borders are red dashed lines. It's not necessary to do this, it's just for demonstration purposes.
There is a jQuery on event handler registered on 2 events, one is blur event and the other is the change event. These events trigger the same handler which will set the step attribute to an input upon the triggering of either change or blur events.
Demo
$('#form1').append("<input id='i2' class='money' type='number' value='0.00'>").append("<input id='i3' class='money' type='number' value='0.00' step='.01'>");
$('.money').on('blur change', function(e) {
if ($(this).val() > 0) {
$(this).attr('step', '.01');
}
});
input[step*=".01"] {
border: 1px dashed red
}
<form id='form0'>
<input id='i0' class='money' type='number' value='0.00'>
<input id='i1' class='money' type='number' value='0.00'>
</form>
<form id='form1'></form>
<form id='form2'>
<input id='i4' class='money' type='number' value='0.00' step='.01'>
<input id='i5' class='money' type='number' value='0.00' step='.01'>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Animated form, how to check input value on page refresh?

I have a form which uses dynamic styling. Consider this html
<div class="field-name field-form-item">
<label class="placeholder" for="name">Name</label>
<input class="form-input" id="name" type="text" name="name" maxlength="50" size="30">
</div>
The label is ABOVE the input, with CSS. When you click the label :
$('.placeholder').on('click focus', function() {
$(this).addClass('ph-activated');
$(this).siblings('input').focus();
})
Then the label is animated and let the user type in the input.
If the user dont wan't to write anything, the animation goes back, and hide input field :
$('input').on(' blur', function(){
if ($(this).val().length === 0) {
$(this).siblings('label').removeClass('ph-activated');
}
});
That's alright.
But when a user fill the input, THEN refresh the page and its browser didn't reset input fields(ie firefox) : the label is above the input, even if the latter is not empty.
I tried this :
$(document).ready(function() {
if ($('input').val().length) {
$(this).siblings('label').addClass('ph-activated');
}
})
But it doesn't seem to trigger, I tried several ways to write this function. Up to now I never managed to give the class ph-activated to a label with a filled input on page refresh.
Sorry I can't fiddle this. I just have far too much html/css/js/php to copy paste
Well you are targeting wrong element in $(document).ready because you are referring label with this thinking that $(this) is input whereas it is document. So try applying below code and I hope there will be multiple input elements in page, so I've used $.each and looping through all the inputs
$(document).ready(function() {
$('input').each(function(){ //loop through each inputs
if ($(this).val().length) {
$(this).siblings('label').addClass('ph-activated');
}
});
})
DEMO - Inspect the label and you will find ph-activated class added to label
Try this one:
$(document).ready(function() {
var length = $('input').filter(function( index ) {
return ($(this).val() !== '');
}).length;
if (length > 0) {
$(this).siblings('label').addClass('ph-activated');
}
})

jquery selecting dynamic class id inside dynamically created div

I have some JS that dynamically creates a new div (inputs inside of a form). It works great. I separately have some jquery that checks a dropdown input, and shows a separate div if a specific selection is clicked. It works great.
If I try to use the jquery to show a separate div inside one of the dynamically created ones, it does not work. The first instance of it does work, but none of the dynamically created ones. After searching around, it looks like I need a delegation, but I can't seem to figure it out for my specific situation.
The JSFiddle: http://jsfiddle.net/Xyzeg/ (change the "CPI" dropdown in the first field, for the event to go off). The fiddle includes the other JS for dynamically creating the divs.
Any pointers would be appreciated.
<div style="float:left">
<div id='dynamicInput'>Pension 1: Amount: $<input type='text' name='adjustmentInputs[]' value='0' size='13' maxlength='20'>Start Year:
<input type='text' name='adjustmentInputs[]' value='2032' size='5' maxlength='6'>
<input type='hidden' name='adjustmentInputs[]' value='2100'>
<select name='adjustmentInputs[]'>
<option value='InflationAdjusted'>Inflation Adjusted</option>
<option value='NotInflationAdjusted'>Not Inflation Adjusted</option>
</select>by
<select name='adjustmentInputs[]' class='pensionAdjustment1'>
<option value='CPI'>CPI</option>
<option value='constantPercentage'>Constant %</option>
</select>
<div id='constantPercentageText1' style='display: none'># <input type='text' name='adjustmentInputs[]' value='3' size='5' maxlength='6'>%</div>
</div>
<input type="button" value="Add another Portfolio Adjustment" onClick="addInput('dynamicInput');">
</div>
<script>
$("[class*=pensionAdjustment]").change(function() {
var n = $(this).attr('class').replace('pensionAdjustment', '');
var newId = "constantPercentageText" + n;
var selectedItem = $(this).children('option:selected');
if ($(this).val() == 'constantPercentage') {
$("#constantPercentageText" + n).css('display', 'inline');
$("#constantPercentageText" + n).show();
} else {
$("#constantPercentageText" + n).css('display', 'none');
}
});
</script>
You need to delegate with newly created elements!
Change this line
$("[class*=pensionAdjustment]").change(function() {
to
$(document).on('change',"[class*=pensionAdjustment]", function() {
You can use
$(document).on('change', '[class*=pensionAdjustment]', function(){
// your code
});
It would be better if you use a parent div, instead of document.
Update : The elements you are injection dynamically to the DOM were not present when the event was registered, so new elements are not firing the event. Using event delegation, (registering the event on a parent element) this could be solved because when any element fires an event, the event bubbles up to the last element (upwards) it can find and this way the parent element is being triggered but behind the scene, something like following is happening
e = e || window.event;
var el = e.target || e.srcElement;
You may check this.
You have to bind the event to a parent element, then filter down to the one you want. This way it doesn't matter when the element is added, it will always work. This is called delegation. You delegate the task of handling the event to another element.
$(document).on('change', "[class*=pensionAdjustment]", function(){
var n = $(this).attr('class').replace('pensionAdjustment', '');
var newId = "constantPercentageText" + n;
var selectedItem = $(this).children('option:selected');
if ($(this).val() == 'constantPercentage') {
$("#constantPercentageText" + n).css('display', 'inline');
$("#constantPercentageText" + n).show();
} else {
$("#constantPercentageText" + n).css('display', 'none');
}
});

Disabling a textbox when the other textbox have a value HTML

im sorry for this question but how can i disable a textbox if another textbox have a value??
I already try this code but its not working,, sorry for the noob question T_T
function disable(downpayment,full_payment)
{
if ( downpayment.value.length >= 1 )
document.getElementById(full_payment).disabled = true;
else
document.getElementById(full_payment).disabled = false;
}
</script>
<input name="downpayment" id="downpayment" type="text" onselect="function disable(downpayment,full_payment);" style="width:250px" />
</p>
<p>
<input name="full_payment" id="full_payment" type="text" style="width:250px" />
If you want to stay with plain JavaScript:
// finding the relevant elements *outside* the function
var downpayment = document.getElementById('downpayment'),
full_payment = document.getElementById('full_payment');
function enableToggle(current, other) {
/* 'current' is the element that currently has focus
'other' is the other input element, that does not have focus.
1. if the 'current' value of the focused/active element, once the whitespace
is removed, is greater than 0 (so it has something in it other than whitespace,
the disabled property of the 'other' element is true,
2. if the 'current' element has only whitespace, and/or a zero-length value,
the 'other' element's disabled property is false.
*/
other.disabled = current.value.replace(/\s+/,'').length > 0;
}
// using the onkeyup event to call a function on the elements.
downpayment.onkeyup = function () {
enableToggle(this, full_payment);
}
full_payment.onkeyup = function () {
enableToggle(this, downpayment);
}
This works with the following HTML:
<input name="downpayment" id="downpayment" type="text" style="width:250px" />
<input name="full_payment" id="full_payment" type="text" style="width:250px" />
JS Fiddle demo.
If you're using jQuery already, then you can either nest the above into jQuery's $(document).ready(function(){ /* the code in here */});, or switch to a jQuery-only solution, such as Alex's.
To stick with plain-JavaScript, and avoiding explaining how to set up an equivalent DOM-ready event, put the following at the end of your HTML content, just before the closing </body> tag:
<script>
var downpayment = document.getElementById('downpayment'),
full_payment = document.getElementById('full_payment');
function enableToggle(current, other) {
other.disabled = current.value.replace(/\s+/,'').length > 0;
}
downpayment.onkeyup = function () {
enableToggle(this, full_payment);
}
full_payment.onkeyup = function () {
enableToggle(this, downpayment);
}
</script>
(This is exactly the same JavaScript as above, with the comments stripped out, but wrapped in <script></script> tags)
Putting this at the bottom of the HTML means that the elements exist in the DOM prior to your trying to assign event-handlers to them.
Incidentally, with adjusted HTML, to give:
<form>
<!--
I associated the relevant elements with a class-name 'enableToggle',
you don't have to, it just reduces the work the jQuery has to do later
when using siblings('.enableToggle') to find the relevant elements.
-->
<div>
<label for="downpayment">Downpayment</label>
<input name="downpayment" class="enableToggle" id="downpayment" type="text" style="width:250px" />
<label for="full_payment">Full payment</label>
<input name="full_payment" class="enableToggle" id="full_payment" type="text" style="width:250px" />
</div>
</form>
The following jQuery could be used:
// binds both event-handler to both 'keyup' and 'paste' events.
$('.enableToggle').on('keyup paste', function(){
/* 'curVal' is a Boolean (true or false) depending on whether there's
a value other than whitespace */
var curVal = $(this).val().replace(/\s+/g,'').length > 0;
/* sets the 'disabled' property of the sibling elements of the current
element, as long as those siblings have the class 'enableToggle'
(this avoids having to explicitly identify all the elements you want
to act on). */
$(this).siblings('.enableToggle').prop('disabled', curVal);
});
JS Fiddle demo.
You have tagged the question jQuery, so it's as simple as...
$("#downpayment").on("change paste", function() {
$("#full_payment").prop("disabled", this.value.length);
});
As soon as your down payment has some content in it (even if it's a space, if that's not ideal, $.trim() the input before you check its length property) then it will enable the full payment.
$(document).ready(function()
{
$(".PaxHeads").on('keypress','input[name="DebitAmount"]',function()
{
var myLength = $('input[name="DebitAmount"]').val().length;
if (myLength!=0)
{
$('input[name="CreditAmount"]').attr("disabled", "disabled");
}
else
{
$('input[name="CreditAmount"]').removeAttr("disabled");
}
});
$(".PaxHeads").on('keypress', 'input[name="CreditAmount"]', function()
{
var myLength1 = $('input[name="CreditAmount"]').val().length;
if (meLength1!=0)
{
$('input[name="DebitAmount"]').attr("disabled", "disabled");
}
else
{
$('input[name="DebitAmount"]').removeAttr("disabled");
}
});
});

using jquery to change contents of form upon typing

I am trying to get the default value to not go away on click, but rather when the user starts typing (so they know what the field is for)....the problem is the following:
when I use onchange instead of onfocus it keeps the default value in there when they start typing. If its confusing what I am doing go to facebook and look how their search box works...thats what I am going for.
<script>
function uFocus() {
$('#fakeusername').hide();
$('#username').show();
$('#username').focus();
}
function uBlur() {
if ($('#username').attr('value') == '') {
$('#username').hide();
$('#fakeusername').show();
}
}
</script>
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:gray;' type='text' name='fakeusername' id='fakeusername' value=' Username' onfocus='uFocus()' />
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:#000000;display: none' type='text' name='username' id='username' value='' onblur='uBlur()' />
Two options:
In HTML5, the placeholder attribute will simulate what you want with no Javascript needed.
<input type='text' name='fakeusername' id='fakeusername' value='Username' placeholder='Type your username' />
The second, and I believe the approach used by Facebook, is to swap a background image containing the sample text with a blank one. So you might create two background images (the first containing the words "Type your username" in the font used by the input, the second a blank) and set them to flip whenever the input is focused.
Is this what you are looking for:
$("#fakeusername").on({
focus: function() {
$(this).css('color', '#000');
},
blur: function() {
$(this).css('color', 'grey');
},
keydown: function() {
if ($(this).val()==' Username') {
$(this).val('');
}
}
});
FIDDLE
Here's a method that places label over top of input and requires proper for/ID match to allow browser to do default focus of input when clicking on label. Positions label over top of input, if no value of input on blur will show label again. Using label makes it accessible
http://jsfiddle.net/UCxaZ/2

Javascript/jQuery issue

I'm trying to make radio buttons that when you have them active, it displays a dropdown. I can already make it display, but when I click on another radio button, it shows one, but doesn't hide the other...
Code:
<input type='radio' name='op' onchange='$("#ban_length").fadeToggle();'/>
<input type='radio' name='op' onchange='$("#rank_list").fadeToggle();'/>
JavaScript section:
$(document).ready(function() {
$('#op1').change(function(){
$("#ban_length").fadeIn();
$("#rank_list").fadeOut();
});
$('#op2').change(function(){
$("#ban_length").fadeOut();
$("#rank_list").fadeIn();
});
});
HTML:
<input type='radio' name='op' id='op1'/>
<input type='radio' name='op' id='op2'/>
<div id="ban_length">demo</div>
<div id="rank_list">demo</div>
Demo:
http://jsfiddle.net/b2UPt/1/
<input type='radio' name='op' onchange='$("#ban_length").fadeIn();$("#rank_list").fadeOut();'/>
<input type='radio' name='op' onchange='$("#rank_list").fadeIn();$("#ban_length").fadeOut();'/>
Though I would suggest removing the javascript from the elements themselves, giving them ids and adding the javascript to a separate script with $(theID).change(function(){....
Alternatively, you can use hide instead of fadeOut if you would like them to hide immediately.
And one last suggestion. If there are many of these and not just 2, I would add a shared class to each of the elements you are fading in. Then instead of hide on each element, just call $(".className").hide() to hide any that might be visible.
The change event only fires on the element that was clicked (i.e. the radio button that is now enabled). It isn't fired when a radio button is automatically disabled.
So you need to check all the radio buttons every time one of them triggers the change event. You need to be able to tell them apart, though, so start by giving them ids:
<input type="radio" name="op" id="radio_ban_length" />
<input type="radio" name="op" id="radio_rank_list" />
After that, you can use them to toggle the correct dropdowns:
$('input:radio').change(function() {
var id = $(this).attr("id");
if (id === "radio_ban_length") {
$("ban_length").fadeIn();
$("rank_list").fadeOut();
} else {
$("rank_list").fadeIn();
$("ban_length").fadeOut();
}
});
Alternatively, if you like a challenge or if you might have more than two radio's, you could use filter() and :checked to do something like this:
function getDropdownId(radioId) {
return '#' + radioId.replace(/^radio_/, '');
}
var radios = $('input:radio');
radios.change(function() {
// Checked radio's:
radios.filter(':checked').each(function(){
var id = getDropdownId($(this).attr('id'));
$(id).fadeIn();
});
// Unchecked radio's:
radios.filter(':not(:checked)').each(function(){
var id = getDropdownId($(this).attr('id'));
$(id).fadeOut();
});
});
Note that this method does rely on the id's of the radio buttons matching those of the dropdowns (e.g. radio_ban_length for ban_length).
Update: here is a live example: http://jsfiddle.net/55ANB/1/
add id="ban" and id="rank" to your radios
in your jquery section, add the click handler to the radio buttons
$(':radio').click(function() {
if ($(this).attr("id") == "ban") $("ban_length").fadeToggle();
if ($(this).attr("id") == "rank") $("rank_length").fadeToggle();
});

Categories

Resources