Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

jquery,json and javascript best practices

Follow hybrid(both) approaches Change button text at loading time (before action) as well as Change button text after action

Creating dynamic success message based on action

Follow hybrid(both) approaches to add input field in form statically and dynamically

Dynamically add style and css

Dynamically add element of form handling

optimize-code -using-arrays-and-for-loops
empty content before appending data using id to display data

Follow hybrid(both) approaches Change button text at loading time (before action) as well as Change button text after action

Change button text at loading time (before action):

  @php
   $valueAfterColon = isset($item->addcarts) ? explode(':', $item->addcarts)[1] ?? null : null;
                        @endphp
                       @if ($valueAfterColon == 'yes' && auth()->user()->email == $parts[0])
                           <button type="submit"  
                            class="btn btn-sm  btn-primary" style="position: relative;float:right">Added</button> 
                           @else
                           <button id="callmyAjaxButton" class="btn btn-sm  btn-primary mr-2"   data-id="{{ $item->id }}"   style="position: relative;float:right" onclick="mySocialClick(this, event)">Add cartss</button>                                                 
                           @endif     
                           <button id="callAjaxButton" class="btn btn-sm  btn-primary mr-2"   data-id="{{ $item->id }}"   style="position: relative;float:right" onclick="myButtonClick(this, event)">View Pricess</button> 
Enter fullscreen mode Exit fullscreen mode

*output *

Image description

Change button text after action (in the if (data.success) { } block)

if (data.success) {
    $('#share-social').modal('hide');
    var prices = data.prices;
    var influencer = data.influencer;

    // Change button text to "Added"
    $('.addToCartBtn').text('Added');

    // Disable the button and add a disabled class
    $('.addToCartBtn').prop('disabled', true).addClass('disabled');
}
Enter fullscreen mode Exit fullscreen mode

*output *

Image description

Creating dynamic success message based on action

creating-dynamic-success-messages-in-laravel-with-jquery-modal
after success get server json data in blade page using jquery

     success: function(data) {
           // Handle the response from the server
           console.log(data);
           var html = '';
           if (data.success) {    
            $('#share-social').modal('hide');
            var prices = data.prices;
        var influencer = data.influencer;
        var publisher = data.publisher; 

        console.log('add prices success click ho rha ha', prices);
        var socialSiteCount;
        if (prices && Array.isArray(prices.prices)) {
    // Calculate the number of social sites
    var socialSiteCount = prices.prices.length;


    console.log('Number of social sites:', socialSiteCount);
        } else {
            console.log('Prices is not an object with a "prices" array or is undefined.');
        }

let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
                Publisher ${publisher} has successfully added an influencer ${influencer} for follwing sites with pricerate given below . Please check in the cart.
            </h5>`;
            for (let i = 0; i < socialSiteCount; i++) {
    const entry = prices.prices[i];
    const socialSite = entry.social_site;
    const price = entry.price;

    const socialSiteText = socialSite === 'face' ? `${socialSite}book` : socialSite;
    htmlCode += `<p class="text-center" style="margin: 2px 0; color: blue;">
        Social Site: ${socialSiteText}, Price: $${price} per post.
    </p>`;
}
            console.log('Influencer:', influencer);
            console.log('Publisher:', publisher);
            console.log('add success success click ho rha ha');
            $('#approve-modal').modal('show');
            $('#approvessmycart').html(`
            ${htmlCode}
               `);

           }
           else 
           {

           }
         },
Enter fullscreen mode Exit fullscreen mode

Follow hybrid(both) approaches to add input field in form statically and dynamically

Dynamic input fields are powerful for flexibility,
how-to-add-dynamic-input-field-after-click-add-button-in-laravel-blade-file-using-jquery

$(document).ready(function() {
    // Counter for dynamic input names
    let inputCounter = 2;

    // Event listener for "Add Input" button
    $('#add-input').click(function() {
        // Create a new input field with a unique name
        let newInput = `<div class="form-group">
                            <label for="input${inputCounter}">Input ${inputCounter}</label>
                            <input type="text" name="input${inputCounter}[]" class="form-control">
                        </div>`;

        // Append the new input field to the container
        $('#dynamic-inputs-container').append(newInput);

        // Increment the counter for the next input field
        inputCounter++;
    });
});
Enter fullscreen mode Exit fullscreen mode

Image description

Static input field form

 <form action="/submit" method="post">
        <!-- Static Input Fields -->
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>

        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>

        <!-- Submit Button -->
        <button type="submit">Submit</button>
    </form>
Enter fullscreen mode Exit fullscreen mode

Dynamically add element of form handling

how-to-add-dynamic-input-field-after-click-add-button-in-laravel-blade-file-using-jquery

Dynamically add style and css

list-out-the-checklist-different-way-to-add-and-remove-styles-using-jquery
dynamically-increase-the-height-or-width-of-a-text-input-textbox-based-on-the-number-of-lines-of-text-entered-into-it

optimize-code -using-arrays-and-for-loops

how-to-apply-presense-validation-in-form-handling-using-array-and-for-loop-in-jquery
Display different dynamic display message in same modal using append
how-to-to-optimize-multiple-ajax-requests-using-arrays-and-for-loops-in-jquery

empty content before appending data using id to display data

$('#mystatus').empty();
                $('#modification').empty();
                     $('#mystatus').append('<span><b>Influencer Status: </b>' + status + '</span>');
Enter fullscreen mode Exit fullscreen mode

append data using id after empty content
how-to-clear-the-content-of-the-html-element-before-rendering-using-jquery

Top comments (0)