Как получить идентификатор тега ввода формы HTML?

0
<?php
        $i = 1;
        $query1 = mysql_query("SELECT * FROM 'alert_history' ORDER BY 'alert_history'.'id' DESC LIMIT ".$start.",".$per_page."");
        while($result = mysql_fetch_array($query1)){
            echo '<td colspan = "2"><form method = "POST" onsubmit = "submitform()" ><textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" id = "comment'.$i.'" name = "comment"></textarea> <br />';
            echo '<input type = "text" id = "alertid'.$i.'" name = "alertid" value = "'.$result['id'].'">';
            echo '<input  type = "submit" name = "submit" value = "Comment" ></form></td>';
            $i++;
        }
?>


<script>
    function submitform(){
            var comment = $("#comment").val();
        var alertid = $("#alertid").val();
        alert(comment);
        $.ajax({
        type: "POST",
            url: "analytic.php",
            data:{cmt:comment,alert_id:alertid}
        });
            //return false;
      }
</script>

Как получить тег textarea и идентификатор input тега для функции javascript?
Оба тега показывают в цикле while, поэтому я хочу, чтобы каждый textarea и тег input имели разные идентификаторы.

  • 0
    Вы должны прочитать этот вопрос
  • 0
    Обратите внимание, что вопрос, который упоминает @AncientGeek, касается изменения mysql на MYSQLI или PDO.

4 ответа

1

Если вы генерируете динамический идентификатор в текстовом поле, то время, если что-то измените в текстовом поле, чтобы сохранить его идентификатор в локальной переменной и использовать его в своем коде

<input type = "text" class="textBox" id = "alertid'.$i.'" name = "alertid" value = "'.$result['id'].'">';
var Id
  $(document).on('change', "input.textBox", function () {
             Id = $(this).attr("id");
alert(Id )
});

Надеюсь, этот код поможет вам.

0

Попробуй это:

(См. Рабочую демонстрацию JsFiddle)

<?php
        $i = 1;
        $query1 = mysql_query("SELECT * FROM 'alert_history' ORDER BY 'alert_history'.'id' DESC LIMIT ".$start.",".$per_page."");
        while($result = mysql_fetch_array($query1)){
            echo '<td colspan = "2"><form method = "POST" onsubmit = "submitform(this)" ><textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" id = "comment'.$i.'" name = "comment"></textarea> <br />';
            echo '<input type = "text" id = "alertid'.$i.'" name = "alertid" value = "'.$result['id'].'">';
            echo '<input  type = "submit" name = "submit" value = "Comment" ></form></td>';
            $i++;
        }
?>


<script>
    function submitform(form){

      var comment = $(form).find("textarea").val();
      alert(comment);

      var alertid = $(form).find("input[name=alertid]").attr("id");
      alert(alertid);
      //Or if you mean:
      var alertid = $(form).find("input[name=alertid]").val();
      alert(alertid);

        $.ajax({
        type: "POST",
            url: "analytic.php",
            data:{cmt:comment,alert_id:alertid}
        });
            //return false;
      }
</script>
0

поэтому сначала вы устанавливаете разные идентификаторы, а затем извлекаете их.

var textAreaId = $('textarea').prop('id);
var inputId = $('input').prop('id);

Обновить

$ i постоянна для каждого отдельного набора текстовых полей и ввода вместе.

Если вы хотите захватить каждый набор текстовых полей и ввода, вы должны скорее назначить идентификатор, а не делать это для каждого элемента textarea и input.

<?php
        $i = 1;
        $query1 = mysql_query("SELECT * FROM 'alert_history' ORDER BY 'alert_history'.'id' DESC LIMIT ".$start.",".$per_page."");
        while($result = mysql_fetch_array($query1)){
            echo '<td colspan ="2" id='.$i.'"><form method = "POST" onsubmit = "submitform()" ><textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" name = "comment"></textarea> <br />';
            echo '<input type = "text" name = "alertid" value = "'.$result['id'].'">';
            echo '<input  type = "submit" name = "submit" value = "Comment" ></form></td>';
            $i++;
        }
?>



<script>
    function submitform(){
            var comment = $(this).closest('td').find('textarea').val();
            var alertid = $(this).parent().prop('id');
        alert(comment);
        $.ajax({
        type: "POST",
            url: "analytic.php",
            data:{cmt:comment,alert_id:alertid}
        });
            //return false;
      }
</script>
  • 0
    Сэр, каждое поле имеет разные id .. id = "comment". $ I. '"
  • 0
    @ Томас ответ обновлен, пожалуйста, проверьте.
0

В jQuery выберите тег и используйте .each():

$("textarea").each(function(){
   alert($(this).attr("id"));
   alert($(this).val());
});
$("input").each(function(){
   alert($(this).attr("id"));
   alert($(this).val());
});

Демо здесь (клиентская сторона).

Ещё вопросы

Сообщество Overcoder
Наверх
Меню