Click here to Skip to main content
15,396,239 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have created the code using the this keyword. It works fine, if you click on the object(span) it will show the relevant data in the edit box. However, the whole span is clickable and I only want to make the edit button clickable and accomplish the same task. How can I do this? I have tried binding the HTML label to the span using the for attribute, but this did not work. If you copy the code and run in your browser, you will see that it works when you click anywhere on the span container. Is it possible to transfer this functionality to a button or label?

What I have tried:

<pre><?php include 'header.php'; ?>

<!DOCTYPE html>
<html lang="en">

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<div id='form'></div>
<div id="output"></div>

var post, showPost, title, content, output, i;

function showPost() {
showPost = '[{"title": "Hello World", "content": "What a beautiful day"}, {"title":"How are you", "content":"The beauty oflife"}, {"title":"The big bang", "content":"Wowww!!!!!"}, {"title":"Welcome", "content":"To my world"}]';
post = JSON.parse(showPost);
output = '';
for (i = 0; i < post.length; i++) {
title = post[i].title + "<br>";
content = post[i].content + "<br>";

output += "<div id='contents' style='border:1px solid #333;margin:10px;padding:10px' >";
output += "<label for='send'>" + "edit" + "</label>";
output += "<span id='send' onclick='showData(this)'>";
output += "<h1 id='h1-heading'>" + title + "</h1>";
output += "<p id='post-par'>" + content + "</p>";
output += "</span>";
output += "</div>";

document.getElementById('output').innerHTML = output;
console.log(title + "<br>" + content);



function showData(val) {
var contents = document.getElementById('contents').value = val.innerHTML;
document.getElementById('form').innerHTML = contents;
Updated 25-Jun-22 18:37pm

1 solution

First, there's no such thing as "looping out a ... button". That makes no sense at all.

Reading the rest of your question, it's not entirely clear what you're doing and where. But, if you're only getting an "output" of a single item, it could be because you keep replacing the innerHTML of an item instead of adding the new content to the old:
// The following line replaces the content of the 'output' element, not add to it.
document.getElementById('output').innerHTML = output;

If you want to add the content, you have to, well, add.
//         Do a little addition here -------v
document.getElementById('output').innerHTML += output;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900