2014-10-28 4 views
0

Как создать динамическое имя переменной на основе всех имен ввода флажков форм? Это то, что я до сих поримя динамической переменной из имени ввода формы

var nameArray = []; 
$.each($("#store-filter input").serializeArray(), function(i, field) { 
    nameArray[field.name] = field.value; 
}); 

alert(nameArray[0]); 

for (i = 0; nameArray.length > i; i++) 
{ 
    //alert(nameArray[i]); 
    var nameArray[i] = nameArray[i].value; 
    var nameArray[i]+'_checked_values' = $(\'input[name="nameArray[i]+[]"]:checked\').map(function() { 
     return this.value; 
    }).get(); 

} 
alert(make); //variable name from name="make[]" 

образец HTML

<form id="store-filter" action:"javascript:void(0);"> 
      <span id="store"> 
       <input id="store_0" value="2" name="store[]" type="checkbox">&nbsp;<label for="store_0">Store 1</label> 
       <input id="store_1" value="3" name="store[]" type="checkbox">&nbsp;<label for="store_1">Store 2</label> 
       <input id="store_2" value="3" name="store[]" type="checkbox">&nbsp;<label for="store_2">Store 3</label> 
      </span> 
      <span id="make"> 
       <input id="make_0" value="2" name="make[]" type="checkbox">&nbsp;<label for="make_0">make 
     1</label> 
       <input id="make_1" value="3" name="make[]" type="checkbox">&nbsp;<label for="make_1">make 
     2</label> 
    <input id="make_2" value="4" name="make[]" type="checkbox">&nbsp;<label for="make_2">make 
     3</label> 

      </span> 
      <span id="time"> 
       <input id="time_0" value="2" name="time[]" type="checkbox">&nbsp;<label for="time_0">time 1</label> 
       <input id="time_1" value="3" name="time[]" type="checkbox">&nbsp;<label for="time_1">time 2</label> 
    <input id="time_2" value="4" name="time[]" type="checkbox">&nbsp;<label for="time_2">time 3</label> 
      </span> 
</form> 

так далее в моем коде я могу создать строку URL-адрес ?make=1,2,3&store=40,5,6&time=1,2,3,4 и т.д.

параметры $ _GET взяты из входного флажки имя динамически

+3

Можете ли вы объяснить вашу проблему немного больше, поскольку это не ясно, что вы пытаетесь сделать. В первом случае кажется, что вам нужен объект, а не массив, поэтому вы можете связать значения с ключами. Однако я не вижу значимости этого во втором фрагменте кода, где вы создаете массив выбранного значения с помощью 'map' ...? –

+1

Что означает «я хочу сделать и сделать [] динамически»? – undefined

+0

@RoryMcCrossan извините за то, обновленный вопрос. и добавил еще мой код – user2636556

ответ

1

Я хотел бы предложить следующий подход, очевидно, я привязка к нажатию одной кнопки, вы должны добавить, что события/взаимодействия по вашему выбору:

function makeQueryString() { 
 
    function keyValues(idPref) { 
 
    // using the pass-in 'id' as a key: 
 
    var key = idPref, 
 
    // searching within the element identified with that 'id' for 
 
    // other elements whose 'id' *starts* with that string: 
 
     values = $('#' + idPref + ' input[id^="' + idPref + '"]').map(function() { 
 
     // iterating over those found elements and, if the value is *not* the 
 
     // defaultValue (value on page-load), *or* the checked state is not the 
 
     // default state (checked/unchecked as on page-load): 
 
     if (this.value !== this.defaultValue || this.checked !== this.defaultChecked) { 
 
      // we return the value: 
 
      return this.value; 
 
     } 
 
     // get() converts to a JavaScript Array, join() concatenates Array elements 
 
     // to form a string: 
 
     }).get().join(','); 
 

 
    // if there is a key, and there are associated values, we return a 'key=value,value2' 
 
    // string, otherwise we return an empty string: 
 
    return key && values.length ? key + '=' + values : ''; 
 
    } 
 

 
    // we return the value obtained after iterating over the form's span elements 
 
    // that have an [id] attribute: 
 
    return $('form span[id]').map(function(){ 
 
    // obtaining the 'key=value1,value2' strings from the called-function: 
 
    return keyValues(this.id); 
 
    // converting those returned elements into an Array, and joining with & characters: 
 
    }).get().join('&'); 
 
} 
 

 
$('#test').click(function(e) { 
 
    e.preventDefault(); 
 
    console.log(makeQueryString()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="test">test</button> 
 
<form id="store-filter" action: "javascript:void(0);"> 
 
    <span id="store"> 
 
       <input id="store_0" value="2" name="store[]" type="checkbox">&nbsp;<label for="store_0">Store 1</label> 
 
       <input id="store_1" value="3" name="store[]" type="checkbox">&nbsp;<label for="store_1">Store 2</label> 
 
       <input id="store_2" value="3" name="store[]" type="checkbox">&nbsp;<label for="store_2">Store 3</label> 
 
      </span> 
 
    <span id="make"> 
 
       <input id="make_0" value="2" name="make[]" type="checkbox">&nbsp;<label for="make_0">make 
 
     1</label> 
 
       <input id="make_1" value="3" name="make[]" type="checkbox">&nbsp;<label for="make_1">make 
 
     2</label> 
 
    <input id="make_2" value="4" name="make[]" type="checkbox">&nbsp;<label for="make_2">make 
 
     3</label> 
 

 
      </span> 
 
    <span id="time"> 
 
       <input id="time_0" value="2" name="time[]" type="checkbox">&nbsp;<label for="time_0">time 1</label> 
 
       <input id="time_1" value="3" name="time[]" type="checkbox">&nbsp;<label for="time_1">time 2</label> 
 
    <input id="time_2" value="4" name="time[]" type="checkbox">&nbsp;<label for="time_2">time 3</label> 
 
      </span> 
 
</form>

Ссылки:

+0

Удивительный, спасибо за подробное объяснение. если хранилище и время не проверены, url выглядит так: make = 5,37 &&&& 'Я мог бы удалить завершающий' &&&& 'после того, как будет создан URL, но ради обучения. как бы я сделал в вашем коде? – user2636556

0

Вы находитесь в Javascript, вам не нужно объявлять размер ваших массивов, нет никаких проблем, добавив/удалив что-либо из Объект/массив.

Вы должны создать переменную make, а затем получить значения. Наконец, вы сможете вернуть ее.

var make; 
$.each($("#store-filter input").serializeArray(), function(i, field) { 
    make[i] = field.name; 
}); 

Позже в вашем коде вы будете использовать массив make.

make[0]; 

EDIT:

Вот пример я сделал для вас: http://jsfiddle.net/kjkzm8qm/

ПРИМЕЧАНИЕ. Ваш $ .each ($ ("# магазин-фильтр вход") serializeArray () ... бесполезно, вы должны выбрать все свои входы, добавив класс И, вы должны ЗАКЛЮЧИТЬ свои теги ввода, добавив/в конец.

HTML

<input name="test" class="inputs" /> 

JAVASCRIPT

$.each($(".inputs"), function(){ }); 
+0

обновил вопрос и добавил еще мой код. получение 'undefined error' – user2636556

+0

Почему вы используете * alert (make) *, когда ваша переменная * nameArray *? : o Вы должны попробовать ** console. (nameArray) **, затем откройте консоль в Firefox/Chrome –

+0

. Я предположил, что поскольку имя ввода является 'make', имя создаваемой динамической переменной также будет' make': P – user2636556

Смежные вопросы