JackParker2 JackParker2 - 3 months ago 15
HTML Question

Why Won't My Hidden Field Populate from JavaScript Function?

I created a JavaScript function that creates a string that I need to use in another form on the website I'm working on. To do this I thought I would just write the value to a hidden field, and then submit it in the HTML form. However, nothing I do will get the value to appear in the field even though the alert will populate.



function customFunc(){
var customD = document.querySelector('input[name = "customD"]:checked').value;
var customL = document.getElementById('Custom_Length').value;
var customW = document.getElementById('Custom_Width').value;
var lowerV = customL * customW;
var maxV1 = Math.ceil(lowerV/100)*100;
var maxV2 = maxV1 - 1;
var lowerB = maxV1 - 100;
var pStyle = document.querySelector('input[name = "pl"]:checked').value;
var itemTest = pStyle +customD+"."+lowerB+"-"+maxV2;
alert(itemTest );
return itemTest ;
document.getElementById('testSku').value = itemTest ;
}


On the HTML side I have this as the hidden field

<input type="text" name="testSku" id="testSku">

Answer

The return statement ends a function and returns to the caller. Anything after that in the function is not executed. So the assignment to the input's value is ignored. Put the return statement last.

function customFunc(){
    var customD = document.querySelector('input[name = "customD"]:checked').value;
    var customL = document.getElementById('Custom_Length').value; 
    var customW = document.getElementById('Custom_Width').value;  
    var lowerV = customL * customW;
    var maxV1 = Math.ceil(lowerV/100)*100;
    var maxV2 = maxV1 - 1;
    var lowerB = maxV1 - 100;
    var pStyle = document.querySelector('input[name = "pl"]:checked').value;
    var itemTest = pStyle +customD+"."+lowerB+"-"+maxV2;
    alert(itemTest );
    document.getElementById('testSku').value = itemTest ;
    return itemTest ;
}