Asaf
Asaf

Reputation: 2035

Can't set the value of input with Javascript

I'm trying to change the value of an input field with Javascript.
I tried everything, but nothing seems to works. I tried putting the 5 between quotation marks and using jquery. I also double-checked the array and everything.

Here is the input code:

<input type="number" id="id_[SOME_ID_HERE]" value="0">

and the loop used to update the values.

for (var i = 0; i < shoppingCart.length; i++) {
    var val = shoppingCart[i];
    document.getElementById("id_" + val.substring(3)).value = 5;
}

jsfiddle: http://jsfiddle.net/zkTud/

EDIT: Seems like it doesn't work with type="text" as well...

EDIT2: Thank you everyone who answered. My problem was actually something else.
The input was loaded from another page, and it took time and the for loop I had problem with (see above) was executed before the file was done loading.
All I did was to move the for loop as is to the callback function and it works now.

Thanks anyways!
I really appreciate the help I'm getting in this site! :)

Upvotes: 0

Views: 4210

Answers (3)

Furqan Hameedi
Furqan Hameedi

Reputation: 4400

Check this, JSFiddle , Updated and corrected your problem.

Code:

var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";

for(var i = 0; i < shoppingCart.length; i++) {
    var val = shoppingCart[i];

    $("#id" + val.substring(4)).val( "5");
}

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34107

demo http://jsfiddle.net/bY4EV/6/

sustring(3) gives d_1 : How to substring in jquery

hope this helps

code

var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";

for(var i = 0; i < shoppingCart.length; i++) {
    var val = shoppingCart[i];

    $("#id_" + val.substring(5)).val("5");
}

​

Upvotes: 2

James Allardice
James Allardice

Reputation: 165951

The problem is that your call to substring is returning too much of the string, so there are no elements found by getElementById. Change it to this:

for(var i = 0; i < shoppingCart.length; i++) {
    var val = shoppingCart[i];
    document.getElementById("id_" + val.substring(5)).value = 5;
}

Here's an updated fiddle.

The substring method (when called with one argument) returns the characters from the index specified to the end of the string. Since you are specifying index 3, you get "d_1", "d_2" etc. when actually you just want the number.

Alternatively, you could of course change the string to which you append the substring, but I think that would be more confusing to read (not immediately obvious which element will be returned):

document.getElementById("i" + val.substring(3)).value = 5;

Upvotes: 3

Related Questions