简体   繁体   中英

Set form hidden value on submit

I got a form, and I want to send hidden input by javascript, how to do it? F.ex:

<input id="total" type="hidden" value="" name="total" />

And when someone click submit I want to set it value

Are you trying to instantaneously change the value of the hidden input? Something like that can be achieved with the onsubmit event, of course.

var submit = document.getElementById("submit");
var hidden = document.getElementById("hidden");

var eventListener = function(el, type, listener) {
    if(el.addEventListener) {
        el.addEventListener(type, listener, false);
    } else if(el.attatchEvent) {
        el.attatchEvent("on"+type, listener);
    } else {
        el['on'+type] = listener;
    }
};

var onsubmit = function() {
    var newVal = "value to set for hidden input";

    hidden.value = newVal;
};

eventListener(submit, "submit", onsubmit);

The above code will listen to the submit event on the submit button and when triggered, it will change the value of the hidden input. To go into further detail with any answer, we'd need a more descriptive question. Otherwise, I really don't know what you want.

You can try following:

 document.getElementById("total").value = "value you want to set";
    document.formname.submit();

If you're trying to create a unique id so that you can add this person into some db with a unique key or you want to create some sort of session id or a similar id and store it in memory then I suggest using php or perl not javascript. I'm a newbie too but i've had that sort of dilemma come up with some stuff i was trying to do and php did the trick for me. I ended up using js to validate the form data and pass it to the php once it checked out. js is great if you want to check to see if the data is present and doesn't contain anything that you don't want or need in the form. it's not great for security.

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