catch input on change event with javascript - javascript

First of all, I'm using this function:
jQuery(document).on('propertychange change click keyup input paste', 'input[name="wager_id_111"]', function(){
var thisValue = jQuery(this).val();
var amountReal = jQuery('.amount_visible');
if ( thisValue != '' ){
var amount_in_btc = thisValue / 1000;
amount_in_btc = amount_in_btc.toFixed(5);
amount_in_btc = parseFloat(amount_in_btc);
amountReal.show(1, function(){
amountReal.find('span').html('= ' + amount_in_btc);
});
} else {
amountReal.hide();
}
});
and it works when user types amount it the input. The problem is, when input value is being changed via code, so I can't detect it was changed. Becouse there is buttons how much amount add to input (like 1, 10, 50, 100) and when users selects one of those, input value is being changed jQuery('input[name="wager_id_111"]').val(newVal); but as I said the function I showed below can't catch this. What the option would be to make it work?
Fiddle:
fiddle link

you can add this line of code: $('input[name="wager_id_111"]').trigger('change'); to your .click() function
demo: http://jsfiddle.net/et3gsf9w/1/

The solution is to place the code that operates the input value into a function, and call it two times, one when the event is raised and the other one via code.

Related

Angular JS calculation based on input boxes

I read this thread:
Simple Percentage Calculation of an Input Field with JQuery
But can't seem to get it to work for my situation. I have two input boxes, Wholesale and Sell Price, and I want to calculate the markup (difference) on the fly as the user is changing their Sell Price. I've built a simplified version of what I'm trying to do here:
http://jsfiddle.net/schuss/rp0brqj1/2/
And below is the JS - can anyone see what I'm doing wrong? Thanks!!
$(function() {
// cache elements that are used at least twice
var $sellprice = $("#SellPrice"),
$markup = $("#markup"),
$wholesale = $("#wholesale");
// attach handler to input keydown event
$sellprice.keyup(function(e){
if (e.which == 13) {
return;
}
var sellprice = parseFloat($sellprice.val()),
markup = sellprice-wholesale;
if (isNaN(sellprice)) {
$markup.hide();
return;
}
else {
$markup.fadeIn().text(markup.toFixed(2));
}
});
});
You want to set the value of input field, so in this case you need to use $.fn.val method:
$markup.fadeIn().val(markup.toFixed(2));
Demo: http://jsfiddle.net/rp0brqj1/6/
Try this (I haven't included the else - and don't forget to include JQuery in your fiddles!):
$(function() {
var $sellprice = $("#SellPrice"),
$markup = $("#markup"),
$wholesale = $("#Wholesale");
$sellprice.on('keyup', function(){
$markup.val(parseFloat($sellprice.val()-$wholesale.val()))
});
});
Fiddle

function called repeatedly in javascript

I define a tag picker which will generate checkbox inputs based on "group". If I select the tags I want and press done button, it should return a string to set the value of a text input.
Here are the related codes. The problem is it only works well at the first time. For example, for the first time, if I checked 'jquery','javascript' in the tags,
console.log('output is:' + tags);
print out 'output is: jquery,javascript'. Works!
Then I use it again and select 'jquery','javascript','bootstrap',
it will return
output is: jquery,javascript,bootstrap
output is:
One more time for 'jquery','javascript','bootstrap', it returns
output is: jquery,javascript,bootstrap
output is:
output is:
Seems the done button pressed, the function is called repeatedly. Being stuck with it for several hours but can't figure out. Really appreciate for your answer! Thanks
(function(){
$.fn.tagPicker = function(source,options){
var settings = $.extend({
perRow : 3
},options);
$.fn.attachRow = function(row,col){
//codes here
...
}
$.fn.attachPicker = function(){
//codes here
// generate html for checkbox inputs
...
};
var $input = this;
if($('.tag-picker').length == 0){
$input.attachPicker();
$('body').on('click','.tag-picker .close-picker',function(){
$('.tag-picker').remove();
})
$('.tag-picker .close-picker').off();
$('body').on('click','.tag-picker #btn-done', function(){
var tags = getTags();
$('.tag-picker').remove();
console.log('output is:' + tags);
$input.val(tags);
});
}
function getTags(){
var t = [];
$('.tag-picker input').each(function(){
if($(this).is(':checked')) t.push($(this).attr('id'));
})
return t.join(',');
}
}
})(jQuery);
$('body').on('click','input.participant',function(){
$(this).val('');
$(this).tagPicker(group);
})
You are initialising the plugin every time the elements are clicked. You should initialise it once, on DOM ready.
OR if you want to do this anyway; you could use .one() for the event to run only once and remove itself. Use .off() to detach an event, attached with .on().

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

Need to run a function based on conditional

I'm trying to assign a function to a couple of checkboxes, but I only want them added based on a condition, in this case the step number of the form. This is a roundabout way of making the checkboxes readOnly AFTER they have been selected (or not). So, at step 1 I want the user to choose cb1 or cb2, but at step 2 I want to assign the function that will not let the checkboxes values be changed.
What am I doing wrong?
function functionOne() {
this.checked = !this.checked
};
if (document.getElementById("stepNumber").value == 2) {
document.getElementById("cb1").setAttribute("onkeydown", "functionOne(this)");
document.getElementById("cb2").setAttribute("onkeydown", "functionOne(this)");
}
You are passing the element in an argument, so use that:
function functionOne(elem) {
elem.checked = !elem.checked
};
You could also use properties:
document.getElementById("cb1").onkeydown = functionOne;
document.getElementById("cb2").onkeydown = functionOne;
function functionOne() {
this.checked = !this.checked
};
This is a solution that requires jquery but you can use the .click function to disable checkboxes once one is clicked.
Here is a working example:
http://jsfiddle.net/uPsm7/
Why not on the selection disable the checkbox?
Function onCheck(elm)
{
document.getElementById("cbValue").value = elm.value;
elm.disabled = true;
}
<input id="cbValue" type="hidden" />
Use the hidden input field to allow form to send data back to server.

By JQuery, how to specify on function as onClick handler for many radio buttons?

I have a function called handleOnClickRadio(i, j); and lots of radio buttons named as id="something-radio[i][j]". All these radio buttons are in a table called "bigtable".
How could I attach the function handleOnClickRadio() to all these radio buttons? And call it correct with handleOnClickRadio(i,j).
Thanks.
I would not attach the click handler to the buttons at all. You say you have lots of them. Attaching the same event handler to each of them is a waste of memory and could even be a performance problem.
Use event delegation instead:
$('#tableID').delegate('input[type=radio]', 'click', function() {
// code here
});
Then you could extract the i and j via regular expression (you could also consider to change the pattern so that you can use something simpler like split()):
var exp = new RegExp("\\[(.+?)\\]\\[(.+?)\\]", 'g');
var match = exp.exec(this.id);
var i = match[1];
var j = match[2];
You could put this together like so:
$('#tableID').delegate('input[type=radio]', 'click', function() {
var match = this.id.match(/\[(.+?)\]\[(.+?)\]/)
var i = match[1]; // use parseInt(match[1]) if you need an integer
var j = match[2];
handleOnClickRadio(i,j);
});
edit: Made code a bit simpler.
If i and j correspond to column and row indicies, see #Caspar Kleijne's answer for an alternative way to retrieve them.
For accessibility, you should consider binding the handler to the change event. Then changes via the keyboard will be recognized too.
wire up the event like this
$("#bigtable input[type='radio']").bind("click", OnClickRadio);
and use the handler like
var OnClickRadio = function () {
var col = $(this).parent("td").index();
var row = $(this).parent("td").parent("tr").index();
handleOnClickRadio(col, row)
});
You can attach an onClick method to a collection of radio buttons within a table with a simple bit of jQuery. When you say 'table called "bigtable"', I'm assuming that you mean that it has id="bigtable" in the following code.
$(document).ready(function() {
$("#bigtable input:radio").click(function() {
// Your on click code here
});
});
However, I would usually give each of the radio buttons a specific class using class="magicRadioButton" and then your jQuery code becomes a little clearer and doesn't rely on all of those radio buttons being within a table;
$(document).ready(function() {
$(".magicRadioButton").click(function() {
// Your on click code here
});
});
Now, if you need to then plug this information into your current handleOnClickRadio method, you can do so with the following.
$(document).ready(function() {
$("#bigtable input:radio").click(function() {
var button_id = $(this).attr("id");
var re = new RegExp("\\[(.*?)\\]\\[(.*)\\]");
var matches = re.exec(button_id);
var i = matches[1];
var j = matches[2];
handleOnClickRadio(i,j);
});
});
Give them class names in conjunction with $(this) in your click trigger
I suggest using delegate if you have lot of radios: that way, only one Event listener will be attached
see http://api.jquery.com/delegate/
$("#globalContainer").delegate("input", "click", function(){
//Perform a string test / regex to test if the id matches something-radio[i][j]
//With a regex with capturing groups you can retrieve [i] and [j] values at the same time
if ( test($(this).attr("id")) ) {
}
});
Ideally, you'd have a onclick assigned to the big table rather than each and every radio button. Events in JavaScript bubble up so the table (which is the eventual parent of all these radio buttons) will receiving the event.
So in jQuery you would have code like this
$('#bigtable').click(handleOnClickRadio);
The signature of your handleOnClickRadio function would be
function handleOnClickRadio(evt) {
var radio = evt.target;
var id = $(radio).attr('id');
}
evt.target will identify the actual radio button that was clicked/checked and you can access other attributes of the radio as well. such as
$(radio).attr('id)
Will give you the id of the radio button.
<input type="radio" class="many-radio-buttons" ....
jQuery:
$('.many-radio-buttons').click(function() {
//your_code;
});

Categories

Resources