0

I'm trying to set a dynamic variable name in each method using conditional statement. I tried to assign a variable like we do in php, but it doesn't work. How to do that?

Here's my code

var owners_index_val_ar = $("#owners_index").val().split(',');
$.each(owners_index_val_ar, function(index, value){
    $("#owner"+value+" :input").each(function(){
        if($(this).val() == ""){
            $(this).closest('.form-group').addClass("has-error");
            error = true;
        }
    });

    if(error == true){
        var error_code_own_"+value = true; // this doesn't work
    }
})
Kanav
  • 2,695
  • 8
  • 34
  • 56
  • 1
    I think you'll need to both show us the relevant HTML and show is what a representative `"#owners_index"` field would have in it for us to know what is and isn't right in your code. – jfriend00 Aug 04 '14 at 08:14
  • Try using `$("[id^='owner']").each(` or a common class. What is `owners_index_val_ar` and what does your html look like? – Joe Aug 04 '14 at 08:15
  • i would suggest creating an 'error' array and then assigning dynamic 'error keys' to it.. eg. `error_code[value]` – haxxxton Aug 04 '14 at 08:15
  • @jfriend00 it is an input field. its value can be `1` or `1,2` or `1,2,3` etc – Kanav Aug 04 '14 at 08:15
  • Then just create an array of error values. For dynamic lists of values, it's much better to use an array than to try to create a bunch of named variables dynamically. – jfriend00 Aug 04 '14 at 08:33
  • @jfriend00 can you give an example? – Kanav Aug 04 '14 at 08:35
  • The problem is that you have two `each` statements. Your `error` variable is created in the second one. So just set a default value to `false` right before the second `each` statement. – Arthur Aug 04 '14 at 08:42

0 Answers0