1

Possible Duplicate:
Variable name as a string in Javascript

What I'm trying to do is have an input field to edit some information. I'm setting it up so that as each field is changed (a combination of text boxes and checkboxes), AJAX updates the information and shows the changes in a profile box (server load is low, not concerned about efficiency here). If the user hits Escape, I want the value in the text box to revert to the original value (if they were editing a field that they changed their mind on). For the text boxes I've run into a variable issue - I know I can use arrays or hidden fields, but now I want to know how to make this version work :)

I set my variable:

 var first_name = "' || i.instructor_fname || '";

I have my input field:

<input type="text" id="first_name" value="' || i.instructor_fname ||'">

and the Escape function:

if (e.keyCode == 27) { 
   if (document.activeElement.id != "" ) {
       $("#" + document.activeElement.id)
                 .val(document.activeElement.id);
   }
}

For first_name, the output is first_name. The value is set correctly, as the text boxes are populated correctly. It seems that I'm not getting 'first_name' to be read as a variable, but as a string. I've tried a few combinations of joining literals to it, but still no luck. Any ideas out there? Again, I know I can use other techniques for this, but it seems like figuring this out might come in handy for other projects.

Community
  • 1
  • 1
ini
  • 201
  • 1
  • 4
  • 14
  • Well, `document.activeElement.id` is a string, why do you expect JavaScript to interpret it as variable name? – Felix Kling Jul 26 '12 at 20:55
  • You never *use* the variable ... the *value* `"first_name"` is used in a few places. –  Jul 26 '12 at 20:56
  • Am I at a dead-end then? – ini Jul 26 '12 at 20:58
  • You should have a look at the question I linked to. – Felix Kling Jul 26 '12 at 21:02
  • 1
    @FelixKling OP has already pointed out that he knows arrays and other techniques are avaliable. Plus I don't think this a duplicate of the link you provided. OP effectivly wants to evaluate the string as a varible to use the vars value. Your link asks how to reflect on a variable to get the variable name as a string. That's how I read it anyways. – Chris Moutray Jul 26 '12 at 21:13

4 Answers4

1

I'm not sure I understand, but perhaps you need to call eval() on document.activeElement.id.

nicolagi
  • 1,289
  • 13
  • 18
  • That's exactly what I needed! It won't let me 'check' this answer for 8 minutes. – ini Jul 26 '12 at 21:01
  • 1
    There is a much better way than `eval`: http://stackoverflow.com/questions/4602141/variable-name-as-a-string-in-javascript – Felix Kling Jul 26 '12 at 21:01
  • I'm still learning JS - why would using eval be bad/wrong? It seems simple and works perfectly for my issue.. – ini Jul 26 '12 at 21:07
  • @ini: It's just not a good solution. What you actually want is a specific data structure, a map of `field_name -> original value`. You can use objects for that in JavaScript. Use the right tools for the right task. – Felix Kling Jul 26 '12 at 21:14
  • @ini `eval` should be avoided at all costs, because it grants to much privileges the the evaluated string. It's a potential security issue and on top it's slow because the JS engine needs to parse the string. – Christoph Jul 26 '12 at 21:17
0

I am not sure I understand either, but how close is this coming?

http://jsfiddle.net/PXcD8/

html:

<input type="text" id="foobar">

js:

$(function()
{
    $(':text').each(function()
    {
        var text = $(this);
        text.keyup(function(event)
        {
            if (event.which == 27)
                reset_textbox();
        });

        reset_textbox();

        function reset_textbox()
        {
                text.val(text.attr('id'));            
        }
    });
});

This will set the text of a textfield to the same value as its id initially and when the user has pressed escape having it focused.

Anders Lindén
  • 6,839
  • 11
  • 56
  • 109
  • Please add your code here as well and provide an explanation. If the link is down for whatever reason, your answer becomes useless. – Felix Kling Jul 26 '12 at 21:15
  • That's not quite what I need for this application, but its nice and slick for and might be useful in the future. bruciasse had it correctly in that i need to eval() to get things to come out right – ini Jul 26 '12 at 21:17
0

A more appropriate solution would be to create a field_id -> value map. This can be easily done with objects:

var field_values = {
    first_name: "' || i.instructor_fname || '",
    last_name: "...',
    // ...
};

Then you can get the value by simply using bracket notation:

$("#" + document.activeElement.id)
    .val(field_values[document.activeElement.id]);

Assuming that the executed handler is bound to the element you want to modify, the code becomes as simple as:

$(this).val(field_values[this.id]);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

If your looking for an alternative solution why not simply include a default-value attribute with your input.

<input type="text" id="first_name" value="' || i.instructor_fname ||'"
    default-value="' || i.instructor_fname ||'" />

then within your Escape key handler

if (e.keyCode == 27) if (document.activeElement.id != "" ) {
    var e = $("#" + document.activeElement.id);
    e.val(e.attr('default-value'));
}

Personally this feels a bit more elegant/cleaner than having javascript variables floating about.

In addition...

Thinking about the implementation assuming the default-value always matched the input elements initial value then you wouldn't even need to change how the server renders the markup for your page. I.e. still render your original input element (minus the default-value attribute).

<input type="text" id="first_name" value="' || i.instructor_fname ||'" />​

All you would need is the following startup script

$(document).ready(function() {
    $('input').each(function() {
        var e = $(this);
        e.attr('default-value', e.val());
    });
})
Chris Moutray
  • 18,029
  • 7
  • 45
  • 66