Biomehanika
Biomehanika

Reputation: 1540

jQuery 'change' method (for HTML attribute modify) working only once

I have this pair of functions affecting two inputs, and one select. These are exclusive so when inputs are filled, select must be modified to have option 3 selected, and when any option except 3 is selected, both inputs must be empty:

$('#ar_filter').on('change', '#ar_fromDate, #ar_toDate', function() {
        if ($('#ar_fromDate, #ar_toDate').val!=""){
           $('.lastDays').attr('readonly','readonly').find('option[value=3]').attr('selected', true);
        }
    });   

$('#ar_filter').on('change', '#lastDays', 'select', function() {
        if ($('.lastDays').val()!=3){
            $('#ar_fromDate, #ar_toDate').val("");
        }
    });

This works, but only the first time. When I write some value on the inputs, it resets correctly select to value 3, but when I change manually selected options, after it resets and leaves inputs empty, it does not reset anymore the select, even when writing on any of those inputs.

JSFIDDLE EXAMPLE (try making 2 select resets by filling the inputs: it will only make the first one)

Upvotes: 0

Views: 67

Answers (1)

War10ck
War10ck

Reputation: 12508

Based on your JSFiddle, I believe your second implementation of .on() is incorrect. The third optional argument can be passed as data to the handler function as denoted in the reference documentation.

Try changing:

$('#ar_filter').on('change', '#lastDays', 'select', function() {

to this:

$('#ar_filter').on('change', '#lastDays', function() {

Based on your comment above, I believe your selector is wrong. #lastDays is the id of the <select> element, which is where you want the change event bound. The extra select is not needed.

Updated Fiddle

Note:

The updated fiddle includes the .val() fix described by @tymeJV in his answer.

EDIT:

In addition to the .on() selector fix described above, you'll need to break out the two selectors in your .val() statement. This is because only the first input will be validated each time the change event occurs. This comes directly from the jQuery documentation for .val():

Get the current value of the first element in the set of matched elements.

The second value will not be fetched or validated.

Change this:

$('#ar_fromDate, #ar_toDate').val() != ""

to this:

$('#ar_fromDate').val() != "" || $('#ar_toDate').val() != ""

This should fix the problem. I've included an updated fiddle below. I've left the original fiddle in tact to show the progression of steps in solving this problem for the benefit of future visitors.

Complete Fiddle

Upvotes: 1

Related Questions