west
west

Reputation: 25

Javascript function parameter does not work

In my html form I have 4 file input fields.

<input type="file" id="one" name="Title_image1" onchange="check_extension(one)"/>
<input type="file" id="one2" name="Title_image2" onchange="check_extension(one3)"/>
<input type="file" id="one3" name="Title_image3" onchange="check_extension(one4)"/>
<input type="file" id="one4" name="Title_image4" onchange="check_extension(one5)"/>

I want to check file extension on inputs using javascript.

My function

function check_extension($field_id)
{
    var allowed = {'jpg': 1, 'png': 1};
    var fileinput = document.getElementById("$field_id");

    var y = fileinput.value.split(".");
    var ext = y[(y.length) - 1];
    ext = ext.toLowerCase();

    if (allowed[ext]) {
        document.chooseF.confirm.disabled = false;
        return true;
    } else {
        alert("This is an unsupported file type. Supported files are: jpg,png");
        document.chooseF.confirm.disabled = true;
        return false;
    }
}

I am using the same function for all the input fields with fieldid as parameter, but it does not work.

Upvotes: 0

Views: 48

Answers (2)

Volune
Volune

Reputation: 4339

  • onchange="check_extension(one)"

    Here one is the Node with the id "one", one is not the string "one"

  • document.getElementById("$field_id");

    Even if $field_id is the id "one", "$field_id" is a different string
    So getElementById("$field_id") will give you the node with id "$field_id", not the node with id "one".

Fixes

onchange="check_extension('one')"

and

document.getElementById($field_id)

Also I discourage naming string variables with a leading $

Upvotes: 2

bulforce
bulforce

Reputation: 1071

change this:

<input type="file" id="one" name="Title_image1" onchange="check_extension(one)"/>

like so:

<input type="file" id="one" name="Title_image1" onchange="check_extension('one')"/>

Then change this:

function check_extension($field_id)
{
    var allowed = {'jpg': 1, 'png': 1};
    var fileinput = document.getElementById("$field_id");
....

like so:

function check_extension(field_id)
{
    var allowed = {'jpg': 1, 'png': 1};
    var fileinput = document.getElementById(field_id);
...

Upvotes: 0

Related Questions