• Status: Solved
  • Priority: High
  • Security: Private
  • Views: 75
  • Last Modified:

Jquery Datatables - Issue Finding controls

I have an html view...which has a template....
Note the use of display none.  
This template is used to inject a row into my datatable.

The problem with this is ....later on I have javascript that needs to find this control on the page...and it cannot because
Both template and the row added are rendered in html...

I need some way of appending an ID value to the controls when the row is added to the datatable...

Please help.


Here is template on my view:

<table id="new-row-template" style="display:none">
        <tbody>
            <tr>
                <td>
                    <label></label> 
                </td> 
                <td>
                   @Html.DropDownList("ddlRole", new SelectList(ViewBag.DDLRoles, "Value", "Text"), "")
                </td>
                <td>
                    @Html.DropDownList("selectdesignate", new List<SelectListItem>
                    {
                        new SelectListItem{ Text="", Value = ""  },
                        new SelectListItem{ Text="Primary", Value = "Primary" },
                        new SelectListItem{ Text="Secondary", Value = "Secondary" },
                     })                 
                </td>
                <td> 
                   @Html.TextBox("txtAllocation", new { @class = "form-control", @type = "number" })         
                </td>
                <td>
                    <button type="button" id="btnInsertContactEntity" class="btn btn-primary btn-xs actionButton" onclick="javascript:return InsertContactClient();">Save</button>                  
                </td>
                <td>
                    <button type="button" id="btnDeleteContactEntity" class="btn btn-danger btn-xs actionButton"  onclick="javascript:return RemoveContactClient();">Remove</button>
                </td>
            </tr>
        </tbody>
    </table>   

Open in new window



Here is function that adds the row....but as you can see it doesnt do anything to ensure the row is unique so it count be found later..or specifically the controls in that row.
 function addNewRow() {
        var table = $('#contactEntity-crud').DataTable();
        var row = $("#new-row-template").find('tr').clone();
        table.columns.adjust().draw();
        table.rows.add(row).draw();
        $('#contactEntity-crud tbody').prepend(row);
    }

Open in new window



Finally here is my function that is trying to find these controls....but  cannot ..


function InsertContactClient() {
if (true){ 
debugger;
 var contact = $('#hdnContactId').val();
 //var clientName =  $("#hdnClientName").val(inputlabel);
 var clientId =  $("#hdnClientId").val();
alert(clientId);
 var contact = $('#hdnContactId').val(); // value of Contact on Page
alert(contact);
 var role  = $("#ddlRole :selected").text(); // The text content of the selected option
alert(role);
 var roleValue = $("#ddlRole").val(); // The value of the selected option
 var designate = $("#selectdesignate :selected").text(); // The text of Designate primary or secondary
alert(designate);
 var allocation = $("#txtAllocation").val(); // The text value of the allocation 
alert(allocation);
    $.ajax({
        url: "/Contact.mvc/InsertContactClient/" + contact + "?clientId=" + clientId +  "&allocation=" +  allocation + "&role=" +  role + "&designate=" +  designate,
        type: 'GET',
        cache: false,
        dataType: 'json',
        data: { data: contact },
        success: function (data) {
                var result = $.trim(data.Result);               
                ShowGridRedraw();
                },
        error: function (request, status, error) {
        alert(request.responseText);
    }
      
     });
}
}

Open in new window

0
Robb Hill
Asked:
Robb Hill
  • 11
  • 4
  • 2
5 Solutions
 
Leonidas DosasCommented:
Inside addRow() function add an another function that it counts and add a data-id attr at all rows with a series .With this way you can manipulate the desired row as you want.
2
 
Robb HillSenior .Net DeveloperAuthor Commented:
its only the 1 row..that I cannot find......any idea how you might do that....I am about 3 hours in...and not coming up with the best way to iterate this properly.
0
 
Dustin SaundersDirector of OperationsCommented:
Leonidas is correct, you need to specify the row ids.  See below.

	var i = 1;
	
	$('#table_element').append('<tr id="row_n' + i + '"></tr>');
	$('#row_n' + i).html('whatever_HTML');
	i++;

Open in new window


What you could do in each row, is label each td wit the same value i as the row.  Then whatever row you select or if you have a button that row, have the function pass the row number i and you can use:

function thing(x) {
    var whatever = document.getElementById('row_n' + x);
}

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
Robb HillSenior .Net DeveloperAuthor Commented:
please elaboratate...I dont think this will work ..if I am understanding correctly.

I only need the row added to get this the controls prepended..

Can you please show example with atleast on of th elements(controls) in my row.


The reason I cannot do this id change on every control in every row ...is every other row...already has an id on it that I create ....its only the new row that doesnt...and has the conflict with the html template.

If I go and change every row..I will mess up that scheme.  I only need to somehow fix te newly added row.   The row is used to insert so its only ever one row that has this issue.
0
 
Robb HillSenior .Net DeveloperAuthor Commented:
Here is the code that creates the other rows..and you can see that I change the Id values as I build each row here.

 private void ExtendData(List<GenericGridData> list)
        {
            string designateString = "";
           
            IContactEntityEditService contactEntityEditService = DependencyResolver.Current.GetService<IContactEntityEditService>();
            List<string> roles = contactEntityEditService.GetContactLinkedEntitiesRoles();

          


            foreach (var contact in list)
            {

                switch (contact.designate)
                {
                    case "Primary":
                        designateString = "<select id='selectDesignate_" + contact.clientxcontactId + "'><option value = ''></option><option value='2' selected='selected'>Primary</option><option value='3'>Secondary</option></select>";
                        break;

                    case "Secondary":
                        designateString = "<select id='selectDesignate_" + contact.clientxcontactId + "'><option value = '1'></option><option value='2'>Primary</option><option value='3'  selected='selected'>Secondary</option></select>";
                        break;

                    default:
                        designateString = "<select id='selectDesignate_" + contact.clientxcontactId + "'><option value = '1' selected='selected'></option><option value='2'>Primary</option><option value='3'>Secondary</option></select>";
                        break;
                
                }
                                
                contact.role = selectlist(roles, contact.role, contact.role,contact.clientxcontactId);      
                contact.designate = designateString;
                contact.allocation = "<input type='number' step='0.01' value='0.00' placeholder='0.00'  id='txtAllocation_" + contact.clientxcontactId + "'>%</input>";
                contact.Update = "<button id=\"btnUpdate\" class=\"btn btn-primary btn-xs actionButton\"";
               
                contact.Update += "onclick=\"javascript:UpdateContactEntity('" + contact.clientxcontactId + "')\";>SAVE</button>";
                contact.Delete = "<button id=\"btnDelete\"  class=\"btn btn-danger btn-xs actionButton\"";
                contact.Delete += "onclick=\"javascript:DeleteContactEntity('" + contact.clientxcontactId + "')\";>DELETE</button>";

               
            }

              
        }

        public string selectlist(List<string> list, string label, string value,int id)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<select id = 'selectRole_" + id + "'>");
            foreach (string str in list)
            {
                if (str == value)
                    sb.Append("<option value='" + str + "' selected='selected'>" + str + "</option>");
                else
                    sb.Append("<option value='" + str + "'>" + str + "</option>");


            }
            sb.Append("</select>");

            return sb.ToString();
        }

    }
}

Open in new window

0
 
Dustin SaundersDirector of OperationsCommented:
Why can't you add a new id for the new row, maybe I'm not understanding?

What data is on the form when the user adds a new row?  Can you add into your template something like:

id="row_@"

Open in new window

And when you grab the row and controls on that row, replace the @ with your i variable.
.replace(new RegExp('@','g'),i))

Open in new window


But I'm not sure how you're assigning your other IDs.  What is contact.clientxcontactId and how would a new row get that value?

You could always assign the new rows a dummy HTML id and after inserting with that, use the response to update the ids with your desired value.
0
 
Robb HillSenior .Net DeveloperAuthor Commented:
a new row would never get that contact.clientxcontactid...that is a primary key coming from a database that I assigned when building that datatable to help me find the rows.....


So your idea sounds correct I think...the row template...in theory doesnt even need the same control names.....much less the ids...its just that the template and the new row added in the databable are not unique because one becomes hidden....so essentially the id is the same.

So if there was a way to replace the newly added row ID that would work......
0
 
Robb HillSenior .Net DeveloperAuthor Commented:
ifi you look at this function

function addNewRow() {
        var table = $('#contactEntity-crud').DataTable();
        var row = $("#new-row-template").find('tr').clone();
        table.columns.adjust().draw();
        table.rows.add(row).draw();

//////add some new function call here to change the row id
        $('#contactEntity-crud tbody').prepend(row);
    }

Open in new window



I think the function to change row ID would happen in my comment above...
how would I change this...there are anly a few.

If you look at html there is only lable, two dropdownlists, and a decimal input box.

 <tbody>
            
                    <label></label> 
              
                   @Html.DropDownList("ddlRole", new SelectList(ViewBag.DDLRoles, "Value", "Text"), "")
                
                    @Html.DropDownList("selectdesignate", new List<SelectListItem>
                    {
                        new SelectListItem{ Text="", Value = ""  },
                        new SelectListItem{ Text="Primary", Value = "Primary" },
                        new SelectListItem{ Text="Secondary", Value = "Secondary" },
                     })                 
                
                   @Html.TextBox("txtAllocation", new { @class = "form-control", @type = "number" })         
               

Open in new window

0
 
Leonidas DosasCommented:
function addNewRow() {
       var i=1;
        var table = $('#contactEntity-crud').DataTable();
        var row = $("#new-row-template").find('tr').clone();
        table.columns.adjust().draw();
        table.rows.add(row).draw();
        $('#contactEntity-crud tbody').prepend(row);
  
       //Get all the rows and sets a new data-idrow in each of them
       $('tr').each(function(){         
          $(this).attr('data-idrow',i);
          i++;
        });  
    }

Open in new window

1
 
Robb HillSenior .Net DeveloperAuthor Commented:
interesting...let me try.....be back shortly....thanks!!!!!!!!
0
 
Robb HillSenior .Net DeveloperAuthor Commented:
I am not sure how to use this code.


I see that this marked all my TR tags with this incrementing attribute...how does that help me find the value of the control?
0
 
Robb HillSenior .Net DeveloperAuthor Commented:
I have it doing this so far...this finds each control in the one row object...

but now I need to modify the id or add attribute when it finds each control

  function addNewRow() {
    debugger;
       var i=1;
        var table = $('#contactEntity-crud').DataTable();
        var row = $("#new-row-template").find('tr').clone();
        table.columns.adjust().draw();
        table.rows.add(row).draw();
        $('#contactEntity-crud tbody').prepend(row);
        row.find('label,input, select, textarea').each(function()
        {

            alert(this.tagName);
        });
    }

Open in new window

0
 
Robb HillSenior .Net DeveloperAuthor Commented:
OK ..using the attribute idea on the TR from before..I added the attribute on each of the controls.   So now I just need to know how to find that control using the attribute

  row.find('label,input, select, textarea').each(function()
        {
            $(this).attr('data-idrow',i);
            alert(this.tagName);
        });
0
 
Dustin SaundersDirector of OperationsCommented:
Just set the element's .id equal to whatever you want.
https://www.w3schools.com/jsref/prop_html_id.asp

In your template, just add in an id to whatever item you need.  As mentioned, one way to do it is to assign it a character you can replace then after you clone it, update that symbol.

"new_row_@"

use
.clone().replace(new RegExp('@','g'),i))

Open in new window


In your insert code, if you don't want to reload the table, you could update the IDs by doing your web method and returning the new id, then in the success() function roll back and update all of those elements with the newly returned id.

You can do the same thing for any control in that row, give it and id of "control_@" and rewrite that number as you generate it.

On my code that does similar work, I have all my controls assigned as:

"control_x_y" and replace x with the record number and y with the control number.  So when I go to collect all the data I can run a nested loop to grab it all.

It's hard to know more again without knowing the database, what you're inserting, and what it looks like on screen + intended behavior.  But if you are having a fundamental issue with the existing design, whats preventing you from re-structuring the way you do that to work with the problem you have?
1
 
Dustin SaundersDirector of OperationsCommented:
OK ..using the attribute idea on the TR from before..I added the attribute on each of the controls.   So now I just need to know how to find that control using the attribute

  row.find('label,input, select, textarea').each(function()
        {
            $(this).attr('data-idrow',i);
            alert(this.tagName);
        });

Open in new window


Make i a global variable and all you need to do is look for the row associated with (i - 1).  If you added multiple rows, iterate through them that same way.
0
 
Robb HillSenior .Net DeveloperAuthor Commented:
Dustin:

going back to your clone approach..which I liked alot after your 2nd post about it.....

but Im getting syntax errors on that.

var row = $("#new-row-template").find('tr').clone().replace(new RegExp('@','g'),i));

I am getting this error:


Parser Error
  Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

 Parser Error Message: "','" is not valid at the start of a code block.  Only identifiers, keywords, comments, "(" and "{" are valid.
0
 
Robb HillSenior .Net DeveloperAuthor Commented:
Once this set of controls in the 1 row have an attrribute..not sure of jquery selector to do that.

HEre is how I did it on id

 var roleValue = $("#ddlRole").val();

How would I rewrite that to find an attribute on that control
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 11
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now