Using Javascript to update hidden form fields with the image file name on individual form pages

I have a customized Django wizard_form.html that shows the user 3 different images on three different pages of my survey.

I am trying to use the script below to update 3 hidden form fields on three different pages with the content value="{{display_image}}" as a way to store the image file name displayed to the user in the database

This works great for the first page / image, for example.

 <input id="id_9-slider_one_image" name="9-slider_one_image" type="hidden" value="P1D1.jpg"/> 

But I can't get him to work on a second or third

 <input id="id_10-slider_two_image" name="10-slider_two_image" type="hidden" /> 

Can someone tell me what I am doing wrong?

My code

 {% if wizard.steps.current in steps %} <div class="image_rating"> <img src="{% static "survey/images/pathone/" %}{{display_image}}" value="{{display_image}}" onload="updateInput1(this); updateInput2(this); updateInput3(this);"/> </div> <script type="text/javascript"> function updateInput1(ish) { var valueAttribute = ish.getAttribute("value"); document.getElementById("id_9-slider_one_image").setAttribute( "value", valueAttribute); } function updateInput2(ish) { var valueAttribute = ish.getAttribute("value"); document.getElementById("id_10-slider_two_image").setAttribute( "value", valueAttribute); } function updateInput3(ish) { var valueAttribute = ish.getAttribute("value"); document.getElementById("id_11-slider_three_image").setAttribute( "value", valueAttribute); } </script> 

Any help, as always, is greatly appreciated, thanks.

+7
javascript html django
source share
2 answers

First you need to assign the value of the input identifier to a variable, for example element_id

 element_id = "id-slider_one_image" 

If you cannot name them anyway, just provide this with the actual identifier of the element (for example: id_9-slider_one_image ).

Then you need to change the function arguments to also take the identifier of the element

 function updateInput(ish, elementId) { var valueAttribute = ish.getAttribute("value"); document.getElementById(elementId).setAttribute( "value", valueAttribute); } 

Then your onload attribute should pass the element_id string in addition to the element reference:

 onload="updateInput(this, '{{element_id}}');" 
+5
source share

just create a function that calls all 3 update functions with try catch

 function Update(sender){ try{ updateInput1(sender); } catch(e){ try{ updateInput2(sender); } catch(e){ updateInput3(sender);}} } 

and use onload='Update(this)'

+3
source share

All Articles