Reputation: 143
I have a series of textboxes with the same name
<%for(i=0;i<=nooftasks;i++){%>
<input type="text" id="duration"
name="duration" class="td4" onkeyup="durationFormat()">
}%>
In Javascript I have to add a colon after two digits
function durationFormat()
{
var duration = document.getElementsByName("duration").value;
if(duration.length==2){
duration=duration+":";
}
}
But I could not get the desired result as I could not get the string from the textbox
of that particular text box.
Any ideas?
Upvotes: 0
Views: 3515
Reputation: 889
You have to loop into your elements with name duration
.
function durationFormat() {
var duration = document.getElementsByName("duration");
for (var i = 0; i < duration.length; i++) {
if(duration[i].value == 2){
duration[i].value += ":";
}
}
}
The logic for this is:
elements
that have an attribute name with duration
value in that property..getElementsByName
method.:
at the end of the value if his value is 2
.For those that don't understand what duration[i].value += ":";
does, automatically gets the value of the input element at i
position of the array and adds the value :
at the end. It's exactly the same that if you do duration[i].value = duration[i].value + ":";
. I prefer to use +=
, because it's sorter. I never tested, but I think that it's also the fastest way for browsers to add some content at the end. It can also be used for string variables.
Upvotes: 1
Reputation: 943650
getElementsByName
returns a NodeList not an Element. A NodeList is like an Array. You need to loop over it and apply your changes to each value in turn.
Even if you have used getElementById
(which returns an Element) and had unique IDs for your inputs (you don't, this is invalid, fix it) then it still wouldn't modify the value. Copying the value
property into a variable and then modifying it won't change the value
property of the input. You would need to go back and then input.value = duration
after you made your modification.
If you want to get the specific input that invoked the function, then:
addEventListener
insteadsuch:
<fieldset id="durations">
<legend>Durations</legend>
<%for(i=0;i<=nooftasks;i++){%>
<input type="text" name="duration" class="td4">
}%>
</fieldset>
<script>
function durationFormat(ev) {
var input = ev.target;
if (input.value.length === 2) {
input.value += ":";
}
}
document.getElementById('durations').addEventListener('keyup', durationFormat);
</script>
Upvotes: 2
Reputation: 25527
<input type="text" id="duration" name="duration" class="td4" onkeyup="durationFormat(this)">
<script>
function durationFormat(obj) {
if ((obj.value.length)== 2) {
obj.value+=":";
}
}
</script>
Upvotes: 2