Reputation: 1274
I have created a form in which I have 2 text fields and one File field. I have added Javascript on 'text'
fields. If user left 'text'
fields and press submit button, All Fields are Required
Font turns red, I want to turn it red as well when user doesn't upload any Image. I have tried various ways but its not working. Kindly tell me the way of doing it.
<script type="text/javascript">
function myFunction()
{
var category_name = document.forms["insert"]["sub_category_name"].value;
//var image = document.forms["insert"]["file"].item();
var error = document.getElementById("error");
if(category_name=="" )
{
error.style.color="Red";
return false;
}
else
{
//message.innerHTML="Data Inserted!";
}
}
</script>
PHP code
<?php
echo "
<form name='insert' action='sub_categories.php' method='POST' onSubmit='return myFunction()' enctype='multipart/form-data'>
<table class='gridtable' border=2 bordercolor='#CCCCCC' cellpadding='10'>
<tr>
<th>
Sub-Category Name: </th><td> <input type='text' name='sub_category_name' ></td></tr>";
echo "
<tr>
<th>
Image1:</th><td> <input type='file' name= 'file' ></td></tr>
";
Thanks
Upvotes: 2
Views: 4915
Reputation: 2214
Your best, easiest bet is to use JQuery as follows:
$("input[type='file'][name='file']").filter(function (){
return !this.value
}).length;
The reason you cannot use ':empty' is because ':empty' matches when an element does not have any descendants. Input elements cannot have descendants, thus your 'input' will always evaluate ':empty' as true.
Upvotes: 0
Reputation: 8334
Just get your file input by id and check if it's value is empty :
if(document.getElementById('file').value=='') {//something here }
Upvotes: 6