1

I did try to do this (with jQuery):

type = (blabla == blublu)? 'category':'regular';
(type+'Name').val('...');

this is the console response:

Uncaught TypeError: Object categoryName has no method 'val'

although they actually exist...

so how can I make it work??

edit:

this is the full function:

var type = (1 == 1)?'something':'blabla';

var somethingName = $('#somethingName');
var blablaName = $('#blablaName');
more variables like this..

function itemMode(mode, inputValue){
  inputValue = (typeof inputValue !== 'undefined')? inputValue:'';
  var functionName = null;
  switch(mode){
  case 'open':
    btnValue = 'something';
    functionName = editCategory; // this need to be from type to
    openItem = true;
    break;
  case 'close':
    btnValue = 'something';
    functionName = addCategory; // this need to be from type to
    openItem = false;
    break;
  default:
    return false;
  }
  (type+'Name').val(inputValue);
  $('#btn'+type.capitalize()).off('click').val(btnValue).click(functionName);
  (type+'Name').off('keypress').keypress(function(e){enterPress(e,functionName);});
}

i try (type+'Name') to crate reference to an existing var or object.

GoDLighT
  • 148
  • 10

5 Answers5

8

Your problem is not with the concatenation. That works fine. You concatenate type with 'Name', and you get the string 'categoryName'. You then do this:

('categoryName').val(...);

This is the same as 'categoryName'.val(...), which obviously won't work, because strings do not have a val method.

You are attempting to do a jQuery selection, for which you need the jQuery constructor:

$(type+'Name').val('...');

This, of course, is also unlikely to work, unless you have elements with the tag name categoryName. Presumably you actually want elements with that class:

$('.' + type + 'Name')

or id:

$('#' + type + 'Name')

or something similar.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • ya i thought about it but ן'm trying to do a function that will fit some situations and this is not the only id thet influence form that function – GoDLighT Nov 04 '13 at 13:11
2

Variables are created as properties of the window object, so if they are global you can do this...

window[type + "Name"]

Since you want to refer to a "cached" jQuery object, use the following...

(window[type + "Name"]).val("123");

For example, if you've cached a jQuery object like this...

var sumVar = $('#sumid');

You can refer to it directly like this...

sumVar.val("123");

Or you can refer to it using a variable as the name, like this...

var varName = "sumVar";

(window[varName]).val("123");

Here's a modified version of the script you posted above...

var type = (1 == 1)?'something':'blabla';

window.somethingName = $('#somethingName');
window.blablaName = $('#blablaName');

function itemMode(mode, inputValue){
    inputValue = (typeof inputValue !== 'undefined')? inputValue:'';
    var functionName = null;
    switch(mode){
        case 'open':
            btnValue = 'something';
            functionName = editCategory; // this need to be from type to
            openItem = true;
            break;
        case 'close':
            btnValue = 'something';
            functionName = addCategory; // this need to be from type to
            openItem = false;
            break;
        default:
            return false;
    }

    (window[type + 'Name']).val(inputValue);

    $('#btn' + type.capitalize()).off('click').val(btnValue).click(functionName);

    (window[type + 'Name']).off('keypress').keypress(function(e){enterPress(e,functionName);});
}
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
  • it just i dont want to do this $('#sumid') in the function because i did it 2 lins before the function declared so i did $('#sumId') into sumVar and when i do sumVar.jQuerystuff() it work but when i try to expand my function to more same suff i need it to be variable – GoDLighT Nov 04 '13 at 14:45
  • I learned Programming not to repeat things twice, this is my goal – GoDLighT Nov 04 '13 at 14:47
  • Okay, I've updated the answer and I *think* it will help more. – Reinstate Monica Cellio Nov 04 '13 at 14:52
  • If you just want to refer to a cached jQuery object then just use the variable. `var $body = $("body"); $body.hide();` - for example. – Reinstate Monica Cellio Nov 04 '13 at 15:04
  • I try my best but i do `var sumVar = 123` and `console.log(sumVar);` return 123 and `console.log(window[sumVar]);` return undefined – GoDLighT Nov 04 '13 at 15:12
  • Please check the code I just posted, with changes to your original script. I put `window.` before the 2 variable declarations, and then reference them later using `window[...]`. Other than that I've not changed anything. – Reinstate Monica Cellio Nov 04 '13 at 15:13
  • @GoDLighT This is the expected behaviour since `window[sumVar]` is the same as `window[123]`, and there is no variable named "123". To get the value of the variable "sumVar" you have to do that : `window['sumVar']`. –  Nov 04 '13 at 15:14
  • In that example you just posted, `window[sumVar]` will look for a property of the `window` object called "123", as that is the value of `sumVar`. You should have done `window["sumVar"]` as you're trying to reference a variable by name. – Reinstate Monica Cellio Nov 04 '13 at 15:15
  • k got it i wil try it – GoDLighT Nov 04 '13 at 15:17
  • i lost the jQuery object console say: `Uncaught TypeError: Object # has no method 'val' ` – GoDLighT Nov 04 '13 at 15:24
  • in `(window[type + 'Name']).val(inputValue);` it return the corrent input elemet but not jQuery object – GoDLighT Nov 04 '13 at 15:35
  • Both `somethingName` and `blablaName` are jQuery objects, so it must not be referencing one of them, or you're not doing it as in the script above. Open the console and type `window["somethingName"]` and then `window["blablaName"]` and see what is returned for each – Reinstate Monica Cellio Nov 04 '13 at 15:37
  • When I give up on the `var` in `var sumVar = $('sumId')` it return the object but with the `var` it return only html element – GoDLighT Nov 04 '13 at 15:39
  • Can you do what I asked in the previous comment, to debug the issue you've got with the script? – Reinstate Monica Cellio Nov 04 '13 at 15:41
  • my script is diffrent from the exmple so i try to do 3 new lines to try your solution, 1 `var sumVar = $('input')` 2 `console.log(window['sumvar'])` 3 `console.log(sumvar)` and i put it next to where it shuld be in the code within functions so when i use `var` the varible is not global and he save only the corrent element but not the jQuery object – GoDLighT Nov 04 '13 at 15:49
  • Use `window.sumVar = $("input");` and then refer to is as `(window["sumVar"])` - be careful of case. Your comment above shows different cases for the examples – Reinstate Monica Cellio Nov 04 '13 at 15:52
  • No problem - glad we got there in the end :) – Reinstate Monica Cellio Nov 04 '13 at 16:02
0

You can create a function and use it's returned value:

DEMO1       DEMO2

function type(){
  return (blabla == blublu) ? 'category' : 'regular';
}


$('[name="'+ type() +'Name"]').val('SOME VALUE'); 

If you use ID rather than name attribute:

function type(){
  return (blabla == blublu) ? '#category' : '#regular';
}


$( type() +'Name').val('SOME VALUE'); 

Or just simply:

var typeID =  blabla==blublu? '#category' : '#regular';
$( typeID +'Name').val('SOME VALUE'); 
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

val() is a method provided by jquery. So to access it you will need to use the '$' operator along with the mode of selection :

var type = (blabla == blublu)? 'category':'regular';

For accessing using ID :

$("#"+type).val("...");

For accessing using Class :

$("."+type).val("...");

For accessing using any custom attribute for eg. data :

$("data['"+type+"']").val("...");
Chimba
  • 132
  • 1
  • 7
-2

You only can safely do that with an object key.

Create an object like so.

var obj = {
   'categoryName': ...

};

To retrieve it use something like this:

obj[someString]

eval is an option is not wise.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Do what? I'm sorry but your answer is as muddled as the question :/ –  Nov 04 '13 at 14:54