1

I am trying to style input type=file.

When I try to override the deault button with my custom buttom (so that I can styel it). The problem I am facing is when ever I click my custom button the form gets submitted and validation kicks in. Is there a way I can fix it.

HTML

<input type="file" name="upload" id="upload" class="upload"/>
<button class="fileButton" id="fileButton">Choose File</button>
<input type="submit" name="button" value="Contact Me" class="supportButton"></input>

Last input is my form submission button.

Javascript:

<script type="text/javascript">
 $('#fileButton').click(function(){
 $('#upload').click();
 alert("input");
 });
</script>

When I click my custom button, it triggers the file uplaod button ( I can browse and upload file) but at the same time it submits the form.

Fiddle: http://jsfiddle.net/uw5wqxpw/

1
  • i think its working fine you only have to include jquery in fiddle example Commented Dec 23, 2014 at 4:40

5 Answers 5

2

If you use type="button" it won't submit a form. Default type for button if not declared is submit. Thus when you are clicking on it it submits the form as default behavior would expect

<button type="button" class="fileButton" id="fileButton">Choose File</button>
Sign up to request clarification or add additional context in comments.

1 Comment

don't feel bad, have done this by accident myself numerous times
2

You need to suppress the default action of clicking on a button:

$('#fileButton').click(function(e){
    e.preventDefault();
    $('#upload').click();
    alert("input");
});

Comments

2

add jquery file to you code.then use trigger function in jquery it will work

 $('#fileButton').click(function(){
 $('#upload').trigger("click");
 });
.upload{
    display:none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="upload" id="upload" class="upload"/>
<button class="fileButton" id="fileButton">Choose File</button>
<input type="submit" name="button" value="Contact Me" class="supportButton"></input>

Comments

1

When your function runs the $('#upload').click() line, it is actually simulating the button being clicked as it is shorthand for .trigger("click"), and then the submit button's default behavior is triggered. I think the function you need is $('#upload').on("click", clickHandler).

Comments

1

By default type attribute is submit which makes your form to submit, use type='button' instead:

<button class="fileButton" id="fileButton" type='button'>Choose File</button>

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.