简体   繁体   中英

Save Img Src to Javascript Variable

I am trying to set the image src inside a hidden variable that is passed from my form. When I output the variable is "undefined". I am pretty new to Javascript and not sure what the problem could be. My error is on line:

document.sampleForm.image.value = "images/"+img.attr('src')+"";

Javascript:

$('tr', '#target').each(function () {
    var tr = $(this);
    html += '<center><tr>';
    $('td', tr).each(function () {
        var td = $(this);
        if (!td.is('td.header')) {
            var img = $('img', td);
            var text = $('textarea', td).val();
            html += '<td style="width: 33%;">';
            html += (img.length) ? '<img src="' + img.attr('src') + '" style="display: block; max-width: 100%;" />' : '<div style="width: 100%;"></div>';
            document.sampleForm.image.value = "images/"+img.attr('src')+""; 
            document.forms["sampleForm"].submit();
            html += '</td>';
        } 
    });
    html += '</tr></center>';
});

HTML:

<table id="target">
<form id="sampleForm" name="sampleForm" action="test.php" method="post">
    <tr><center>

        <td class="logo" colspan="3">
            <h3>Choose Header</h3>
          <div class="img-container"><input type="hidden" name="image" id="image" value=""></div>

        </td>

    </center>
    </tr>
    <tr>
    <td style="height:auto;">

    <?php

    $test = mysql_query("SELECT id, title FROM tmpl2");



    echo "<select class='image_select' id='logo_option' name='logo_option[]' multiple='multiple'>";


        while ($row = mysql_fetch_assoc($test))
    {
        echo "<option value='".$row[id]."'>$row[title]</option>";
    }   


    echo "</select>";



    ?>



    </td>
    </tr>


           <tr><center>

        <td class="logo" colspan="3">
                <h3>Choose Logo</h3>
          <div class="img-container"></div>

        </td>

    </center>
    </tr>
    <tr>
    <td style="height:auto;">
    <?php

    $test = mysql_query("SELECT id, title FROM tmpl2");

    echo "<select class='image_select' id='header_option' name='header_option[]' multiple='multiple'>";


        while ($row = mysql_fetch_assoc($test))
    {
        echo "<option value='".$row[id]."'>$row[title]</option>";
    }   


    echo "</select>";

    ?>
    </td>
    </tr>

</table>

The reason you are getting undefined is because

document.sampleForm.image.value = "images/"+img.attr('src')+"";

is not a property of the HTMLImageElement . You need .src .

document.sampleForm.image.src = "images/"+img.attr('src')+"";

but as @Barmar said you really should not be doing it like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM