2013-04-28 2 views
1

Это не должно быть так сложно. Спасибо за любую помощь.Получить идентификатор выбора формы с помощью jquery

Я пытаюсь получить идентификатор (формы: eq #) родительской формы с помощью действия кнопки.

Итак, когда пользователь нажимает кнопку, мне нужно иметь возможность добавить селектор (эквалайзер) формы к действию кнопки.

Это является частью функции кнопки, и она работает:

$('form:eq('+formVal+') input[name='+fieldName+']').val(currentVal + 1); 

IF

formVal = число.

Это число должно быть идентификатором выбора формы. Вы используете, у меня есть несколько форм на моей странице, все используют один и тот же сценарий jquery, и я стараюсь, чтобы при нажатии кнопки в форме действие применимо только к одной форме, а не ко всем формам на странице.

Форма: eq0 запускает первую форму на странице. Форма: eq1 запускает вторую форму на странице и т. Д.

Мне нужно сделать эту динамику.

Я пробовал код в соответствии с: formVal = $ (this) .parent ('form'). Attr ('id');

... для получения formVal, который является числовым номером селектора (родительской) формы.

Как, черт возьми, я это делаю? Спасибо за любую помощь. Полный сценарий здесь:

jQuery(document).ready(function(){ 
    // This button will increment the value 
    $('.qtyplus').click(function(e){ 
     // Stop acting like a button 
     e.preventDefault(); 
     // Get the field name 
     fieldName = $(this).attr('field'); 
     // Get the form name 
     formVal=$(this).parents("form").find('id'); 
     // Get its current value 
     var currentVal = parseInt($('form:eq('+formVal+') input[name='+fieldName+']').val()); 
     // If is not undefined 
     if (!isNaN(currentVal)) { 
      // Increment 
      $('form:eq('+formVal+') input[name='+fieldName+']').val(currentVal + 1); 
     } else { 
      // Otherwise put a 0 there 
      $('form:eq('+formVal+') input[name='+fieldName+']').form.id.val(0); 
     } 
    }); 
    // This button will decrement the value till 0 
    $(".qtyminus").click(function(e) { 
     // Stop acting like a button 
     e.preventDefault(); 
     // Get the field name 
     fieldName = $(this).attr('field'); 
     // Get its current value 
     var currentVal = parseInt($('input[name='+fieldName+']').val()); 
     // If it isn't undefined or its greater than 0 
     if (!isNaN(currentVal) && currentVal > 0) { 
      // Decrement one 
      $('input[name='+fieldName+']').val(currentVal - 1); 
     } else { 
      // Otherwise put a 0 there 
      $('input[name='+fieldName+']').val(0); 
     } 
    }); 
}); 

ответ

0

Вы можете использовать closest найти форму кнопки находится, this.form также может работать также в зависимости от того, какого типа элемента это.

$('.qtyplus').click(function(e){ 
    // Stop acting like a button 
    e.preventDefault(); 
    // Get the field name 
    var fieldName = $(this).attr('field'); 
    // Get the form name 
    var $form=$(this).closest("form"); 
    //var $form=$(this.form); 
    // Get its current value 
    var currentVal = parseInt($form.find('input[name='+fieldName+']').val()); 
    // If is not undefined 
    if (!isNaN(currentVal)) { 
     // Increment 
     $form.find('input[name='+fieldName+']').val(currentVal + 1); 
    } else { 
     // Otherwise put a 0 there 
     $form.find('input[name='+fieldName+']').val(0); 
    } 
}); 
+0

Спасибо за ответ. Извините, я знаю, что мой вопрос был немного неудобным. Я пытаюсь получить эту переменную, которую я произвольно называл formVal. На кнопке формы есть действие. Как я могу получить доступ к идентификатору селектора родителя из этой кнопки? ...Спасибо за ответ. – user877

+0

@ user877 см. Обновление – Musa

+0

Большое спасибо. Ближе всего сделал трюк. – user877

0

Почему не сделать это так просто, как:

jQuery(document).ready(function(){ 
    // This button will increment the value 
    $('.qtyplus').click(function(e){ 
     // Stop acting like a button 
     e.preventDefault(); 
     // Get the field name 
     fieldName = $(this).attr('field'); 
     // Get the form name 
     var form=$(this).parents("form"); 

     var input = form.find("input[name='"+fieldName+"']'"); 
     // Get its current value 
     var currentVal = parseInt(input.val()); 
     // If is not undefined 
     if (!isNaN(currentVal)) { 
      // Increment 
      input.val(currentVal + 1); 
     } else { 
      // Otherwise put a 0 there 
      form.attr("id").val(0); 
     } 
    }); 
    // This button will decrement the value till 0 
    $(".qtyminus").click(function(e) { 
     // Stop acting like a button 
     e.preventDefault(); 
     // Get the field name 
     fieldName = $(this).attr('field'); 
     // Get its current value 
     var currentVal = parseInt($('input[name='+fieldName+']').val()); 
     // If it isn't undefined or its greater than 0 
     if (!isNaN(currentVal) && currentVal > 0) { 
      // Decrement one 
      $('input[name='+fieldName+']').val(currentVal - 1); 
     } else { 
      // Otherwise put a 0 there 
      $('input[name='+fieldName+']').val(0); 
     } 
    }); 
}); 

Как мы можем получить доступ к родительской формы, мы не должны получить к нему доступ только получить идентификатор и использовать этот идентификатор, чтобы искать снова форму.

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