How to access value of input field in a complex dynamic table using jQuery

Viewed 21

How can I get "Segment" column input value?

Edit

I have changed the logic, I'm adding a button to each line in the table and adding an on "click" event , in the on click function i want to use a value of one of the fields but the segmentName val() function is not returning it

        function generateSetDefaultSegmentValueButton(){

        $('#cust_segment_rules_sublist_default_splits tr').each(function(){
            let lineIndex = this.id.replace('cust_segment_rules_sublist_default_row_','');
            // console.log("lineIndex0: " + lineIndex)
            $(this).find("td:contains('Button')").each(function(){
                $(this).html('<button type="button" id="col_default_value_button_line_' + lineIndex + '" style = "cursor: pointer;" >Select defaul segment value</button>');
                $(`#col_default_value_button_line_${lineIndex}`).on("click", {arg1: `${lineIndex}`} ,onDefaultSegmentClick);
            })
        })
    }

    function onDefaultSegmentClick(e){
        let lineIndex = e.data.arg1;
        let segmentName =  $(`#cust_segment_rules_sublist_default_row_${lineIndex} td:nth-child(8) div`).val()
        console.log("segmentName: " + segmentName)
    }

enter image description here

Result in console: "segmentName: "

1 Answers

You need to bind the change event to the input, not table row. So something like this:

 $('#cust_segment_rules_sublist_default_splits .dropdownInput.textbox').on('change', function () {
     let segmentName = $(this).val();
     console.log("segmentName: " + segmentName);
 });

Also there is no need for .each() while binding event generally to all the inputs.

As for the previous value, you can always store it in data-* attribute, e.g. data-oldval="somevalue", or have array/object of input values declared in your JS external file, and manage values in it using some identifier.

var input_values = {};

// load the original values on page load
$('#cust_segment_rules_sublist_default_splits .dropdownInput.textbox').each(function () {
    let input_id = $(this).attr('id');
    input_values[input_id]['old'] = $(this).val();
});

// input onChange
$('#cust_segment_rules_sublist_default_splits .dropdownInput.textbox').on('change', function () {
    let segmentName = $(this).val();
    console.log("segmentName: " + segmentName);

    let input_id = $(this).attr('id');
    let new_value = $(this).val();
    input_values[input_id]['new'] = new_value;
    
});
Related