javascript Var error not working! click even

2019-09-06 11:29发布

问题:

I am trying to get the link value or href from a popup page and add the content to the parent page in a text box. I don't knwo javascript well at all and dont understand why both links are not working.... There can be 2 items listed or there can be 500 so i need this to work with a dynamic list any help would be great! Thank you!!!!

Here is what i have.

Pop up page....

<a href="#item1" id="ddlNames"  name="ddlNames"><img src="link to item 1 image"> </a>
<a href="#item2" id="ddlNames"  name="ddlNames"> <img src="link to item 2 image"> </a>

<input type="button" value="Select" onclick="SetName();" />

<script type="text/javascript">
    function SetName() {
        if (window.opener != null && !window.opener.closed) {
            var txtName = window.opener.document.getElementById("txtName");
            txtName.value = document.getElementById("ddlNames").href;
        }
        window.close();
    }
</script>

Here is the code on the main page.

<script type="text/javascript">
    var popup;
    function SelectName() {
        popup = window.open("img_sel.php", "Popup", "width=300,height=100");
        popup.focus();
    }
</script>

<input type="text" name="image" id="txtName" />
<input type="button" value="Select Name" onclick="SelectName()" />

Here is what i have now.....

<?php 
$colors = array("red","green","blue","yellow"); 
foreach ($colors as $value)
  {
 echo "<a href=\"#$value\" id=\"$value\"  name=\"$value\"> $value </a>";
  }
?>

<input type="button" value="Select" onclick="SetName();" />

<script type="text/javascript">

    cars=<?php echo json_encode($colors); ?>;
    function SetName() {
        if (window.opener != null && !window.opener.closed) {
            var txtName = window.opener.document.getElementById("txtName");

        for (var i=0;i<cars.length;i++)
        {   
        txtName.value = document.getElementById((cars[i])).href;
        }
        }
        window.close();
    }
</script>

回答1:

Same ids are not the good idea so you can do it this way, there is no need to use id.
Here is full code