Reputation: 1161
I have an input
textfield with the name qtyText
, to which a user enters a value. I would like to set this value as the value for another hidden field named 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 works, 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 trying to send it to the servlet. I would like to have a value = someJSFunction()
, some kind. The function needs to trigger upon onChange
event in the qtyText
input field.
Upvotes: 3
Views: 36533
Reputation: 1
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"/>
Upvotes: 1
Reputation: 253308
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]);
};
}
}
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"
.
Upvotes: 1
Reputation:
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;
};
}
}:
Upvotes: 7