rhorne
rhorne

Reputation: 161

Javascript - Use document.getelementbyid().value with a variable

I'm trying to capture the value of a text field on an HTML form using document.getElementById(my_field).value where the variable my_field is passed to my function dynamically, but am hitting a wall.

How do you use a variable in this context?

The function just doesn't seem to parse the contents of the variable my_field, instead treating it as a string no matter whether I use quotes, square brackets or curly braces.

function myFunction() {
    var my_field = arguments[0];
    var current_value = document.getElementById(my_field).value;
    alert ("Current Value: " + current_value);
}

I'm doing it this way because I have multiple records on a form and each row has its own unique id for the required field.

Running the above just does nothing. The alert never pops which I assume is because current_value never gets set.

To add further detail - I tried to simplify everything for the purposes of this question as there's lots of other unnecessary complications that will only detract from the main issue - on my HTML form is a text field which calls my function on onChange

onchange="enforce_multiples('quantity[<?php echo $line_id; ?>]',<?php echo $product['minimum'];?>)"

I've checked that arguments[0] and [1] are being captured correctly by outputting their values to an alert. Everything works fine up until I try to set the quantity_entered value.

<script>
function enforce_multiples() {

var line_id = arguments[0];
var quantity_increments = arguments[1]; 
var quantity_entered = document.getElementById([line_id]).value;

alert("QE" + quantity_entered);

//var quantity_mod = quantity_entered % quantity_increments;
//var revised_quantity = quantity_entered - quantity_mod;  

//alert("RQ: " + revised_quantity);
//document.getElementById([line_id]).value = revised_quantity; 
}
</script>

Checked the console and I receive the error: Uncaught TypeError: Cannot read property 'value' of null on the geElementById line

Upvotes: 0

Views: 8022

Answers (2)

rhorne
rhorne

Reputation: 161

OK so I got to the bottom of this in case anyone is interested.

In order to use a variable in document.getElementById() you simply add the variable name with no quotes.

var my_variable = "field1";
document.getElementById(my_variable);

The reason this wasn't working on my form was because the text fields only had the name parameter and not an id parameter.

So I needed to change:

<input type="text" name="field_name" value="1234" />

To

<input type="text" name="field_name" id="field_name" value="1234" />

And that sorted it. Otherwise I was just getting generic NULL error messages in the console.

Upvotes: 1

Damien
Damien

Reputation: 1600

You should write document.getElementById(my_field) instead of document.getelementbyid(my_field).

Upvotes: 1

Related Questions