Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply css styles to dynamic JavaScript array?

I'm trying to apply CSS styles to input elements that are added to the HTML DOM dynamically via a JSON object.

Essentially an Ajax call receives a JSON payload with an array of data. Some KnockoutJS code then foreach's over the DOM to dynamically add rows.

I'm trying to add styles to inputs where a value is less than a required value. The bottom line is, I know the elements are dynamic to the DOM, and I'm having trouble accessing them so I can apply the style. I've tried both jQuery and pure JavaScript, and I can't access the newly added fields.

How would I do this?

I have a very complex fiddle created that creates the inputs. But I can't figure out how to style those inputs whose values are less than the current year.

I'm trying to add the .k-invalid style to the NextPaymentDate input whose value is less than the current year.

var $incomeWrapper = $("#income-wrapper");
$incomeWrapper.find("input#iNextPaymentDate_" + i).removeClass("k-valid").addClass("k-invalid");

The above doesn't work.

http://jsfiddle.net/kahanu/rdb00n76/9/

like image 320
King Wilder Avatar asked Aug 10 '26 12:08

King Wilder


1 Answers

You could add a filter function to your selector like this:

$('input[id^="iNextPaymentDate_"]').filter(function(index) {
    return parseInt($(this).val().split('/')[2]) < new Date().getFullYear();
}).addClass('k-invalid');

Fiddle: http://jsfiddle.net/rdb00n76/10/

The above code selects all inputs whose ids start with iNextPaymentDate_, then applies a filter that evaluates the current element against the current full year. To do this I split the date string on / and take the 3rd item which should be the year. Then I cast the value to int and compare the the current year.

Your actual filter function should probably be a lot more solid than the one above. For example, you could include moment.js for comparisons.

like image 127
Mario Tacke Avatar answered Aug 12 '26 04:08

Mario Tacke