0

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.

2 Answers 2

2
  • 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 $

Sign up to request clarification or add additional context in comments.

Comments

0

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);
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.