user3214392 user3214392 - 6 months ago 16
HTML Question

Enable/Disable Html button based on the data from the server

I am using datatable Jquery and making an ajax call to read data from the server.
Lets say database has 3 attributes "Attribute1 , Attribute2, Status".
Depending upon the Status, the third column on the datatable should be enabled or disabled button.

function test(server_url,table_id){
.ajax({url: server_url,dataType:"html",success: function(result){
var json_obj=JSON.parse(result);
var Columns="<thead><tr>";
var Fields=[],Tool_columns=[];
UserGroupFields=json_obj.columns;
for(i=0;i<json_obj.columns.length;i++){
Columns+="<th>"+json_obj.columns[i]+"</th>";
var field_dic={};
var tool_dic={};
field_dic["label"]=json_obj.columns[i];
field_dic["name"]=json_obj.columns[i];
Fields[i]=field_dic;
Tool_columns[i]=tool_dic;
}
tool_dic["targets"]=-1;
tool_dic["data"]="null";
tool_dic["defaultContent"]="<button this.disabled=true'>Yes</button>";
myTable=('#'+table_id).DataTable({
"order":[[0,"desc"]],
aaData:json_obj.data,
dom: 'T<"clear">lfrtip',
columns:Tool_columns,
tableTools: {
sRowSelect: 'single',
"sRowSelector": "td:not(:last-child)",
"aButtons": [ {
"sExtends": "editButton",
"sButtonText": "Edit",
"target": "#"+table_id
}]
},
"search": {
"regex": true,
"smart": false
}
});


Through above code I am able to add a button to each row read from the server . So how do I now enable or disable it based on the third atrribute of each record "Status".

Type of Data :

Object { columns: Array[3], data: Array[2] }


Data :

[{"column1":"1","Column2":"abc","Status":"Yes"},{"column1":"2","Column2":"xyz","Status":"No"}]


Any leads would be appreciated.
I am new to JQuery and JavaScripts

Thanks

Answer

Check the value of status in data and set the button in aaData accordingly.

Added one line in your code :

field_dic["button"]=(json_obj.columns[i]["status"]=="LIVE")?"Button Text":"Button Text";

for(i=0;i<json_obj.columns.length;i++){
        Columns+="<th>"+json_obj.columns[i]+"</th>";
        var field_dic={};
        var tool_dic={};
        field_dic["label"]=json_obj.columns[i];
        field_dic["name"]=json_obj.columns[i];
        field_dic["button"]=(json_obj.columns[i]["status"]=="LIVE")?"<button disabled='disabled'>Button Text</button>":"<button>Button Text</button>";
        Fields[i]=field_dic;
        Tool_columns[i]=tool_dic;
    }

Loop to read "Status" value and set the value accordingly.

for(i=0;i<json_obj.data.length;i++){
    if(json_obj.data[i]["Status"]=="Yes"){
       json_obj.data[i]["Status"]="<button disabled='disabled'>Button Text</button>";
    }
    else{
        json_obj.data[i]["Status"]="<button>Button Text</button>";
    }
}