一个JavaScript函数,用于更新多个隐藏字段,具体取决于它们是否存在

A JavaScript function to update multiple hidden fields depending if they exist or not

本文关键字:取决于 存在 是否 字段 隐藏 函数 JavaScript 用于 更新 一个      更新时间:2023-09-26

我有一个JavaScript函数,用于更新向用户显示的图像的文件名字段中隐藏的内容。这适用于具有单个图像和单个隐藏字段的页面。我正在尝试对其进行自定义,以便在单个页面上使用它来更新多个隐藏字段,具体取决于它们是否存在。

以前,我试图从onload中调用用分号分隔的单独函数。它适用于第一个页面/隐藏字段,但当第一个隐藏字段在第二个页面上不可用时,它一直在清除错误。

在这次尝试中,我试图使用一个带有if语句的函数来链接到隐藏字段的id,但不幸的是,我似乎无法让它在任何页面/隐藏字段上工作

有人能告诉我哪里出了问题吗?我相信这是可能的,但我没有得到任何结果。感谢

电流输出

<input id="id_9-slider_one_image" name="9-slider_one_image" type="hidden" />
<input id="id_10-slider_two_image" name="10-slider_two_image" type="hidden" />
<input id="id_11-slider_three_image" name="11-slider_three_image" type="hidden" />

所需输出

<input id="id_9-slider_one_image" name="9-slider_one_image" type="hidden" value="P1DP.jpg"/>
<input id="id_10-slider_two_image" name="10-slider_two_image" type="hidden" value="P6D6.jpg"/>
<input id="id_11-slider_three_image" name="11-slider_three_image" type="hidden" value="P3D3.jpg"/>

我的代码

<div class="image_rating">      
    <img src="{% static "survey/images/pathone/" %}{{display_image}}" value="{{display_image}}" onload="updateInput(this)"/>                                                                                   
</div>  

<script type="text/javascript">
    function updateInput(ish) {
    var valueAttribute = ish.getAttribute("value");

    if($(this).attr("id") == "id_9-slider_one_image")
        document.getElementById("id_9-slider_one_image").setAttribute(
        "value", valueAttribute);
    if($(this).attr("id") == "id_10-slider_two_image")
        document.getElementById("id_10-slider_two_image").setAttribute(
        "value", valueAttribute);

    if($(this).attr("id") == "id_11-slider_three_image")
        document.getElementById("id_11-slider_three_image").setAttribute(
        "value", valueAttribute);
    }
</script>

由于这个问题和投票率最高的答案,我能够在尝试设置值之前检查页面中是否存在id

{% if wizard.steps.current in steps %}              

<div class="image_rating">      
    <img src="{% static "survey/images/pathone/" %}{{display_image}}" value="{{display_image}}" onload="updateInput(this)"/>                                                                                    
</div>  

<script type="text/javascript">
    function updateInput(ish) {
    var valueAttribute = ish.getAttribute("value");
    if (document.getElementById('id_9-slider_one_image')) {
        document.getElementById("id_9-slider_one_image").setAttribute(
        "value", valueAttribute)
    }
    if (document.getElementById('id_10-slider_two_image')) {
        document.getElementById("id_10-slider_two_image").setAttribute(
        "value", valueAttribute)
    }
    if (document.getElementById('id_11-slider_three_image')) {
        document.getElementById("id_11-slider_three_image").setAttribute(
        "value", valueAttribute)
    }
</script>