I have a huge form with several input fields. This is a Balance and a Profit & Loss sheet, so the input text fields has to be formatted as "money". I found some nice jQuery plugin to do the formatting: accounting JS, but right now I have to call it manually on all the fields and this is not the best method I think...
How can I call the accounting.formatMoney() function on ALL the input text fields on keydown?
So if there is a KeyDown or KeyUp event on the FORM or BODY, the script will find ALL the input fields and execute the script.
This is the formatting and the Javascript function I want to call on every INPUT text field:
var options = {
symbol : "",
thousand: " ",
precision : 0,
format: "%v%s"
};
var tmp = parseInt(document.getElementById('input_id').value, 10);
document.getElementById('input_id').value = accounting.formatMoney(tmp, options);
The form is sent back to BODY via AJAX, so I think the best method would be to call the function this way:
$(document).ready(function(){
$('body').on('keyup', 'input', function(e){
// collect all input fields and execute the function
});
});
Thank you very much for the help!
You might do
$(document).ready(function(){
$('body').on('keyup', 'input', function(){
$(this).val(accounting.formatMoney($(this).val(), options));
});
});
But this supposes your users would like the input to be modified while they're typing.
If you want to have the input modified when the users leave the field or type 'enter', do this :
$(document).ready(function(){
$('body').on('blur change', 'input', function(){
$(this).val(accounting.formatMoney($(this).val(), options));
});
});
Note that in a real world application I would have a class on my inputs to make the selector more selective ('input.money' instead of 'input').
EDIT :
If you want to apply this to the inputs in a table whose id is bstable, do
$(document).ready(function(){
$('#bstable').on('blur change', 'input', function(){
$(this).val(accounting.formatMoney($(this).val(), options));
});
});
If the bstable table is obtained via ajax and isn't immediately here, you may do
$(document).ready(function(){
$(document.body).on('blur change', '#bstable input', function(){
$(this).val(accounting.formatMoney($(this).val(), options));
});
});
$('body').on('keyup', 'input', function(){
$("body").find("input").each(function(index, element){
$(element).val(accounting.formatMoney($(element).val(), options));
});
});
Related
I wish to grab the current value of a search input and then clear the input box on focus, store the string and pass it into a function to re-populate the input box on blur.
$("input#search").bind('focus', function() {
var search_text = document.getElementById('search').value;
$("input#search").val("");
}).bind('blur', function(search_text) {
$("input#search").val(search_text);
});
Currently, this successfully grabs the value on focus and clears the input box, but on blur, it populates the input with [object Object].
Am I correctly passing the string on line 4?
Firstly, don't use bind(). It was deprecated a long time ago. Use on() instead.
With regard to your issue, you can't directly pass a parameter to the anonymous handler function in the manner you're attempting. As it stands your search_text variable will hold the blur event.
To fix this you could store the variable in a data attribute on the #search element itself. Try this:
$("input#search").on('focus', function() {
$(this).data('search-text', this.value).val('');
}).on('blur', function(search_text) {
$(this).val($(this).data('search-text'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" value="foo bar" />
Also, the behaviour you're creating here is similar to the placeholder attribute. It may be worth investigating that to see if it meets your needs.
Use .on() of jQuery to register event.
var search_text;
$("input#search").on('focus', function() {
search_text = document.getElementById('search').value;
$("input#search").val("");
});
$("input#search").on('blur', function() {
$("input#search").val(search_text);
});
Alternate could be ,
$("input#search").on('focus', function() {
var search_text = document.getElementById('search').value;
$("input#search").val("");
$(this).on('blur', function() {
$("input#search").val(search_text);
});
});
No. Here is how you would do, declaring the variable before the event listeners so that it's in the scope:
var search_text;
$("input#search").bind('focus', function() {
search_text = document.getElementById('search').value;
$("input#search").val("");
}).bind('blur', function() {
$("input#search").val(search_text);
});
The convention in JavaScript for naming variables in Camel Case, so you would rather use searchText (not that it really matters).
I'm struggling to get the behaviour I need - as follows:
A HTML form is pre-populated with a value via jQuery. When the user focuses on the input field I want the form to clear. On blur from the form, the form should repopulate the form with the existing value.
I have a solution that clears and repopulates the form but it fails as soon as anything is typed in.
This is what I have so far:
var x = "Default";
$(function () {
$("input").attr({
"value": x
});
$("input").focus(function () {
$("input").attr({
"value": ""
});
});
$("input").blur(function () {
$("input").attr({
"value": x
});
});
});
https://jsfiddle.net/thepeted/p74kfdt8/6/
If I look in developer tools, I can see the input value is changing dynamically in the DOM, but in the case that the user has typed something in to the form, the display no longer updates.
I'd love to understand why this is happening (ie, why it works in one case and not the other). Also, if there is a better way of approaching the problem.
As pointed out by Stijn, best practice would be to use the placeholder attibute.
However if you do want to use a function for it. I would check on the focus if the value is the default value or not. If so, empty the input, if not, don't do anything.
On blur, you also only want to place the default value back if the value is empty... so check for that aswell.
var x = "Default";
$(function() {
$('input[type=text]').val(x);
$('input[type=text]').on('focus', function() {
var elem = $(this);
if (elem.val() == x)
elem.val('');
}).on("blur", function() {
var elem = $(this);
if (elem.val() == '')
elem.val(x);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
Your edited jsfiddle.
updated code:
$("input").blur(function () {
$("input").val(x);
});
Personnaly, I'd use the placeholder attribute as everyone pointed out. If you too are facing the need to support older browsers and some others that do not support the placeholder attribute, use this snippet I've made:
$('input[placeholder]').each(function(){
var $this = $(this);
$this.val($this.attr('placeholder')).css('color','888888');
$this.focus(function(){
if($(this).val() == $(this).attr('placeholder'))
$(this).val('').css('color','');
});
$this.blur(function(){
if($(this).val() == '')
$(this).val($(this).attr('placeholder')).css('color','888888');
});
});
This script will find all inputs with a placeholder attribute, give it's value to the input, and add the correct events. I've left the css calls just to show you where to put the codes to mimic the greyed text like modern browsers do.
Try this code
var x = "Default";
$(function () {
$("input").val(x);
$("input").focus(function () {
$("input").val("");
});
$("input").blur(function () {
$("input").val(x);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>
I have a hidden input field like this in jade:
input(name='saintForm[quotes][]', type='hidden')
I want to use jquery to add to this array from a dynamic unordered list, but not sure how. Here's my failing attempt:
$('#form').on('submit', function(e){
e.preventDefault();
$('.quote').each(function (i){
var item = $(this).text().replace(' (x)','');
$("input[name='saintForm[quotes][]']").push(item);
});
this.submit();
});
If you're just adding a value to the default form functionality you could create an input with a value.
// grab your form and wrap it in jQuery
var myForm = $('#form');
// list teo the submit event
myForm.on('submit', function(e) {
e.preventDefault();
$('li.quote').each(function() {
$('<input />', {
type: 'text', // input type
name: 'saintForm[quotes][]', // the name of the form input
value: $(this).text() // the text from the current list-item
}).appendTo(myForm); // append each input to the form
});
myForm.submit(); // submit the form
});
You can of course send all sorts of arbitrary data to the server easily with AJAX but if you are just using the normal form submit I guess this is a good way to do it.
I just created an autocomplete textbox via jquery now i am stuck with two problems.
1) I need to get the value of the selected item from the Autocomplete list.
So far i did these..
My jquery
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
I am getting the autocomplete list from the database its working fine, but the problem is that
2) When i type 'r' all the names with values gets populated and if i select say Robin from the list and try to display it with alert, i only gets 'r', (i only typed r,and selected 'robin' from list) why is this so?
here is the code i wrote for this
for the autocomplete textbox
<input name="tags" type="text" id="tag" value="" onchange= "newfn()" />
and in newfn()
<script>
function newfn()
{
authname = document.getElementById("tag").value;
document.autoquote.qid.value=authname;
alert(authname);
}
</script>
and if i put an alert at first saying
alert("Hi");
then, i get first alert saying hi, and I get robin not r
So what is the correct way to get what value i selected from the autocomplete list?
Now my second Question is that the selected value from this autocomplete textbox, I need to pass it with another jquery to another php page so that I can get this value there and give it in a query as a criteria.
Because it is not the way to catch a select event http://api.jqueryui.com/autocomplete/#event-select :
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true,
select: function( event, ui ) {
//Then use "ui" object, for example ui.item.label or ui.item.value
}
});
});
$(".autosearch-smart").autocomplete('autocomplete.php', {
select: function( event, ui ) {
// here you can get id and values from the autocomplete list
// try to debug
console.log(ui.item.id);
console.log(ui.item.label);
console.log(ui.item.value);
}
});
you can use the autocomplete's select property like this
$("#tag").autocomplete('autocomplete.php', {
selectFirst: true,
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
alert(label);
alert(value)
// you can write additional javascript code here to make use of these values
}
});
Please check the jQuery UI documentation for more examples and info.
Here is a JSFiddle.(Please note that an additional source attribute has been added in the fiddle to simulate the loading of data set as real cross domain AJAX calls are not allowed)
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
select: function( event, ui ) {
//check the values in console
alert(ui.item.value+" - "+ui.item.value);
}
});
});
I have a website url field that has the value set for returning visitors who have previously filled out the form. If they change the value, then ('keyup blur paste', function() will copy it to a div. If they do not change the value, the ('keyup blur paste', function() does not copy the value to the div
I would like to figure out how to add to this script a function that would also copy the value to the div if they do not change it, because blur only works if they click in the input before they submit the form.
Here is my current script:
$(function () {
$('#Website').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("#viewer").text(str.replace(/^http\:\/\//, ''));
}, 0)
})
});
If I get you correctly, you want to populate the div on load as well as on keyup/blur/paste? Something like this?
$(function () {
$('#Website').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("#viewer").text(str.replace(/^http\:\/\//, ''));
}, 0)
});
// just add the line below
$("#viewer").text($('#Website').val().replace(/^http\:\/\//, ''));
});
I've updated the fiddle you created to demonstrate this working: http://jsfiddle.net/8kn4V/2/
on your page load...
$('#mydiv').html('whatever the value of the cookie');
is that what you need? as they mentioned in the comments above, your question is a little confusing.
use val() for input , select and textareas, and use text() for general elements like divs.
First solution
It seems now you are using a timeout of 0. That is not necessary at all, I think. So please check out this Fiddle:
$('#website').on("keyup blur paste", function () {
var s = $(this).text();
$("#viewer").text(s.replace(/^http\:\/\//, ''));
});
Edited solution
Now it seems you also want code that update #viewer from #website even when not triggered.
Here is a second fiddle — I hope you'll give credit if this solves the problem as it stands currently.
Relevant code:
function viewerupdate(me){
var s = me.text();
$("#viewer").text(s.replace(/^http\:\/\//, ''));
}
$('#website').on("keyup blur paste", function () { viewerupdate($(this)) });
var current_viewer = $('#viewer').text();
$('#submit').click(function(){ // assumes in the case that no change was made, that the submission is done through #submit
if($('#viewer').text() == current_viewer )
viewerupdate($('#website'));
});