Object htmlparagraphelement js как исправить

Есть выбор типа доставки в с обработкой JS; выводится выбранный тип вот таким образом: , но почему то, когда ещё не сделал...

Есть выбор типа доставки в <input type="radio"> с обработкой JS; выводится выбранный тип вот таким образом: <output id="product-price"></output>, но почему то, когда ещё не сделал выбор, щёлкнув на какую-нибудь пустую строчку формы заказа, на месте этого вывода появляется это сообщение [object HTMLParagraphElement].

Что это такое и как с этим бороться?

Вот фрагменты кода JS:

window.onload = function(){ totalPrice = "<?=$_SESSION['total_price']?>"; }

window.onclick = function onclickRadio() {
  var nameRadio = document.getElementsByName('nameRadio');
  for (var i = 0; i < nameRadio.length; i++) {
    if (nameRadio[i].type === 'radio' && nameRadio[i].checked) {
        rezultatRadio = nameRadio[i].value;       

    }
  }
  document.getElementById('rezultatRadio').innerHTML =  rezultatRadio;
  document.getElementById('product-price').innerHTML =  new Number (+rezultatRadio) + new Number (+totalPrice);
}

<input type="radio" name="nameRadio" value="300" > Наш курьер (Стоимость доставки 300 руб)
    <input type="radio" name="nameRadio" value="0">Самовывоз

Вот html вывод, где появляется это предупреждение:

<td align="center"><p id="rezultatRadio"></p> руб </td>

Если выводить через , то появляется такое предупреждение: [object HTMLOutputElement]

Пробую теперь вот такой код, вообще ничего не выполняется….:

function(){ totalPrice = "<?=$_SESSION['total_price']?>"; }

function showResult() {
  var nameRadio = document.getElementsByName('nameRadio');
  for (var i = 0; i < nameRadio.length; i++) {
    if (nameRadio[i].type === 'radio' && nameRadio[i].checked) {
        rezultatRadio = nameRadio[i].getAttribute('data');       

    }
  }
  document.getElementById('rezultatRadio').innerHTML =  rezultatRadio;
  document.getElementById('product-price').innerHTML =  new Number (+rezultatRadio) + new Number (+totalPrice);

}

showResult();
window.onclick = showResult;

<input type="radio" name="nameRadio" data='300' value="300" checked="checked"> Наш курьер (Стоимость доставки 300 руб)
    <input type="radio" name="nameRadio" data='0' value="0">Самовывоз

Столкнулся с проблемой вывода вместо элемента массива строки ‘[object HTMLParagraphElement]’. В консоли выводит то, что должно — 3 html элемента, а при попытке вывода этих элементов на экран с помощью innerHTML выводит строку ‘[object HTMLParagraphElement]’.
Вот код js:

document.addEventListener('DOMContentLoaded', function() {
    //функция, перебирающая элементы
    let technologyHandler = (str) => {
        let techArr = str.split(' ');
        let techArrElem = techArr.map((el) => {
            let docElem = document.createElement('p');
            docElem.classList.add('project_technologies-item');
            docElem.innerHTML = el;
            return docElem;
        });
        return techArrElem;
    }
    let modal = document.getElementById('works-description'),
        closeModal = document.getElementById('close'),
        openElement = document.getElementsByClassName('openingFigure'),
        headline = document.getElementById('headline'),
        taskDescription = document.getElementById('task_description'),
        deadlinesDescription = document.getElementById('deadlines_description'),
        projectTechnologies = document.getElementById('project_technologies'),
        modalImg = document.getElementById('modal-img'),
        modalHref = document.getElementById('modal-href');
    for (let i = 0; i < openElement.length; i++) {
        openElement[i].addEventListener('click', function (e) {
            let handler = e.currentTarget;
            let modalTitle = handler.getAttribute('data-headline'),
                task = handler.getAttribute('data-task'),
                deadline = handler.getAttribute('data-deadline'),
                dataTechnologies = handler.getAttribute('data-technologies'),
                dataImg = handler.getAttribute('data-img'),
                dataHref = handler.getAttribute('data-href');

            modalImg.src = dataImg;
            headline.innerHTML = modalTitle;
            taskDescription.innerHTML = task;
            deadlinesDescription.innerHTML = deadline;
            projectTechnologies.innerHTML = technologyHandler(dataTechnologies).map((el) => el); //вывод элементов на экран
            modalHref.href = dataHref;
            modal.style.display = 'flex';
        });
    }
    closeModal.addEventListener('click', function() {
        modal.classList.remove('fade');
        modal.classList.add('fade-out');
        modal.addEventListener('transitionend', function () {
            modal.style.display = 'none';
            modal.classList.remove('fade-out');
            modal.classList.add('fade');
        });
    });
});

Вот html:

<div id="works-description" class="fade">
                <div class="works-description-block">
                    <a id="close">✖</a>
                    <div class="img-block">
                        <img src="img/" id="modal-img" alt="image">
                    </div>
                    <div class="works-description-text">
                        <h2 id="headline">Site name</h2>
                        <h3>Задача</h3>
                        <p id="task_description"></p>
                        <h3>Сроки</h3>
                        <p id="deadlines_description"></p>
                        <div id="project_technologies"></div> //сюда вывожу элементы
                        <a id="modal-href" href="https://obogrevatel-ua.com/" target="_blank">Перейти на сайт</a>
                    </div>
                </div>
            </div>

           <figure data-img="img/digitalCrafters-bg.png" data-headline="DigitalCrafters" data-task="Верстка посадочной страницы по PSD макету" data-deadline="3 дня"             data-technologies="css html js" <-- элементы              data-href="http://siteportfolio.h1n.ru/DigitalCrafters/" class="openingFigure wow fadeInUp digitalCrafters-figure">
                    <figcaption>
                        <h2>Digital Crafters</h2>
                        <p>Верстка</p>
                    </figcaption>
                </figure>

Есть выбор типа доставки в <input type="radio"> с обработкой JS; выводится выбранный тип вот таким образом: <output id="product-price"></output>, но почему то, когда ещё не сделал выбор, щёлкнув на какую-нибудь пустую строчку формы заказа, на месте этого вывода появляется это сообщение [object HTMLParagraphElement].

Что это такое и как с этим бороться?

Вот фрагменты кода JS:

window.onload = function(){ totalPrice = "<?=$_SESSION['total_price']?>"; }

window.onclick = function onclickRadio() {
  var nameRadio = document.getElementsByName('nameRadio');
  for (var i = 0; i < nameRadio.length; i++) {
    if (nameRadio[i].type === 'radio' && nameRadio[i].checked) {
        rezultatRadio = nameRadio[i].value;       

    }
  }
  document.getElementById('rezultatRadio').innerHTML =  rezultatRadio;
  document.getElementById('product-price').innerHTML =  new Number (+rezultatRadio) + new Number (+totalPrice);
}

<input type="radio" name="nameRadio" value="300" > Наш курьер (Стоимость доставки 300 руб)
    <input type="radio" name="nameRadio" value="0">Самовывоз

Вот html вывод, где появляется это предупреждение:

<td align="center"><p id="rezultatRadio"></p> руб </td>

Если выводить через , то появляется такое предупреждение: [object HTMLOutputElement]

Пробую теперь вот такой код, вообще ничего не выполняется….:

function(){ totalPrice = "<?=$_SESSION['total_price']?>"; }

function showResult() {
  var nameRadio = document.getElementsByName('nameRadio');
  for (var i = 0; i < nameRadio.length; i++) {
    if (nameRadio[i].type === 'radio' && nameRadio[i].checked) {
        rezultatRadio = nameRadio[i].getAttribute('data');       

    }
  }
  document.getElementById('rezultatRadio').innerHTML =  rezultatRadio;
  document.getElementById('product-price').innerHTML =  new Number (+rezultatRadio) + new Number (+totalPrice);

}

showResult();
window.onclick = showResult;

<input type="radio" name="nameRadio" data='300' value="300" checked="checked"> Наш курьер (Стоимость доставки 300 руб)
    <input type="radio" name="nameRadio" data='0' value="0">Самовывоз

I am having difficulties working with variables in jQuery.
The var would need to return the width of the window.
To test this I wrote some code where the width is displayed in a paragraph when I hit a button:

var update = function() {
  width = $(window).width();
}

$(document).ready(
  function() {
    $('button').click(
      function() {
        update,
        $('#width').text(width)
      }
    )
  }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>

I get «[object HTMLParagraphElement]» instead of the value of the width.
I don’t understand why, because when I run this code:

var width = $(window).width();

$(document).ready(
    function () {
        $('button').click(
            function () {
                $('#width').text(width)
            }
        )
    }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>

I do get the value without any problems. But in this way I can’t update the variable after resizing the window (I think because the variable is only declared at the loading of the page.)

This probably is a real newbe problem, but I am very eager to learn…

asked May 31, 2015 at 12:42

Biest's user avatar

‘Named’ elements with ids are added as properties of document.
This is why when you were calling width before, it should have been undefined had you not had this element

<p id="width">Width</p>

Since you had this element, width defaulted to [object HTMLParagraphElement]

See Do DOM tree elements with ids become global variables?

Also, you need to call update with a ()

var update = function() {
  return $(window).width();
}

$(document).ready(
  function() {
    $('button').click(
      function() {
        var width = update();
        $('#width').text(width)
      }
    )
  }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>

Note, the above returns a value rather than use/assign a global variable width. This is better practice to avoid anti-patterns.

Community's user avatar

answered May 31, 2015 at 12:43

AmmarCSE's user avatar

AmmarCSEAmmarCSE

29.7k5 gold badges41 silver badges53 bronze badges

1

I am having difficulties working with variables in jQuery.
The var would need to return the width of the window.
To test this I wrote some code where the width is displayed in a paragraph when I hit a button:

var update = function() {
  width = $(window).width();
}

$(document).ready(
  function() {
    $('button').click(
      function() {
        update,
        $('#width').text(width)
      }
    )
  }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>

I get «[object HTMLParagraphElement]» instead of the value of the width.
I don’t understand why, because when I run this code:

var width = $(window).width();

$(document).ready(
    function () {
        $('button').click(
            function () {
                $('#width').text(width)
            }
        )
    }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>

I do get the value without any problems. But in this way I can’t update the variable after resizing the window (I think because the variable is only declared at the loading of the page.)

This probably is a real newbe problem, but I am very eager to learn…

asked May 31, 2015 at 12:42

Biest's user avatar

‘Named’ elements with ids are added as properties of document.
This is why when you were calling width before, it should have been undefined had you not had this element

<p id="width">Width</p>

Since you had this element, width defaulted to [object HTMLParagraphElement]

See Do DOM tree elements with ids become global variables?

Also, you need to call update with a ()

var update = function() {
  return $(window).width();
}

$(document).ready(
  function() {
    $('button').click(
      function() {
        var width = update();
        $('#width').text(width)
      }
    )
  }
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>

Note, the above returns a value rather than use/assign a global variable width. This is better practice to avoid anti-patterns.

Community's user avatar

answered May 31, 2015 at 12:43

AmmarCSE's user avatar

AmmarCSEAmmarCSE

29.7k5 gold badges41 silver badges53 bronze badges

1

I am a newbie. Here is my code:

<html>
  <head>
    <script type="text/javascript">
      function replyOne () {
        document.getElementById("comment_content").value = document.getElementById("username")
      }
    </script>
  </head>
  <body>
    <p id="username">Jack</p>
    <textarea id="comment_content" ></textarea>
    <button onclick="replyOne()">Copy Text</button>
  </body>
</html>

I expect that when I click the button, it will copy ‘Jack’ to the textarea.
But instead it just writes ‘[object HTMLParagraphElement]’.

1) Solution

It should be:

document.getElementById("comment_content").value =
    document.getElementById("username").innerHTML

Without the .innerHTML, it will try to copy in the actual element, not its content.

2) Solution

You can use textContent,innertext,innerHTML.But two of them are browser specific and innerHTML can work on three major browser.

Also you can parse the dom by parent children combination and will get required value.

 function replyOne () {
    document.getElementById("comment_content").value=document.getElementById("username").innerHTML;

    //OR 
    document.getElementById("comment_content").value=document.getElementById("username").textContent;

    }
3) Solution

You need to extract what you are looking for using the obj.innerText attribute and you will solve the problem-:

var t= document.getElementById("comment_content");
var text=t.innerText;
alert(t);
4) Solution

This is solution of [objectHTMLParagraphElement] with example

var sel = document.getElementById('ex').innerHTML; // without innerHTML this will 
comes [objectHTMLParagraphElement]
var txt = sel + "Hello";    
document.write(txt); // output Hello

Comments Section

Got it. Thank you so much. :)

@hsming: don’t forget to tick (accept) answers that worked for you.

You were only 61 when that answer was already given tho :). And also the reason why it should be avoided (does not work on all browsers).

Related Topics
javascript

Mentions
Tckmn
Zahra Zamani
Owen Versteeg
Hsming
Ruju
Rana Saha
Renato Cappellani
Sachith Muhandiram

References
stackoverflow.com/questions/16147488/why-did-i-get-object-htmlparagraphelement

154 votes

1 answers

Get the solution ↓↓↓

i have a function that shows me if a file exists, if so he will return me the file path if it doesnt exist he will still give me the path so he can create the file:

function getnamechats($user1,$user2){
   
    $filename1="chats/chat".$user1."&".$user2.".json";
         $filename2="chats/chat".$user2."&".$user1.".json";
    if (file_exists($filename1)) {
        return $filename1;
    }
    else if (file_exists($filename2)) {
        return $filename2;
    }
    else{ return $filename1;}
}

it works fine on creating/opening the file to write on it,ive tested a lot of times and my json file gets updated everytime:

function send_chat($nick,$chat){
    global $userid;global $chatparse;
   $heasda=getnamechats($userid,$chatparse);
 $ok=$heasda;
    // read/write
    $filename = "$heasda";
    $fopen = fopen($filename,"r");
    $fgets = fgets($fopen);
    fclose($fopen);
    $decode = json_decode($fgets,true);
    // limit 10
    end($decode);
    if(key($decode) >= 10){
        array_shift($decode);
        $new_key =10;
    }
    else{
        $new_key = key($decode);
        $new_key++;}
    
    $format = array($nick,$chat);
    $decode[$new_key] = $format;
    $encode = json_encode($decode);
    // write
    $fopen_w = fopen($filename,"w");
    fwrite($fopen_w,$encode);
    fclose($fopen_w);
    
}

but in the function that opens/create it to read i get the following error the first variable is right(1) but the second one (suppost to be after the &) just doesnt work, and the error HTMLParagraphElement appears,example:

chats/chat1&[object HTMLParagraphElement].json

i then called again the getnamechats() function as soon as a new msg is triggered just to check if the file still exists, if it does, it will send me the variable $heasda to show_chat($heasda) and basically it will do the same as send_chat, but instead writing on it, it will read it:

function show_chat($heasda){
   print_r($heasda);
    $filename = $heasda;
    $fopen = fopen($filename,"r");
    $fgets = fgets($fopen);
    fclose($fopen);
    $decode = json_decode($fgets,true);
    $val .= "<table  id='table' class="table table-condensed">";
    foreach($decode as $post){
        
        $val .= "<tr><td><b style="color:#{$post[0]}">{$post[0]}</b>: {$post[1]}</td></tr>";}
    
    $val .= "</table>";
    return $val;
}

if(isset($_POST["chat"]) && $_POST["chat"] != ""){
    $nick = $_SESSION['iduser'];
    $chat = $_POST["chat"];
    send_chat($nick,$chat); 
}

if(isset($_GET["chat"]) && $_GET["chat"] != ""){
    global $userid;global $chatparse;
   $heasda=getnamechats($userid,$chatparse);
    echo show_chat($heasda);
    exit;
}

?>

As someone said it can be JavaScript heres the code too, ive read about it but i still dont understand properly:

function autoloadpage() {
        $.ajax({
            url: "?chat=1&chat-pars="+secnum,
            type: "POST",
            success: function(data) {
                $("div#chat").html(data);
            }
        });
    }

2021-11-10

Write your answer


63

votes

Answer

Solution:

secnum is a DOM element, not the text inside it. You need to get the text.

You should also callencodeURIComponent in case it contains characters that have special meaning in a URL.

function autoloadpage() {
    $.ajax({
        url: "?chat=1&chat-pars="+encodeURIComponent(secnum.innerText),
        type: "POST",
        success: function(data) {
            $("div#chat").html(data);
        }
    });
}


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-11-10

Link To Source

Link To Answer
People are also looking for solutions of the problem: the browser (or proxy) sent a request that this server could not understand.

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Object finereader ошибка цб
  • Object doesn t support this property or method error 438 vba
  • Objbase h 239 error c2760
  • Obd2 ошибка p0300
  • Nx license error invalid inconsistent license key or signature 8

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии