5

I want to add data variables to an element before causing a specific behavior, but this may require adding more than one data parameter. How can I accomplish this?

     $("#dlg_box").data("r_redirect","index.php").dialog("open");
Brett Weber
  • 1,839
  • 18
  • 22
Hosea Kambonde
  • 291
  • 1
  • 4
  • 13
  • 3
    Uhm, you may need to elaborate. As it stands, your question is the equivalent to "My goldfish died, any idea why?" – SpYk3HH May 21 '13 at 13:19
  • I'm pressuming you're passing the 'Open' param,right? Any errors or anything thrown in the console that could provide some insight? a bit more info (as much as you can! - could really help.. it's not a very well structured question...) – Stuart.Sklinar May 21 '13 at 13:20
  • Yes @97ldave, r_redirect should be the key and index.php the value, but how do i pass two keys? – Hosea Kambonde May 21 '13 at 13:23
  • Check out my answer below. @Abilash answer will also work. I prefer the way mine reads, its a bit more clear to understand/maintain. – 97ldave May 21 '13 at 13:44
  • [Look at updated answer, please. There are aspects not mentioned here that may dramatically effect code](http://stackoverflow.com/a/16671269/1257652) – Brett Weber May 21 '13 at 17:10

5 Answers5

8

You can do it like this:

var data = $("#dlg_box").data();   
data.r_redirect = "index.php";  
data.foo = "bar";

$("#dlg_box").dialog("open");

This was taken from here.

To retrieve your values:

$("#dlg_box").data("r_redirect");
$("#dlg_box").data("foo");
Community
  • 1
  • 1
97ldave
  • 5,249
  • 4
  • 25
  • 39
4

JQuery's data() method also takes an JS Object as a parameter. So you might think of passing {"r_redirect": "index.php", "whatEver": "youWant" ...} etc to pass multiple values match your requirement.

Ultimately, the data() method converts your parameters into an Object. So whether you pass an Object or Key and Value separately should not matter

Abilash
  • 6,089
  • 6
  • 25
  • 30
  • View my updated answer, your solution is actually quite incorrect. The object you pass is stored as a parameter and is only accessible by reference... something everyone should be aware of – Brett Weber May 21 '13 at 17:21
4

There are different ways to attach data to a jQuery dialog. If you need to attach multiple Data, I recomend using .data("myData", { /* OBJECT */ }, however you can also use inline string and array data. As far as why yours won't work, with so little code to go on, it could be numerous things. However, I've attached a working example of a Dialog with "params" or data for you to take example from. If you post more of your header code tho, I have a feeling we might find a syntax error or a lack of "doc ready" included. Just some thoughts. Anyway, my example:

jsFiddle

$(function() {
    //    Set the dialog to not open on load and clear all changes made when closed
    $("#dlg").dialog({
        autoOpen: false,
        modal: true,
        close: function(e) {
            $(this).children("input").nextAll("p").remove();
        }
    })    //    next i call for my first inner button which will show you how to get "attached" data
    .children("#attached").on("click", function(e) {
        var dlgData = $("#dlg").data("myData");
        $(this).after($("<p />").text(dlgData.data1 + " " + dlgData.data2));
    })    //    finally, the button that will get the string data that was added in the HTML
    .next("#inline").on("click", function(e) {
        var dlgData = $("#dlg").data("inline");
        $(this).after($("<p />").text(dlgData));
    });
    //    simply open our dialog
    $("button").on("click", function(e) { 
        //    HERE data is ATTCHED to our dialog just before opening
        $("#dlg").data("myData", { data1: "Hello", data2: "world" }).dialog("open") 
    });
});
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
1
$('#Dialog').data('data1', data1).data('data2', data2).dialog('open');

While Initializing the dialog get the values following:

var data1 = $(this).data('data1');
var data2 = $(this).data('data2');
Andre Hofmeister
  • 3,185
  • 11
  • 51
  • 74
Amit Gupta
  • 11
  • 1
0

There are some rules you should be aware of before using this!

ADDING

Adding variables using the object returned from $('.selector').data() works because the data object passes by reference, so anywhere you add a property, it gets added. If you call data() on another element, it gets changed. It is what it is what it is...

Adding an object places a object inside of the data object, as well as "extends the data previously stored with that element." - http://api.jquery.com/data/#entry-longdesc

That means that adding an obj to dataObj becomes

dataObj === { /*previous data*/, obj : { } }

Adding an array does not extend the data previously stored, but doesn't behave the same as a simple value either...

USING

If you have simple values stored, you can place them into variables and do what you want with them without changing the data object.

however

if you are using an object or array to store data on an element, beware!

Just because you store it to a variable does not mean you are not changing data value. Just because you pass it to a function does not mean you are not changing data values!

It is what it is what it is.. unless it's simple.. then it's just a copy. :p

var data             = $("#id").data();  // Get a reference to the data object 
data.r_redirect      = "index.php";      // Add a string value
data.num             = 0;                // Add a integer value
data.arr             = [0,1,2];          // Add an array
data.obj             = { a : "b" };      // Add an object

                                         // but here is where the fun starts! 

var r_redirectString = data.r_redirect;  // returns "index.php", as expected.. cool
r_redirectString     = "changed"         // change the value and the compare :
data.r_redirect      == r_redirectString // returns false, the values are different

var oArr             = data.arr;         // Now lets copy this array
oArr.push(3);                            // and modify it.
data.arr            == oArr              // should be false? Nope. returns true.
                                         // arrays are passed by reference.
                                         // but..

var oObj             = data.obj          // what about objects?       
oObj["key"]          = "value";          // modify the variable and
data.obj["key"]     == oObj["key"]       // it returns true, too!

So, resources..

What's the best way to store multiple values for jQuery's $.data()? https://stackoverflow.com/a/5759883/1257652

Community
  • 1
  • 1
Brett Weber
  • 1,839
  • 18
  • 22
  • Why do want to invoke data method again? doesn't make sense. – Abilash May 21 '13 at 13:30
  • because if the OP is not wanting the data to be contained in an object and wants to add two separate data values for two different situations he can. I'm updating my answer to link to yours and add additional information to reflect your valid point – Brett Weber May 21 '13 at 13:35
  • Even if you pass `Key and Value` separately, `data()` method converts it into an Object – Abilash May 21 '13 at 13:36
  • Makes sense, then, but I prefer to add them seperately for clarity. There may be a slight performance hit, but my code is more readable for me. I may try to use your solution in my code as well, thank you for adding value to this question! – Brett Weber May 21 '13 at 13:39