Home > database >  dynamic link change color after click only the first link colors change
dynamic link change color after click only the first link colors change

Time:11-15

I create a dynamic link which created on the runtime and when I click on the link it change the color. But when I click on any other link it also change the first link not that link which I clicked.

My Code:

@foreach (var item in Model)
           {
                  <div >
                          
                           
                          
                   <a href="#"  id="favorite"onclick="Fav(@item.id)" >
                                <i ></i>
                 </div>
}
 <script>
      
        var btnvar = document.getElementById('favorite')
       function Fav(id) {
        var url = '@Url.Action("ajaxRent", "Home")';
        if(btnvar.style.color == "red"){
            btnvar.style.color = "grey"
        }
        else{
            btnvar.style.color = "red"
        }
        debugger

        $.ajax({
            url: url,
            type: 'POST',
            data: {
                id: id
            },
            success: function (data) {
                if(data.length == 0) // No errors
                    alert("Fave success!");
            },
            error: function (jqXHR) { // Http Status is not 200
            },
            complete: function (jqXHR, status) { // Whether success or error it enters here
            }
        }); 
    };

    
       </script>  

CodePudding user response:

Replace your code with the below code:

@foreach (var item in Model)
           {
                  <div >
                          
                           
                          
                   <a href="#"  id="favorite"onclick="Fav(this)" >
                                <i ></i>
                 </div>
}
 <script>
      
        function Fav(x) {
        var url = '@Url.Action("ajaxRent", "Home")';
        if(x.firstElementChild.style.color == "red"){
            x.firstElementChild.style.color = "grey"
        }
        else{
            x.firstElementChild.style.color = "red"
        }
        debugger

        $.ajax({
            url: url,
            type: 'POST',
            data: {
                id: x.id
            },
            success: function (data) {
                if(data.length == 0) // No errors
                    alert("Fave success!");
            },
            error: function (jqXHR) { // Http Status is not 200
            },
            complete: function (jqXHR, status) { // Whether success or error it enters here
            }
        }); 
    };

    
       </script>  

Important note: If phone number anchor tag is repeating then use unique ID every time.

Please let me know if you have any issue.

  • Related