2016-05-24 2 views
0

Я установил несколько флажков с помощью цикла. Вот PHP код, который генерирует цикл:

<form class="small-box-footer" style="text-align:left;padding:10px;" method="post" name="nameHere"> 
    <?php 
    while ($row39 = mysql_fetch_array($result)) { 
     $Referrer_ID = $row39['Subject_ID']; 
     $Referrer_Name = $row39['Subject_Name']; 
    ?> 
     <input type="checkbox" class="subject-selected" name="subject" value="<?= $Referrer_ID ?>"> <?= $Referrer_Name ?><?= $Referrer_ID ?><br />   
    <?php 
    } 
    ?> 
</form> 

В следующем фрагменте кода является HTML, который получает генерируется из этого PHP кода и кода JavaScript, который создает ссылку, если флажок установлен; Вопрос заключается в том, что если условие не становится истинным:

\t $(".centre-selection").each(function() { 
 
\t \t $(this).attr("href", '?module=module_progress_report&Subject='+ $('.subject-selected').val()+ '&Centre_Selected_ID='+ encodeURIComponent($(this).attr('data-centre')) + '&Class_Selected_Year='+ encodeURIComponent($(this).attr('data-year')) + '&Class_Selected_All='+ encodeURIComponent($(this).attr('data-all-centre')) +'&StartDate='+$('#report_date_start').val()+'&EndDate=18/12/2016'); 
 

 
\t \t 
 
\t });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="checkbox" class="subject-selected" name="subject" value="2"> GCSE Maths2<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="3"> GCSE English3<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="4"> GCSE Science4<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="5"> GCSE Art5<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="6"> GCSE Sociology6<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="8"> OCR Nationals ICT8<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="9"> OCR Nationals Sports9<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="10"> OCR Nationals Business Studies10<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="11"> Entry Science11<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="12"> Functional Skills English12<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="13"> Functional Skills Maths13<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="14"> ESOL14<br /> 
 
<input type="checkbox" class="subject-selected" name="subject" value="15"> Preparation for Working Life15<br />

EDIT:

Я думаю, что вопрос не получает должного понимания. Ниже первый JavaScript я написал,

$(".centre-selection").each(function() { 
      //$(this).attr('href', '?module=<?=$_REQUEST['module']?>&Subject='+ $(this).attr('data-subject')+ '&Centre_Selected_ID='+ $(this).attr('data-centre')+ '&Class_Selected_Year='+ $(this).attr('data-year')+ '&Class_Selected_All='+ $(this).attr('data-all-centre')+ '&StartDate='+ $(this).attr('report_date_start')+ '&EndDate='+ $(this).attr('data-attendance-check-end')); 
      $(this).attr("href", '?module=module_progress_report&Subject='+ $('.subject-selected').val()+ '&Centre_Selected_ID='+ encodeURIComponent($(this).attr('data-centre')) + '&Class_Selected_Year='+ encodeURIComponent($(this).attr('data-year')) + '&Class_Selected_All='+ encodeURIComponent($(this).attr('data-all-centre')) +'&StartDate='+$('#report_date_start').val()+'&EndDate=18/12/2016'); 
      }); 

выше JavaScript работал, но значение предмета выбран всегда была «2», который является первым предметом. Мне просто нужно исправить эту ошибку. Благодарю.

+1

Формат сценария пожалуйста ... –

+0

Пожалуйста, используйте инструмент как codepen, это легко и помочь. –

+0

Может быть, вы хотите получить, какой флажок вы изменили. –

ответ

3

Попробуйте что-нибудь,

// loop only for checked checkboxes 
$('.subject-selected:checked').each(function(){ 
    a=$(this).next('a'); // get the next anchor element 
    a.length && a.attr("href", '?module=module_progress_report&Subject='+ this.value+ '&Centre_Selected_ID='+ encodeURIComponent(a.attr('data-centre')) + '&Class_Selected_Year='+ encodeURIComponent(a.attr('data-year')) + '&Class_Selected_All='+ encodeURIComponent(a.attr('data-all-centre')) +'&StartDate='+$('#report_date_start').val()+'&EndDate=18/12/2016'); 
}); 

Как, на @Fahad комментарий

// loop for all checkboxes 
$('.subject-selected').each(function(){ 
    a=$(this).next('a'); // get the next anchor element 
    if(this.checked){ 
     a.length && a.attr("href", '?module=module_progress_report&Subject='+ this.value+ '&Centre_Selected_ID='+ encodeURIComponent(a.attr('data-centre')) + '&Class_Selected_Year='+ encodeURIComponent(a.attr('data-year')) + '&Class_Selected_All='+ encodeURIComponent(a.attr('data-all-centre')) +'&StartDate='+$('#report_date_start').val()+'&EndDate=18/12/2016'); 
    } else { 
     // not checked code here 
    } 
}); 

Обновленный цикл анкер тега, причина получать только 2 каждый раз, потому что вы используете $('.subject-selected').val() и JQuery будет верните первый элемент флажка. Таким образом, вам нужно использовать индекс тега привязки, чтобы получить его эквивалентное значение флажка.

$(".centre-selection").each(function(index) { 
    $(this).attr("href", '?module=module_progress_report&Subject='+ 
     $('.subject-selected:eq('+index+')').val()+ ....); 
}); 
+0

Я не хочу зацикливаться только на отмеченные поля. Я хочу, чтобы каждый результат был ссылкой, но я хочу сначала проверить, что проверенное значение будет сохранено. –

+0

см. Мой обновленный ответ –

+0

Ссылки по-прежнему не создаются. –

2

Вы должны перебрать все subject-selected как это:

$('.subject-selected').each(function(){ 
    if ($(this).is(":checked")) { 
     $(this).attr("href", '?module=module_progress_report&Subject=' + $("input[type='checkbox']").val() + '&Centre_Selected_ID=' + encodeURIComponent($(this).attr('data-centre')) + '&Class_Selected_Year=' + encodeURIComponent($(this).attr('data-year')) + '&Class_Selected_All=' + encodeURIComponent($(this).attr('data-all-centre')) + '&StartDate=' + $('#report_date_start').val() + '&EndDate=18/12/2016'); 
    } 
}); 
+0

логически и синтаксически значения неопределены и неверны '$ (this) .attr ('data-year')', '$ (this) .attr ('data-all-center')' и '$ (" input [ TYPE = 'флажок'] "). Val()'. попробуйте исправить, если вы дадите какой-либо ответ SO. –

0

$(".subject-selected").change(function() { 
 
    if(this.checked) { 
 
     //Do stuff 
 
    } 
 
});

Попробуйте что-то вроде этого

0

Вам необходимо добавить слушателя событий для каждого " ввод "для захвата события (щелкните или cha nge или что-то еще).

Try:

$('.subject-selected').each(function(){ 
    $(this).on('click',function(e){ 
    if ($(this).is(':checked')){ 
    $(this).attr("href", '?module=module_progress_report&Subject=' + $("input[type='checkbox']").val() + '&Centre_Selected_ID=' + encodeURIComponent($(this).attr('data-centre')) + '&Class_Selected_Year=' + encodeURIComponent($(this).attr('data-year')) + '&Class_Selected_All=' + encodeURIComponent($(this).attr('data-all-centre')) + '&StartDate=' + $('#report_date_start').val() + '&EndDate=18/12/2016'); 
    } 
    }); 
}); 
Смежные вопросы