Home > Net >  How to get json decode value from data attribute in jquery
How to get json decode value from data attribute in jquery

Time:12-31

I am working with jquery and right now i am passing "Php array with json encode" in "data attribute" and right now i am trying to get this (json encode) value in jquery, But right now i am getting "new" (after update/new) value instead of existing,How can i do this ? Here is my current code

 echo '<td class=try contenteditable="true" data-id="'.$id.'" data-txt="'.json_encode($col).'">'; //$col is array



   <script>
        $("td").keypress(function(e){
            var id = $(this).attr("data-id")
            var newtxt = $(this).attr("data-txt")
             var oldtext = $(this).text();
                 if(e.which == 13) {
                alert('oldtext is ' oldtext);   
            }
     });
    </script>

CodePudding user response:

To get the existing value of the data-txt attribute, you can use the .data() function in jQuery. Here is an example of how you can use it:

$("td").keypress(function(e){
    var id = $(this).attr("data-id");
    var oldtext = $(this).text();
    var newtxt = $(this).data("txt");
    if(e.which == 13) {
        alert('oldtext is '   oldtext);
        alert('newtxt is '   newtxt);
    }
});

The .data() function retrieves the value of the data-txt attribute and stores it in the newtxt variable. You can then use this variable to access the value of the data-txt attribute.

Alternatively, you can also use the .attr() function to get the value of the data-txt attribute, like this:

var newtxt = $(this).attr("data-txt");

Both of these approaches will allow you to access the value of the data-txt attribute in your jQuery code.

  • Related