2016-09-07 3 views
1

Я пытаюсь захватить значения ячейки из таблицы HTML, сгенерированной из другого кода PHP. Чтобы я мог использовать результат для отправки рандеву у конечного пользователя.Захват значений ячейки из таблицы с помощью JQuery?

Мой текущий JSFiddle может захватить некоторые значения, но не так, как я хочу. Мне нужно восстановить атрибут title & value от кнопки в TD, моя проблема в настоящее время является кодом возврата данных с утра и перейти к следующему утру.

Как я могу вернуть весь день value & title данные для каждого доступного дня в таблице?

Код:

$(document).ready(function(){  

    eachCell(); 

    function eachCell(){ 
    var cellInnerText = []; 
    var cellValue = []; 
    var out = document.getElementById("out"); 
    var out2 = document.getElementById("out2"); 
    $('#ft_agenda tbody tr').each(function(index) {   
     // console.log("index ", index, " this: " , this, "this.attr(rel)", $(this).attr('rel'), "$(this).text()", $(this).text()); 
     console.log($(":first-child", $(this))[0]); 
     cellInnerText.push($("td button", $(this)).attr('value')); 
     cellValue.push($("td button", $(this)).attr('title')); 
    }); 
    out.innerHTML = cellInnerText.join(" | "); 
    out2.innerHTML = cellValue.join(" | ");  
} 

}); 
+0

Почему ты меченый это с PHP? – jeroen

+0

Почему бы вам не изменить свой jquery на просто кнопки поиска '$ ('# ft_agenda tbody tr td button'). Each (function (index) {', а затем вы можете получить значение и заголовок с помощью 'console.log ($ (this) .attr ('value') + '' + $ (this) .attr ('title')); ' – depperm

ответ

1
// Try this code on your jsfiddle 
// https://jsfiddle.net/g60ogt8c/1/ 
$(function() { 

    function findColumnByDate(date) { 
    var col; 
    $('#ft_agenda thead th').each(function(idx) { 
     if ($(this).text().trim() == date.trim()) col = idx; 
    }); 
    return col; 
    } 

    function showAvailableTimes(date) { 
    var times = [], 
     column = findColumnByDate(date); 
    if (column) { 
     var $rows = $('#ft_agenda tbody td:nth-of-type('+column+')'); 
     if ($rows.length) { 
     times[0] = ''; 
     $rows.find('button').each(function() { 
      times[times.length] = $(this).attr('value')+' - '+$(this).attr('title'); 
     }); 
     times[0] = 'For date '+date+' found '+(times.length-1)+' free terms'; 
     } else { 
     times[0] = ['No free terms for date: '+date]; 
     } 
    } else { 
     times[0] = ['Invalid date '+date+' or date not found']; 
    } 
    return times; 
    } 

    // Function showAvailableTimes() now returns array. 
    // In index 0 is status message and if available times found, 
    // these lies on indexes 1 and more. 

    // Use it this way: 
    $('#out').html(''); 
    showAvailableTimes('15-09-2016').forEach(function(item) { 
    $('#out').append(item + '<br>'); 
    }); 

    // Or this way: 
    // Jsonify returned array and send it toSome.php. 
    var json = JSON.stringify(showAvailableTimes('09-09-2016')); 
    $.post('toSome.php', {times: json}); 

    // Or if there are free terms, filter status message 
    // and send just free terms - without status message. 
    var times = showAvailableTimes('09-09-2016'); 
    if (times.length > 1) { 
    var json = JSON.stringify(times.filter(function(itm,idx){return idx>0})); 
    $.post('toSome.php', {times: json}); 
    // Here you can see that status message was skipped 
    $('#out2').text(json); 
    } 

}); 
+0

Perfect WaldemarIce !! Я постараюсь адаптировать его для моей потребности. Я имею в виду, что клиенты дают мне их доступность (например: 15-09-2016), тогда мне нужно проверить, совпадает ли в таблице совпадение даты и, наконец, вернуть 'значение' +' title' Спасибо за помощь – Peacefull

+0

Возможно, если у вас есть время или надоело, вы можете обновить свой ответ:) – Peacefull

+0

Спасибо, чувак, просто проверьте мой первый ответ :) – Peacefull

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