Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to Handling Conditional Styling on button in JavaScript

Index
creating card layout and 3 button
button is visible based on condition
button text changes based on condition
button is disable or not based on condition
button is clickable or not based on condition
button background color is visible based on condition
call loading function and display dynamic message at same time after getting json data
call loading function and open pop up modal at same time after getting json data
how one button(modify) visibility depends on another button(approve)

step 1: create a one card body(card-body row) and divide into 3 parts (col-md-4).
first button view detail is always visible by default

 cardContent += '<div class="card-body row">';
        cardContent += '<div class="left-content col-md-4">'; // Added 'col-md-10' class for the left content
        cardContent += '<button class="btn btn-primary influencer-button"   data-orders_id="' + item.orders_id + '"   data-order_product_id="' + item.order_product_id + '" data-id="' + item.id + '">View Detail</button>';
        cardContent += '</div>';
Enter fullscreen mode Exit fullscreen mode

Image description

step2:create a second button inside another col-md-4 Approve that is visible conditionally

 cardContent += '<div class="left-content col-md-4">'; // Added 'col-md-10' class for the left content
        var backgroundColor = (item.publisher_status === 'Approve') ? '#4CAF50' : '#0069d9';
        var backgroundsColor = (item.publisher_status === 'InProgress' && item.status == 'completed') ? '#4CAF50' : '#0069d9';
        var isDisabled = (item.publisher_status == 'Approve') ? 'disabled' : ''; 
        var isDisableds = (item.publisher_status == 'InProgress' && item.status == 'completed' ) ? 'disabled' : ''; 
// Check the condition and add the "disabled" attribute if necessary
if (item.status == 'completed' && item.publisher_status !== 'Approve' ) {
  cardContent += '<button class="btn btn-danger tasks-approve"  style="background-color:' + backgroundColor + '; cursor: ' + (isDisabled ? 'not-allowed' : 'pointer') + '"  " data-id="' + item.id + '"';

  cardContent += '>Approve</button>';
}
if (item.status == 'Todo' && item.publisher_status !== 'Approve' ) {
  cardContent += '<button class="btn btn-danger tasks-approve"  style="background-color:' + backgroundColor + '; cursor: ' + (isDisabled ? 'not-allowed' : 'pointer') + '"  " data-id="' + item.id + '"';

  cardContent += '>Approve</button>';
}

if (item.status == 'completed' && item.publisher_status == 'Approve' ) {
  cardContent += '<button class="btn btn-danger tasks-approve"  style="background-color:' + backgroundColor + '; cursor: ' + (isDisabled ? 'not-allowed' : 'pointer') + '"  " data-id="' + item.id + '"';

  cardContent += '>Approved</button>';
}

        cardContent += '</div>';
Enter fullscreen mode Exit fullscreen mode

here i apply 3 condition

button is visible based on two field of table status and publisher_status conditionlly

Image description

Image description

and color of button apply conditionally

 var backgroundColor = (item.publisher_status === 'Approve') ? '#4CAF50' : '#0069d9';
 cardContent += '<button class="btn btn-danger tasks-approve"  style="background-color:' + backgroundColor + '; cursor: ' + (isDisabled ? 'not-allowed' : 'pointer') + '"  " data-id="' + item.id + '"';

Enter fullscreen mode Exit fullscreen mode

button is disable or not based on publisher_status field
and button arrow cursor also apply conditionally based on disable

 var isDisabled = (item.publisher_status == 'Approve') ? 'disabled' : ''; 
 cardContent += '<button class="btn btn-danger tasks-approve"  style="background-color:' + backgroundColor + '; cursor: ' + (isDisabled ? 'not-allowed' : 'pointer') + '"  " data-id="' + item.id + '"';
Enter fullscreen mode Exit fullscreen mode

not disable and allow clickable

Image description

disable and not clickable
button text changes to approve to approved
condition 3rd

if (item.status == 'completed' && item.publisher_status == 'Approve' ) {
  cardContent += '<button class="btn btn-danger tasks-approve"  style="background-color:' + backgroundColor + '; cursor: ' + (isDisabled ? 'not-allowed' : 'pointer') + '"  " data-id="' + item.id + '"';

  cardContent += '>Approved</button>';
}
Enter fullscreen mode Exit fullscreen mode

Image description

when we click then pass it in server side

$(document).on('click', '.tasks-approve', function() {
  console.log("tasks-approve aata");
    var orderId = $(this).data('id'); 
    $.ajax({

        type: 'GET',
                url: "{{ route('tasks-approve') }}",
                data: {
                    id: orderId

                },
        success: function(data) {
          var sharedata = data.sharedata;                    
                console.log('sharedata:', sharedata); 
                var influencer_name = data.influencer;             
              var publisher_name = data.publisher;
              var data=data.data;
              displayFilteredData(data);
              $('#approve-modal').modal('show'); 
              $('#approvessmycart').empty();

              $('#approvessmycart').append('<div style="color: black;font-family: Arial, sans-serif; margin-left: 10px;  padding: 10px; border-radius: 5px;">' +
                                '<b>publisher ' + publisher_name + '</b> approved <b>influencer ' + influencer_name + '</b> successfully' +
                '</div>');

                console.log('view-button ka data aata hain');              

        },
        error: function(error) {
            // Handle error
        }
    });
});

Enter fullscreen mode Exit fullscreen mode

server side controller function
here update status and publisher_status field both and insert time by what time we have updated

    public function tasksapprove(Request $request)
    {
     Log::info($request);
     $input = $request->all();
     Log::info(' sharemysuggestion via AJAX:', $request->all());      
  $id=$request->id;        
$shareingdata= DB::connection('payments')->table("sharedatas")->where('id',$id)->first();
$publisher_name=$shareingdata->user_name;
$influencer_name=$shareingdata->pay_influencer_name;
$sharemytask= DB::connection('payments')->table("sharedatas")->where('id',$id)->update(array('publisher_status' =>'Approve','status' =>'completed','publisher_date' => now()));
$authid = Auth::user()->id;
$users=sharedata::where('admin_id', $authid)->whereNotNull('influencer_payment_id')->get();   


return response()->json([
                    'message' => "task disapprove successfully", 
                    'success' => "task disapprove successfully", 
                    'publisher' => $publisher_name, 
                    'influencer' => $influencer_name,
                    'data' => $users,
      ]);

 }
Enter fullscreen mode Exit fullscreen mode

after getting json data we call loading function to see changes and display dynamic message

call loading function

 displayFilteredData(data);
Enter fullscreen mode Exit fullscreen mode

display dynamic message
note: before display dynamic msg must empty the content otherwise duplicate content visible
$('#approvessmycart').empty();

$('#approve-modal').modal('show'); 
              $('#approvessmycart').empty();              
              $('#approvessmycart').append('<div style="color: black;font-family: Arial, sans-serif; margin-left: 10px;  padding: 10px; border-radius: 5px;">' +
                                '<b>publisher ' + publisher_name + '</b> approved <b>influencer ' + influencer_name + '</b> successfully' +
                '</div>');
Enter fullscreen mode Exit fullscreen mode

Image description

step3:create a Third button inside another col-md-4 within card body row Modify that is visible conditionally

  cardContent += '<div class="left-content col-md-4">'; // Added 'col-md-10' class for the left content

// Check the condition and add the "disabled" attribute if necessary
      if (item.status == 'completed'  && item.publisher_status !== 'InProgress' &&  item.publisher_status !== 'Approve') {
        cardContent += '<button class="btn btn-danger tasks-modification"  style="background-color:' + backgroundsColor + '; cursor: ' + (isDisableds ? 'not-allowed' : 'pointer') + '"  " data-id="' + item.id + '"';

       cardContent += '>Modify</button>';  

      }
      if (item.status == 'Todo'  && item.publisher_status == 'InProgress') {
        cardContent += '<button class="btn btn-danger tasks-modification"  style="background-color:' + backgroundsColor + '; cursor: ' + (isDisableds ? 'not-allowed' : 'pointer') + '"  " data-id="' + item.id + '"';

       cardContent += '>Modify</button>';  

      }
      if (item.status == 'completed'  && item.publisher_status == 'InProgress') {
        cardContent += '<button class="btn btn-danger tasks-modification"  style=" background-color:' + backgroundsColor + '; cursor: ' + (isDisableds ? 'not-allowed' : 'pointer') + '" " data-id="' + item.id + '"';

       cardContent += '>Modification</button>';  

      }   

              cardContent += '</div>'; 
Enter fullscreen mode Exit fullscreen mode

button is visible based on two field status and publisher status
button text either modify or modification based on condition
button is disable or not based on condition
buttons background-color also dependes on condition

 cardContent += '<button class="btn btn-danger tasks-modification"  style="background-color:' + backgroundsColor + '; cursor: ' + (isDisableds ? 'not-allowed' : 'pointer') + '"  " data-id="' + item.id + '"';      
       cardContent += '>Modify</button>';
Enter fullscreen mode Exit fullscreen mode
  cardContent += '<button class="btn btn-danger tasks-modification"  style=" background-color:' + backgroundsColor + '; cursor: ' + (isDisableds ? 'not-allowed' : 'pointer') + '" " data-id="' + item.id + '"';

       cardContent += '>Modification</button>'; 
Enter fullscreen mode Exit fullscreen mode

Image description

when we click modify button one pop up modal open

$(document).on('click', '.tasks-modification', function() {
    var orderId = $(this).data('id'); 
    $('#share_id').val(orderId);   
    $('#modificationtext-modal').modal('show'); 
});
Enter fullscreen mode Exit fullscreen mode
 <div id="modificationtext-modal" class="modal fade" role="dialog">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header" style="background-color:#d1e50a;">
                                <h3> Publisher Review</h3>
                                    <button type="button" style="color:black;" class="close"  data-dismiss="modal"> &times;</button>
                                    <br>                                    
                                </div>
                                <center> <div class="modal-body" style="background-color:#dade95ad;">
                                <form method="post" id="suggestion_form" style="margin-left:-10px;" class="form-horizontal" enctype="multipart/form-data">
                                            @csrf                                            

                                                <div class="form-group"  id="suggestFields">
                                                    <label class="control-label" style="color: black;"> Suggestion : </label>                                                 
                                                    <textarea id="suggest_write_up"  name="suggest_write_up" id="suggest_write_up"  rows="4" cols="4" class="form-control" WRAP ></textarea>                                                    
                                                </div>
                                            <!-- Sending admin_id and admin_email in hidden input box -->
                                            <input type="hidden" value="{{ Auth::user()->id }}" name="admin_id" id="admin_id" />
                                            <input type="hidden" value="{{ Auth::user()->email }}" id="admin_email" name="admin_email" />
                                            <input type="hidden"  name="influencer_email" id="influencer_email">
                                       <input type="hidden"  name="influencer_admin_id" id="influencer_admin_id">
                                       <input type="hidden" name="action" id="action" />
                                        <input type="hidden" name="hidden_id" id="hidden_id" />
                                        <input type="hidden" name="share_id" id="share_id" />                                        
                                        <button type="submit" name="action_button" id="action_button" class="btn btn-sm py-1 btn-primary me-2" value="Add">Submit</button>
                                    <input type="hidden"  name="payment_id" id="payment_id">
                                    </div>                                  
                                    </form>
                                </div></center>
                            </div>
                        </div>
                    </div>
Enter fullscreen mode Exit fullscreen mode

Image description

when we submit form ajax route is passing with request parameter and server side action is processing

$('#suggestion_form').on('submit', function(event) {
      event.preventDefault();

      if ($('#action_button').val() == 'Add') {
        console.log('add button click ho rha ha');
        $.ajax({
          url: "{{route('sharemysuggestion.store') }}",
          method: "POST",
          data: new FormData(this),
          contentType: false,
          cache: false,
          processData: false,
          dataType: "json",
          headers: {
            "Authorization": "Bearer " + localStorage.getItem('a_u_a_b_t')
          },
          beforeSend: function() {

          },

          success: function(data) {
            $('#modificationtext-modal').modal('hide'); 
            var sharedata = data.sharedata;                    
                console.log('sharedata:', sharedata); 
                var influencer_name = data.influencer;             
              var publisher_name = data.publisher;
              data=data.data;
              displayFilteredData(data);

              $('#modification-modal').modal('show'); 
              $('#modificationmsg').empty();

              $('#modificationmsg').append('<div style="color: black;font-family: Arial, sans-serif; margin-left: 10px;  padding: 10px; border-radius: 5px;">' +
                                '<b>publisher ' + publisher_name + '</b> gave some modification to<b>influencer ' + influencer_name + '</b> successfully' +
                '</div>');

                console.log('view-button ka data aata hain')
          },
          error: function(xhr, status, error) {           
            console.log(error);
          }
        });
      };
    })
Enter fullscreen mode Exit fullscreen mode

In server side we update two field status and publisher_status then insert time when we update

 public function sharemysuggestion(Request $request)
 {
  Log::info($request);
  $input = $request->all();
  Log::info(' sharemysuggestion via AJAX:', $request->all()); 
$id=$request->share_id;
Log::info($id);
$write_up=$request->suggest_write_up;
Log::info($write_up);
$shareingdata= DB::connection('payments')->table("sharedatas")->where('id',$id)->first();

$publisher_name=$shareingdata->user_name;
$influencer_name=$shareingdata->pay_influencer_name;
$sharemytask= DB::connection('payments')->table("sharedatas")->where('id',$id)->update(array('publisher_status' =>'InProgress','status' =>'Todo','suggestion' => $write_up,'publisher_date' => now()));
$authid = Auth::user()->id;
$users=sharedata::where('admin_id', $authid)->whereNotNull('influencer_payment_id')->get();           
return response()->json([
                    'message' => "task disapprove successfully", 
                    'success' => "task disapprove successfully", 
                    'publisher' => $publisher_name, 
                    'influencer' => $influencer_name,
                    'data' => $users,
      ]);
}
Enter fullscreen mode Exit fullscreen mode

after getting json data from server side we call loading function and display dynamic message

displayFilteredData(data);

 success: function(data) {
            $('#modificationtext-modal').modal('hide'); 
            var sharedata = data.sharedata;                    
                console.log('sharedata:', sharedata); 
                var influencer_name = data.influencer;             
              var publisher_name = data.publisher;
              data=data.data;
              displayFilteredData(data);

              $('#modification-modal').modal('show'); 
              $('#modificationmsg').empty();

              $('#modificationmsg').append('<div style="color: black;font-family: Arial, sans-serif; margin-left: 10px;  padding: 10px; border-radius: 5px;">' +
                                '<b>publisher ' + publisher_name + '</b> gave some modification to<b>influencer ' + influencer_name + '</b> successfully' +
                '</div>');

                console.log('view-button ka data aata hain')
          },
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)