Set the value of a Javascript input hidden field t

2019-05-11 01:41发布

问题:

I have an input text field (name: qtyText) to which a user enters a value. I would like to set this value as the value for another hidden field (name: qtyTextHidden) using JavaScript. How can I go about it?

HTML

<input name = "qtyText" type = "textbox" size = "2" value = "" />
<input type="hidden"  value = "" name="qtyTextHidden"/>

My efforts to set the field value using JS work, but I am unable to send the value to the servlet. So I am attempting to directly set the value using a function and then try and send it to the servlet. I would like to have a value = someJSFunction() kind. The function needs to trigger upon "onChange" in the "qtyText" input field.

回答1:

Using jQuery:

$(document).ready(function() {
    $('input:text[name="qtyText"]').keyup(function() {
        $('input:hidden[name="qtyTextHidden"]').val( $(this).val() );
    });
});

Using JavaScript:

window.onload = function() {
    if(document.readyState == 'complete') {
        document.getElementsByTagName('input')[0].onkeyup = function() {
            document.getElementsByTagName('input')[1].value = this.value;
        };
    }
}:


回答2:

I'd suggest:

function updateHidden(valueFrom, valueTo) {
    valueTo.value = valueFrom.value;
}

var inputs = document.getElementsByTagName('input'),
    textInputs = [],
    hiddenInputs = [],
    refersTo;

for (var i = 0, len = inputs.length; i < len; i++) {
    switch (inputs[i].type) {
        case 'hidden':
            hiddenInputs.push(inputs[i]);
            break;
        case 'text':
        default:
            textInputs.push(inputs[i]);
            break;
    }
}

for (var i = 0, len = textInputs.length; i < len; i++) {
    refersTo = document.getElementsByName(textInputs[i].name + 'Hidden')[0];
    if (refersTo !== null) {
        textInputs[i].onchange = function () {
            updateHidden(this, document.getElementsByName(this.name + 'Hidden')[0]);
        };
    }
}

JS Fiddle demo.

Incidentally: there is no type="textbox". At all. Ever. Anywhere in HTML, not even in HTML 5: it's type="text". The only reason it works with type="textbox" is because browsers are ridiculously forgiving and, if the type isn't understood, it defaults to type="text".



回答3:

To set the value of the hidden field the easiest way is to use the javascript function that to pass three parameters from, to, and form names:

<script type="text/javascript">
    function someJSFunction(form, from, to){
      var el_from=form[from], el_to=form[to];
      el_to.value=el_from.value;
      return el_to.value;
    }
</script>
<form name="myform">
<input name = "qtyText" type = "textbox" size = "2" value = "" onchange="someJSFunction(myform, 'qtyText', 'qtyTextHidden')"/>
<input type="hidden"  value = "" name="qtyTextHidden"/>