Finding Changed Form Element With jQuery - javascript

i have a form(id="search_options") and i tracking changes in form by:
$("#search_options").change(function() {
// Bla Bla Bla
});
In this form i have many inputs and one of is select(id="project_category") and i want to catch if user changed project_category select or another input. How can i done this ? Thanks

What you are looking to do could be accomplished 2 ways I can think of off the top of my head.
First, Capture the change event for all input items in your form individually
$("#search_options input,#search_options select").change(function() {
// "this" is the input that has changed so you would check if it had id = "project_category" here
});
Alternatively you could track the current value of the "project_category" on every change
var current_Project_Category = "";
$("#search_options").change(function() {
if(current_Project_Category != $(this).find("#project_category").val())
{
//project category has changed so mark this as the current one
//also run any change code here
current_Project_Category = $(this).find("#project_category").val()
}
});

There is a plugin made for exactly this purpose:
jQuery Form Observe
This plugin observes values of form
elements. When end-user changes any
values of input elements, observer
shows which values were changed. And
observer also alerts to users when
they try to move out from the page
before submitting changes.

Try this instead:
$("#search_options").find('input,select').change(function() {
var changedId = $(this).attr('id');
var newVal = $(this).val();
});

Related

Dividing a column of <td> by a an input value

I'm stumped by this current project I'm trying to solve. I'm able to print out the exact results that I want in the console, however I can't figure out how to insert those back into their respective tds within the table.
var calc = $('.calc'),
odds = $('.weight');
$(document).on('keyup keydown', '.calc', function(e){
var curVal = calc.val();
$(document).find('.weight').each(function(){
var oddsVal = ($(this).text() / curVal);
console.log(oddsVal);
});
});
I'm trying to divide the text in each cell of the weight column by the input.calc while a user is entering data into the input so that it updates live.
You can see a Fiddle of it here, with the results printing to the console. How can I make it so each cell in the weight column updates?
Thanks in advance for your help!
The problem is that the cells are getting updated before a value is in the input, which results in 'Infinity' being created 4 times. You can even see it in your console log.
Instead, make sure there is a value in calc before executing the function.
Furthermore, if you repeatedly change the calc field, it will do a new calculation based on the newly replaced values, which does not seem like the correct behavior. So, instead, capture the original values on page load and use those in the calculation:
var originalWeights = getOriginalWeights();
function getOriginalWeights() {
var weights = [];
$('.weight').each(function(index) {
weights[index] = $(this).text();
});
return weights;
}
$(document).on('keyup keydown', '.calc', function(e){
if (!calc.val()) return;
var curVal = calc.val();
$(document).find('.weight').each(function(index){
var oddsVal = (originalWeights[index] / curVal);
$(this).text(oddsVal);
});
});
Fiddle
To solve this you have to edit both HTML and JS code. You should store the original value in a data attribute, and then print it inside the loop using the value parameter of the jquery each function. Here is your fiddle edited, hope it helps!
http://jsfiddle.net/ch1qui/LoLrotkn/3/
You should remove the keydown event from the event delegation as the value on the input box would not be available during keydown. Also having keyup and keydown would trigger the events simultaneously, triggering each block twice. Also you don't need to declare the var calc = $('.calc'), globally since the element would be available during the event target on the document.
$(document).on('keyup', '.calc', function(e){
var curVal = $(this).val();
$('table td.weight').each(function(){
var oddsVal = $(this).text() / curVal;
alert(oddsVal);
});
});
Example : http://jsfiddle.net/LoLrotkn/4/

jQuery: Put dynamically generated input values to span/div

I'm trying to create form for printing with dynamically generated inputs.
Contents of the fields is shown later in PreviewDiv.
It works fine as long as I specify where they should be, for example:
$('#Prw_CapacityA_1').text($('#CapacityA_1').val());
$('#Prw_CapacityB_1').text($('#CapacityB_1').val());
$('#Prw_CapacityC_1').text($('#CapacityC_1').val());
But if the user creates 100 fields this would be a lot of code to write.
There must be other methods to fix this dynamically, for example:
$('#Prw_CapacityA_'+ counter).text($('#CapacityA_'+ counter).val());
Here's the js fiddle
You could try using attribute starts with selector to select the elements starting with the specific id's and then loop through them using the each() function.
There is no need to have html within your preview table. You can generate it when the user clicks on preview. Modified fiddle
$('#PreviewButton').click(function(){
var capB = $('td input[id^=CapacityB_]');
var capC = $('td input[id^=CapacityC_]');
var table = $("#AddFieldsToPreviewDiv");
table.empty(); //build table everytime user previews so that previously appended values are removed
table.append('<tr><td>ID</td><td>Text 1</td><td>Text 2</td><td>Text 3</td></tr>');
$('td input[id^=CapacityA_]').each(function(i){
table.append('<tr><td>#'+(i + 1)
+'</td><td>'+$(this).val()
+'</td><td>'+$(capB[i]).val()
+'</td><td>'+$(capC[i]).val()
+'</td></tr>');
});
// Show PreviewDiv and hide FormDiv if PreviewButton clicked
$('#PreviewDiv').show();
$('#FormDiv').hide();
});
You could try giving them a unique class (Normally I'd suggest ID but you're using one) say a class of "getinfo"
You could then try the .each() function
https://api.jquery.com/each/
$( ".getinfo" ).each(function( index ) {
var text = $(this).val();
alert(text);
});
This will make an alert box for every element it finds with the class 'getinfo' and then retrieve the value and display it, I hope this gives you a better idea.
If the amount of inputs can change from one page load to the next then you need to use a loop, rather than pulling all the values by 'hand', More code will help better understand what you're trying to achieve and from what.

Passing a value from one input to another in jQuery

jsFiddle for reference:
http://jsfiddle.net/UxQV7/
What I'm trying to do is if the user clicks on "Add" on the 2nd row, the new form element is displayed underneath.
The user then types a number in that new form element, clicks the "Add" button and then that number will be populated in the Serial# input of the 2nd row and the new form element then is hidden.
The part I'm having trouble is once the user types in the number to that new form element, how do I know to send it back to the 2nd row.
Thanks very much.
You could do:
var index;
$(".addSerial").click(function(){
index = $(this).closest('tr').index();
console.log(index);
$("#serialAdd").toggle();
});
$("#submitSerial").click(function(){
$('table tr:eq('+index+') input:first').val($("#serialToAdd").val());
$("#serialAdd").toggle();
});
fiddle here http://jsfiddle.net/qWGKq/
You're going to have to store a reference value somewhere (in a global variable, for example) to indicate which <a> was clicked to display the Serial Number entry <div> or create it dynamically on the fly and destroy it afterwards.
Save the current row in a variable, and then filter the textbox out of it to set the value to: http://jsfiddle.net/UxQV7/1/.
var currentRow; // will be <tr> of row where user has clicked on Add
$(".addSerial").click(function(){
currentRow = $(this).parents('tr'); // set current row
$("#serialAdd").toggle();
});
$("#submitSerial").click(function(){
$("#serialAdd").toggle();
currentRow.find(':text:eq(2)').val($('#serialToAdd').val());
// find correct textbox in row and copy value
});
You can use jQuery's prev() to get the target input and save it:
var activeField;
$(".addSerial").click(function(){
$("#serialAdd").toggle();
activeField = $(this).prev();
return false;
});
$("#submitSerial").click(function(){
$("#serialAdd").toggle();
activeField.val( $("#serialToAdd").val() );
$("#serialToAdd").val("")
});
Demo: http://jsfiddle.net/7Xykw/
when these controls are rendered you need to have a serial number to each control in id that way you can easily identify controls and add values.
Check this working sample . http://jsfiddle.net/UxQV7/18/

Populating div in real time with form input data

I have a form (just one field) which I am populating with some data. I would like to get me Div container populated with the data I put there in a real time. So no refresh, after I type in some text in the form field, I get it in the div as well. Does anybody know how to do it? JQuery, AJAX?Any advice appreciated.
var div = $('div')[0];
$('input').bind('keyup change', function() {
div.innerHTML = this.value;
});
Try it out: http://jsfiddle.net/H6P2z/
Of course you should make the selectors specific to your actual elements.
With jQuery you can do this very easily:
$('#textFieldId').bind('change', function (event, previousText) {
$('#divId').html($(this).val());
});
You could bind an onkeyup event to the input field. When the event fires, you can grab the contents of the field and do what you want with it.
This might look like this:
$(selector).keyup(function(e) {
// find the value of the field
var text = $(this).val();
// do something with it
$(yourDivSelector).html(text);
});

JavaScript\JQuery - identifying if radio button value changed by click

I have a page that displays a list of records. The user can select the record status using radio buttons, e.g.:
<div id="record_653">
<label><input type="radio" name="status_653" value="new" checked/>new</label>
<label><input type="radio" name="status_653" value="skipped" />skipped</label>
<label><input type="radio" name="status_653" value="downloaded" />downloaded</label>
</div>
I am using JQuery to send the changes made by the user back to the server, where I use them to update the database. This is a simplified version of what I do:
$("#record_653").click(
function(event) {
var url = ...,
params = ...;
post(url,params);
});
The problem is that this code will create requests even if the user clicks the same button that was previously checked. What I actually want is the "on change" event, except its behavior in Internet Explorer is not very useful (e.g. here).
So I figure I somehow have to identify if the click event changed the value.
Is the old value stored somewhere (in the DOM? in the event?) so I could compare against it?
If not, how should I store the old value?
The old value is not stored someplace where you can query it, no. You will need to store the value yourself. You could use a javascript variable, a hidden input element, or jQuery's data() function.
EDIT
The jQuery data function provides access to a key-value-pair data structure as a way to store arbitrary data for a given element. The api looks like:
// store original value for an element
$(selector).data('key', value);
// retrieve original value for an element
var value = $(selector).data('key');
A more developed thought:
$(document).ready(function() {
// store original values on document ready
$(selector).each(function() {
var value = $(this).val();
$(this).data('original-value', value);
})
// later on, you might attach a click handler to the the option
// and want to determine if the value has actually changed or not.
$(selector).click(function() {
var currentValue = $(this).val();
var originalValue = $(this).data('original-value');
if (currentValue != originalValue) {
// do stuff.
// you might want to update the original value so future changes
// can be detected:
$(this).data('original-value', currentValue);
}
});
});
$('#record_653 input:radio').each(function() {
$(this).data('isChecked', $(this).is(':checked'));
$(this).click(function() {
if ( $(this).is(':checked') !== $(this).data('isChecked') ) {
// do changed action
} else {
$(this).data('isChecked', !$(this).data('isChecked') );
}
})
});
This was complicated to do in my head but I think you want something like this.
As was suggested by meder and Ken Browning, I ended up using JQuery's data() to store the previous value and check against it on every click.
Storing an "is checked" boolean for each input radio is one solution. However you need to maintain this value. So in the click event handler, in addition to changing the "is checked" of the current input, you need to find the input that was previously checked and change its "is checked" data to false.
What I chose to do instead was to store, in the parent element, the currently checked object. So my code looks something like:
$(document).ready(
function() {
// find the checked input and store it as "currChecked" for the record
$("#record_653").data("currChecked",
$(this).find("input:radio:checked")[0]);
// add the click event
$("#record_653").click( function(event) {
if ($(event.target).is("input:radio") &&
event.target !== $(this).data("currChecked"))
{
$(this).data("currChecked", event.target);
handleChangeEvent(event);
}
});
});
}
);
Thanks
I had the same problem, but with FF I managed to deal with it using the onchange event rather than the onclick.
This is exactly what I was looking for to deal with IE7. Works like a charm!
Thanks for the detailed solution!

Categories

Resources