I have a php foreach loop that displays a span element with a name in it, and an associated input field for each item in the array being iterated through. There is an onclick so that the value is passed to the associated input field:
<span onclick="setAuthor(this)">name</span>

Here is the statement that generates the input field ($author is generated earlier in the script).

<

form id="myform">
<input class="authors" id="authorname" type="text" name="authorname" value="' . $author . '" />

Here is my function:

function setAuthor(element) {
var author = element.innerHTML;
window.alert(author);
document.forms["myform"].elements["author_name"].value = author;
}

Right now, when I click on each name, I get distinct names as I want for the loop, but every author goes in the top field, not the input field associated with it. I can add a counter to the loop and append the counter variable to the id (authorname), to make the id distinct, but how would I reflect that in the function?

Or, if that's the wrong way of going about this, how can I get to where I want to go with this?

thanks

Try use id="authorname" in SPAN (remove it from INPUT), then associate with name="authorname" of INNPUT:

function setAuthor(element) {
var author = element.innerHTML;
var author_name = element.id;
window.alert(author);
document.forms["myform"].elements[author_name].value = author;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.