I'm trying to add a quick conditional logic to my Laravel project. If a "create_copay" text input is anything other than 0.00, my "create_ams_fee" field should display 0.00. Else, it will be 7.00. However, my code displays no change whatsoever in the create_ams_fee field.
Form Fields (Laravel Collective)
<div class="form-group">
{{Form::label('copay', 'Copay')}}
{{Form::text('copay', '', ['class' => $errors->has('copay') ? 'form-control border border-danger' : 'form-control', 'id' => 'create_copay'])}}
</div><!-- /form-group -->
<div class="form-group">
{{Form::label('ams_fee', 'AMS Fee')}}
{{Form::text('ams_fee', '', ['class' => 'form-control', 'id' => 'create_ams_fee'])}}
</div><!-- /form-group -->
Script
// Calculate AMS Fee field
$('#create_copay').change(function() {
if ($('#create_copay').val() == '0.00') {
$('#create_ams_fee').val('7.00');
} else {
$('#create_ams_fee').val('0.00');
};
});
Edit
This seems to be turning into a dynamic loading issue. The codeblock below is what I'm resulting to try and test. The parent container of these inputs has an id of create_financials. I currently am having no success finding a way to trigger an event by changing the create_copay field.
$( document ).ready( function() {
$('#create_financials').on('input', '#create_copay', function() {
console.log('SUCCESS');
});
});
You are using the 'change' event - this is only fired when focus is taken out of the element (it is blurred) and it has changed, or the form is submitted, or certain other times.
You could use the keydown or keyup events, but a better one is the 'input' event.
If this is a number input, you should use the input type 'number' rather than text - however, if you don't want to or can't do that, casting the text from the input to a number might also be beneficial:
$('#create_copay').on('input', function() {
if ($('#create_copay').val()/1 == 0) {
$('#create_ams_fee').val('7.00');
} else {
$('#create_ams_fee').val('0.00');
};
});
Please see this codepen for a working example:
https://codepen.io/manticorp/pen/wYpXWY
Using the html inspector (right click, inspect element) are you sure your inputs have the ids specified? (create_copay and create_ams_fee).
Also, I've just seen your inputs may already be populated, in which case something like this would be better:
$(function() { // jQuery domready event
$('#create_copay').on('input', updateFields);
function updateFields() {
if ($('#create_copay').val()/1 == 0) {
$('#create_ams_fee').val('7.00');
} else {
$('#create_ams_fee').val('0.00');
};
}
updateFields();
});
If you are creating these fields dynamically, or inserting them into the document after load somehow, then you will need to attach the event to the document/a container element:
$(function() { // jQuery domready event
$('#theContainer').on('input', '#create_copay', updateFields);
function updateFields() {
if ($('#create_copay').val()/1 == 0) {
$('#create_ams_fee').val('7.00');
} else {
$('#create_ams_fee').val('0.00');
};
}
updateFields();
});
Use the keydown event for input field. Change takes effect after the input element loses focus.
Related
I have input element which will take input and filter the contents and the filter event will be trigger once the user gets focused out from the input element.
When the user having the focus in the input element and he clicks in one of the button, the click event is invoked first and then the focus out event, as it creates conflicts while generating the filtered content.
I tried changing the order of code and other options such as changing the way of invocation of the click event - none of the ways worked out for me
$('body').on('focusout', '.classname', functionname);
function functionname(e) {
if (typeof e == 'object') {
}
}
$('body').on('click', '.buttonclass', function (e) {});
Could someone help me to build The FocusOut event to trigger first and then the click event.
Based on the current conditions, you have to - inside the click handler - retrieve the validation result, and based on that result, decide if button submission should or should not occur.
JS Code:
$("#input").focusout(function(){
var that = this;
valid = this.value.length ? true : false;
!valid && window.setTimeout(function() {
$(that).focus();
}, 0);
});
$("#button").click(function(e) {
if ( !valid ) { return false; }
e.preventDefault();
alert('execute your filter)');
});
I have a currency exchange in my backend, I post data from my textbox to the currency exchange using ajax and view the exchanged value in a label, which is otherwise hidden.
The problem is, if I enter a value in the textbox, and then erase the value from the textbox, the latest value is still there ( I want to hide the label again when the textbox is empty )
This is the code I've tried so far:
$('#transferAmount').on('change',function () {
var amount = $('#transferAmount').val();
if (amount.length < 1 || amount === ""){
$('#amountExchangedHidden').hide();
}
});
I've tried with "on-input" aswell, but it didn't work. Does anyone have a good solution to this?
Use input event instead of change event as change event handler will only be invoked once focus in the input field is lost.
The DOM input event is fired synchronously when the value of an <input> or <textarea> element is changed.
$('#transferAmount').on('input', function() {
var amount = $(this).val();
$('#amountExchangedHidden').toggle(!!amount.length);
}).trigger('input'); //`.trigger` to invoke the handler initially
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id='transferAmount'>
<input type="text" id='amountExchangedHidden'>
Use blur Event instead of Change
$(function) {
$('#transferAmount').on('blur',function () {
var amount = $('#transferAmount').val();
if (amount.length < 1 || amount === ""){
$('#amountExchangedHidden').hide();}
});
});
I'm trying to figure out why my focus remains on an element. This is html from the autocomplete angular plug-in that I'm using:
<autocomplete id="search" ng-model="query" attr-placeholder="" click-activation="true" data="items" on-type="updateItems" on-select="searchItems"></autocomplete>
but every time I press enter no matter if I have my focus on the input field or not, or even on an other field, the on-select function is called every time.
this thing is in the plugin itself, maybe it needs some changes?
document.addEventListener("blur", function (e) {
// disable suggestions on blur
// we do a timeout to prevent hiding it before a click event is registered
setTimeout(function () {
scope.select();
scope.setIndex(-1);
scope.$apply();
}, 150);
}, true);
You could monitor what was the last selected input field with this code :
var lastFocusedElement = '';
// This would catch any input field - so you could add your forms selector too.
// for example : $("#myForm:input")
$(":input").focus(function () {
lastFocusedElement = $(this);
});
Then use the complete callback function from animate :
$("#div_NotificationOuter").animate({ bottom: '+=30px' }, 4000,function(){
if (lastFocusedElement != ''){
lastFocusedElement.trigger('focus');
}
});
I am using JQuery remote validation on drop-down field to check whether the selected field already exists or not. The overall code is working fine and validates properly. But the issue is remote validation sending an ajax call after onChange event, means it is showing unique key validation error after clicking anywhere on page.
I want to validate it once user clicks on dropdown option. I tried onclick:true but it's not working. Please check my code:
$("#myform").validate({
// onclick:true,
// onkeyup:true,
rules: {
"customer[customer_personal_details_id]": {
required: true,
remote: {
url: "/validation/check",
type: "post",
data: {
columnVal: function () {
return $("#customer_customer_personal_details_id").val();
}
}
}
}
},
messages: {
"customer[customer_personal_details_id]": {
required: "Please Select Account Holder",
remote: "One active account already exists. Duplicate accounts are not allowed."}
}
});
Thanks. Any help would be appreciated.
Try this - assuming you have <SELECT ID="DROPDOWN_ID">
$('#DROPDOWN_ID').on('click', function() {
$("#myform").validate();
});
The select's change event is a much better indicator of when to validate but there's no onchange option. The following should work:
$(function() {
$('select').on('change', function() {
$(this).trigger('focusout');
})
.on('focusout',function(e) {
e.preventDefault();
});
});
Triggering focusout should trigger a validate to be fired on the select element unless the onfocusout option is set to false. You may want to prevent the default behavior of focusout so that it does not trigger a remote validation twice.
In the demo below you'll see that as soon as you select a new value in select element, an attempt to make an ajax call is made -- see network tab of dev tools -- and on focusout no request attempt is made.
JSFIDDLE DEMO
onfocusout Type: Boolean or Function() Validate elements (except
checkboxes/radio buttons) on blur. If nothing is entered, all rules
are skipped, except when the field was already marked as invalid.
http://jqueryvalidation.org/category/plugin/
I do not use: "JQuery Remote Validation", but this code might help you:
JavaScript code:
window . onload = function ()
{
"use strict";
document . querySelector ( "form#myform > select" ) . selectedIndex = -1;
}
function test ()
{
"use strict";
if ( typeof customOption === "undefined" ) { alert ( "FATAL SYSTEM ERROR !" ); return; }
alert ( "Valid option selected ! Congratulations !\nYour selected value is: \"" + customOption + "\"" );
}
and the HTML5 code:
<select onchange="customOption = this . options [ this . selectedIndex ] . value;">
<!-- ( ... ) -->
</select>
This is only demonstration. You can call your function, so you can: "validate it once user clicks on dropdown option" by change HTML5 code ( select element onchange attribute ).
Working fiddle: JSFiddle
I have the below script:
$("#product1").autocomplete({
source: "get_sku_family",
messages: {
noResults: '',
results: function () {}
},
select: function (event, ui) {
var selectedObj = ui.item;
$.post('get_as_09',
{
data: selectedObj.value
},
function (result) {
if (result[0] > 0) {
$('#h09_1').attr('checked', 'checked');
} else {
$('#h09_1').removeAttr('checked');
}
}
});
}
});
This has an autocomplete field that when text is entered provides options from a database. this works. then on clicking an option from the autocomplete, it queries the database with a function(get_as_09) and checks the checkbox based on the result.
Again this works 100%.
What I do want to change though, is that when I enter a new value on the autocomplete, it must clear the checkboxes before applying the new database lookup logic to check the boxes.
I just don't know where to add the $('#h09_1').removeAttr('checked');
Thanks and Regards...
any help appreciated
UPDATE Ripu
if(data:selectedObj.value.length ==0 ){$('#h09_1').removeAttr('checked');};
$.post('get_as_09', {data:selectedObj.value},function(result) {
if(result[0] > 0) {
$('#h09_1').attr('checked','checked');
} else {
$('#h09_1').removeAttr('checked');
}
});
before this line
$.post('get_as_09', {data:selectedObj.value},function(result) {
check if the value of data:selectedObj.value is empty. If it is empty, then you don't need to make a post request, just simply uncheck the checkbox
try to make it on texbox on change event means when you enter the new value in auto complete make it there to clear any thing you want check
Why dont you clear your checkboxes on focus of the auto-complete field.
Here is the documentation about this event http://api.jqueryui.com/autocomplete/#event-focus
as you said just a $('#h09_1').removeAttr('checked'); should suffice.
focus: function( event, ui ) {
$('#h09_1').removeAttr('checked');
}
what if you put before
$.post('get_as_09', {data:selectedObj.value},function(result) {
so everytime before you put smth inside your $('#h09_1') you clean it?
What if you attach an event listener on the element based on the keypress event? Something like this:
$(selectedObj).one('keypress', function (e) {
var checkbox = $('#h09_1');
if (selectObj.val().length > 0) {
checkbox.attr('checked', false);
}
});
This way you know somebody is typing in the field before you clear it. You could bind the event listener after each database lookup. Just an idea.