How to display image name after upload in HTML? - javascript

hi i create basic page which need's to upload image. It successfully upload image but after it upload it don't displaying the name of file i upload , but it display on console . This is my index.html code.
This is how it's look in browser
It display true.png in console but keep showing choose file after i upload
<div class="container">
<div class="display-3 my-2 text-center">Breast Cancer Prediction</div>
<hr />
{% if image_class %}
<div class="display-4 my-2 text-center">
<div class="alert alert-info alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
<p>Class : {{ image_class.class }}</p>
Confidence: {{ image_class.confidence }}
</div>
</div>
{% endif %}
<div class="col-lg-12 pt">
<form class="" method="POST" action="" enctype="multipart/form-data">
{{ form.hidden_tag() }}
<div class="form-group">
<div class="custom-file mt-4">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
{{ form.picture(class="file custom-file-input ") }}
{{ form.picture.label(class="custom-file-label", for="picture") }}
</div>
</div>
<div class="mt-4 text-center">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
</div>
</div>
<script type="text/javascript">
$('#picture').change(function(e){
var filename = e.target.files[0].name;
console.log(filename);
});
function displayfilename() {
$('#picture').trigger('change');
}
</script>

It displays to the console because you tell it to.
$('#picture').change(function(e){
var filename = e.target.files[0].name;
console.log(filename);
});
What you need to do is find the element that you're looking to list the uploads and then change the text for example
$('#picture').change(function(e){
var filename = e.target.files[0].name;
$('#picture01Desc').text(filename)
});

Related

Django submit form in bootstrap modal

i know that there are a lot of posts with similar topic as this one, but none of them seem to be a useful fix in my case at least. As the headline describes i want to be able to send a new comment form to my database from a bootstrap modal. My data is being shown just fine so the only problem i got is that when i fill out the data for a new comment and press the submit button the modal is just being dismissed and no action has happened in my DB. My best guess for why it is not working is because i got my modal data in a separated html file detail.html. But otherwise i was not able to display the right data for each posts.
button to open the modal in home.html:
<a class="btn btn-outline-primary post_details-btn" class="open-modal" data-url="{% url 'post_detail' post.pk %}" width="17" height="17"><i class="fa fa-comments"></i></a>
my modal in home.html where i display the data from detail.html in the div with the id = modal-div
<div class="modal fade" id="myModal2">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">WINNER:</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div id="modal-div"></div>
</div>
</div>
</div>
</div>
my jquery to display the html code from detail.html in the modal, this code is also located in home.html
var modalDiv = $("#modal-div");
$(".post_details-btn").on("click", function() {
$.ajax({
url: $(this).attr("data-url"),
success: function(data) {
$('#myModal2').modal('show');
modalDiv.html(data);
}
});
});
detail.html
{% block content %}
{% load static %}
<div class="container">
<div class="row">
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
<!-- comments -->
<h2>{{ comments.count }} comments</h2>
{% for comment in comments %}
<div class="comments" style="padding: 10px;">
<p class="font-weight-bold">
{{ comment.name }}
<span class=" text-muted font-weight-normal">
{{ comment.created_on }}
</span>
</p>
{{ comment.body | linebreaks }}
</div>
{% endfor %}
</div>
</div>
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
{% if new_comment %}
<div class="alert alert-success" role="alert">
Your comment is awaiting moderation
</div>
{% else %}
<h3>Leave a comment</h3>
<form method="post" style="margin-top: 1.3em;">
{{ comment_form.as_p }}
{% csrf_token %}
<button type="submit" class="btn btn-primary submit">Submit</button>
</form>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock content %}
my post_detail function in views.py
def post_detail(request, pk):
allposts= Posts.objects.all()
alltags = Tag.objects.all()
post = get_object_or_404(Posts, pk=pk)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
print("form is send!")
else:
comment_form = CommentForm()
context = {
'alltags': alltags,
'allposts': allposts,
'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form,
'alltags': alltags,
}
return render(request, 'detail.html', context)
i did manage to get a solution myself after days of researching. The solution was to add the url in action attribute in the detail.html to the function in views.py that handles the comment form.
<form method="post" action="{% url 'post_detail' post.pk %}">
{{ comment_form.as_p }}
{% csrf_token %}
<button type="submit" class="btn btn-primary">submit</button>
</form>

JQuery/AJAX call function seems to run only once and JQuery selector on AJAX result only yields the inner html

I am new to programming and this is also my first question on this platform. I have tried implementing applicable solutions I could find here for similar questions raised but is still stuck. Should you believe that a previously answered question might answer mine, please share the link to such answer. Also please correct me should you find that I have broken some guidelines on how to properly ask questions on this platform.
Now, on to the actual issues.
The following are the relevant sections (please, let me know if I have missed something that might be relevant). The issues are stated on my comments on modals.js.
modals.js
$(document).ready(function(){
$('#frmAddProduct').on('submit', function aj (event) {
event.preventDefault();
$.ajax({
cache: false,
type : 'POST',
url : '/products/new',
data : $('#frmAddProduct').serialize(),
datatype: 'html'
})
.done(function process (data) {
/* The modal has to be shown unless the user clicks on 'close'*/
$('#modalAdd').modal('show');
let err = $(data).find(".invalid-feedback").html();
if (err){
/* replace the contents of the modal with section from
ajax result to show validation messages*/
let cont = $(data).find("#targetModalContent").html();
$('#targetModalContent').html(cont);
/* Once the code above executes, clicking the submit button again
terminates the whole process.
Maybe this section requires a loop or recursion? But this part
is already on the "on submit" listener, right?*/
}
else {
/* Show success flash message on the modal instead of the original
below nav location */
console.log(data);
let msg = $(data).closest("#targetFlash").html();
/* using the .find doesn't work and results in msg=undefined.
I don't understand why that is the case, I tried using .parent
but it also did not work, or maybe I was using the .parent improperly.
I also tried $($(data).closest("#targetFlash")).parent().html but
it too didn't worked.
Why is it returning only the message and not the whole node
with the enclosing div?
*/
$('#frmAddProduct fieldset>div:first').prepend(msg);
}
});
});
});
products.html
{% extends "tblayout.html" %}
<!-- Main Content -->
{% block thead %}
{% endblock %}
{% block tbody %}
{% endblock %}
{% block tfoot %}
{% endblock %}
{% block maincont %}
<!-- ModalAdd -->
<div class="modal fade" id="modalAdd" tabindex="-1" role="dialog" aria-labelledby="modalAddTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content" id="targetModalContent">
<div class="modal-header">
<h5 class="modal-title" id="modalAddLongTitle">Add {{ legend }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" action="" id="frmAddProduct">
{{ formAdd.csrf_token }}
<div class="modal-body">
<div class="container-fluid">
<fieldset class="form-group">
<div class="form-group row">
{{ formAdd.productSubCategory.label(class="col-form-label col-sm-5") }}
{% if formAdd.productSubCategory.errors %}
{{ formAdd.productSubCategory(class="form-control col-sm-7 is-invalid") }}
<div class="invalid-feedback">
{% for error in formAdd.productSubCategory.errors %}
<span class="col-sm-7 offset-5">{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ formAdd.productSubCategory(class="form-control col-sm-7") }}
{% endif %}
</div>
<div class="form-group row">
{{ formAdd.brand.label(class="col-form-label col-sm-5") }}
{% if formAdd.brand.errors %}
{{ formAdd.brand(class="form-control col-sm-7 is-invalid") }}
<div class="invalid-feedback">
{% for error in formAdd.brand.errors %}
<span class="col-sm-7 offset-5">{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ formAdd.brand(class="form-control col-sm-7") }}
{% endif %}
</div>
<div class="form-group row">
{{ formAdd.description.label(class="col-form-label col-sm-5") }}
{% if formAdd.description.errors %}
{{ formAdd.description(class="form-control col-sm-7 is-invalid") }}
<div class="invalid-feedback">
{% for error in formAdd.description.errors %}
<span class="col-sm-7 offset-5">{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ formAdd.description(class="form-control col-sm-7") }}
{% endif %}
</div>
</fieldset>
</div>
</div>
<div class="modal-footer">
<div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<div>
{{ formAdd.submit(class="btn btn-primary") }}
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
<!-- Optional Body scipt loaded after the main content has loaded -->
{% block bodyscript %}
<script src="../static/js/modals.js"></script>
{% endblock %}
AJAX result on Issue #1
<!-- ModalAdd -->
<div class="modal fade" id="modalAdd" tabindex="-1" role="dialog" aria-labelledby="modalAddTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content" id="targetModalContent">
<div class="modal-header">
<h5 class="modal-title" id="modalAddLongTitle">Add Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" action="" id="frmAddProduct">
<input id="csrf_token" name="csrf_token" type="hidden" value="ImNlZDc1Njc0MTY4NTg5NTNhNDg0NWEyNGYyZjYzZmIyYmFmMTZhZmQi.YAamUA.WGi03w__AklqccdIQgK_pWG5oJg">
<div class="modal-body">
<div class="container-fluid">
<fieldset class="form-group">
<div class="form-group row">
<label class="col-form-label col-sm-5" for="productSubCategory">Product Sub-Category</label>
<select class="form-control col-sm-7 is-invalid" id="productSubCategory" name="productSubCategory" required><option selected value="1">ProductCategory1, ProductSubCategory1</option><option value="2">ProductCategory1, ProductSubCategory2</option><option value="3">ProductCategory2, ProductSubCategory3</option></select>
<div class="invalid-feedback">
<span class="col-sm-7 offset-5">Product combination is already enrolled.</span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-5" for="brand">Brand</label>
<select class="form-control col-sm-7 is-invalid" id="brand" name="brand" required><option selected value="1">Brand1</option><option value="2">Brand2</option><option value="3">Brand3</option></select>
<div class="invalid-feedback">
<span class="col-sm-7 offset-5">Product combination is already enrolled.</span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-5" for="description">Product Description</label>
<input class="form-control col-sm-7 is-invalid" id="description" name="description" placeholder="New Product" required type="text" value="45">
<div class="invalid-feedback">
<span class="col-sm-7 offset-5">Product combination is already enrolled.</span>
</div>
</div>
</fieldset>
</div>
</div>
<div class="modal-footer">
<div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<div>
<input class="btn btn-primary" id="submit" name="submit" type="submit" value="Add Product">
</div>
</div>
</form>
</div>
</div>
</div>
AJAX result on Issue #2 (I have copied only the target div since the rest of the html data is just the same, this is right below the nav)
<div class="alert alert-success" id="targetFlash">
Product 45 has been added!
</div>
main.routes.py
#main.route("/products", methods=['GET', 'POST'])
#login_required
def products():
formAdd = frmAddProduct()
formMod = frmModProduct()
q = sess.query(Product.id.label("PId"),
Product.description.label("PDesc"),
Product.isactive.label("PIsactive"),
ProductSubCategory.id.label("PSCid"),
ProductCategory.description.label("PCDesc"),
ProductSubCategory.description.label("PSCDesc"),
Brand.id.label("BId"), Brand.name.label("BName"))\
.select_from(Product)\
.join(ProductSubCategory)\
.join(ProductCategory)\
.join(Brand)\
.all()
page = request.args.get('page', 1, type=int)
qp = paginate.Page(q, items_per_page=5, page=page)
data = sqlaq2dict(qp)
npage = qp.pager(url= url_for('main.products') + "?page=$page",
link_attr=dict({'class':'btn btn-outline-primary mb-4'}),
curpage_attr=dict({'class':'btn btn-primary mb-4'}),
dotdot_attr=dict())
pagenav = Markup(npage)
return render_template("products.html", title='Products', legend='Product',
data=data, pagenav=pagenav, formAdd=formAdd, formMod=formMod)
#main.route("/products/new", methods=['POST'])
#login_required
def addProduct():
formAdd = frmAddProduct()
if formAdd.validate_on_submit():
p = Product()
p.productSubCategory_id = formAdd.productSubCategory.data
p.brand_id = formAdd.brand.data
p.description = formAdd.description.data
p.isactive = formAdd.isactive.data
syncNext('management', 'Product', 'id') # Ensures right ID for Postgres
sess.add(p)
sess.commit()
flash(
f'Product {formAdd.description.data} has been added!', 'success')
# return jsonify({"status" : "success"}) #Cannot have multiple returns
return redirect(url_for('main.products'))
return render_template("products.html", title='Products', legend='Product',
formAdd=formAdd)
forms.py
class frmAddProduct(FlaskForm):
# productSubCategories = sess.query(ProductSubCategory.id,\
# ProductSubCategory.fullDesc)\
# .filter(ProductSubCategory.isactive==True)\
# .all()
psc = sess.query(ProductCategory.description.label("PCDesc"),
ProductSubCategory.id.label("PSCId"),
ProductSubCategory.description.label("PSCDesc"))\
.join(ProductSubCategory)\
.all()
pscDict = sqlaq2dict(psc) #Converts the resulting tuple to dict
productSubCategories = []
for r in pscDict:
i = (r['PSCId'], r['PCDesc'] + ', ' + r['PSCDesc'])
productSubCategories.append(i)
productSubCategory = SelectField('Product Sub-Category',
choices=productSubCategories,
coerce=int,
validators=[InputRequired()])
brands = sess.query(Brand.id, Brand.name)\
.filter(Brand.isactive == True)\
.all()
brand = SelectField('Brand', choices=brands, coerce=int,
validators=[InputRequired()])
description = StringField('Product Description', validators=[
DataRequired()], render_kw={"placeholder": "New Product"})
isactive = BooleanField('Status', default=True)
submit = SubmitField('Add Product')
#---------------------------------------------Should be composite Key
def validate_productSubCategory(self, productSubCategory):
user = sess.query(Product)\
.filter(Product.productSubCategory_id == self.productSubCategory.data,
Product.brand_id == self.brand.data, Product.description ==
self.description.data)\
.first()
if user:
raise ValidationError('Product combination is already enrolled.')
def validate_brand(self, brand):
user = sess.query(Product)\
.filter(Product.productSubCategory_id == self.productSubCategory.data,
Product.brand_id == self.brand.data, Product.description ==
self.description.data)\
.first()
if user:
raise ValidationError('Product combination is already enrolled.')
def validate_description(self, description):
user = sess.query(Product)\
.filter(Product.productSubCategory_id == self.productSubCategory.data,
Product.brand_id == self.brand.data, Product.description ==
self.description.data)\
.first()
if user:
raise ValidationError('Product combination is already enrolled.')

Cannot read property 'submit' of null i use laravel and javascript

I want to add a product to my favorites, but I do not want to make a load for the entire page, so I use JavaScript as shown in the code where I made an ancor disruption and created a form and took an id from the form and implemented it by using the submit function, but the following error appears and does
Uncaught TypeError: Cannot read property 'submit' of null
Please advise the importance
Thank you
this view
<div class="product-info">
<div class="tab-content" id="myTabContent">
<!-- Start Single Tab -->
<div class="tab-pane fade show active" id="man" role="tabpanel">
<div class="tab-single">
<div class="row">
#foreach($products as $p)
<div class="col-xl-3 col-lg-4 col-md-4 col-12">
<form action="{{route('cart.store')}}" method="post" id="add-cart-{{$p->id}}">
{{ csrf_field() }}
<input type="hidden" name="id" value="{{$p->id}}">
<input type="hidden" name="Product_Name_ar" value="{{$p->Product_Name_ar}}">
<input type="hidden" name="Price" value="{{$p->Price}}">
<div class="single-product">
<div class="product-img">
<a href="{{route('product', ['product' => $p->id])}}">
<img class="default-img" src="{{ asset('images/products/'.$p->image) }}" alt="#">
<img class="hover-img" src="{{ asset('images/products/'.$p->image) }}" alt="#">
</a>
<div class="button-head">
<div class="product-action">
#if(Auth::guard('customer')->check())
<span class="favorite-count">{{ $p->favorite_to_customers->count() }}</span>
<a title="Wishlist" href="javascript:void (0);" onclick="document.getElementById('favorite-{{$p->id}}').submit()" class="{{ Auth::guard('customer')->user()->favorite_products()->where('product_id', $p->id)->count() != 0 ? 'favorite' : '' }}">
<i class="fa fa-heart "></i><span>Add to Favorite</span></a>
<form id="favorite-{{$p->id}}" action="{{route('product.favorite', $p->id)}}" method="post">
{{ csrf_field() }}
</form>
#else
<span class="favorite-count">{{ $p->favorite_to_customers->count() }}</span>
<a title="Wishlist" href="javascript:void (0);" onclick="toastr.info('To add favorite list you to need login first', 'info', {
closeButton: true,
progressBar: true
})">
<i class="fa fa-heart "></i>
<span>Add to Favorite</span></a>
#endif
</div>
<div class="product-action-2">
<button style="background: transparent; border: none; color: black" class="btn btn-warning">Add to chart</button>
</div>
</div>
</div>
<div class="product-content">
<h3>{{ $p->Product_Name_ar }}</h3>
<div class="product-price">
<span>{{ $p->Price }} K.D</span>
</div>
</div>
</div>
</form>
</div>
#endforeach
</div>
</div>
</div>
<!--/ End Single Tab -->
</div>
</div>
This Controller
class Favoritecontroller extends Controller
{
public function add($id) {
$customer = Auth::guard('customer')->user();
$isFavorite = $customer->favorite_products()->where('product_id', $id)->count();
if($isFavorite == 0) {
$customer->favorite_products()->attach($id);
}else {
$customer->favorite_products()->detach($id);
}
return redirect()->back();
}
}
This Route
Route::group(['middleware' => ['auth:customer']], function () {
Route::post('favorite/{id}/add', 'FavoriteController#add')->name('product.favorite');
});
I assume your JS fails here
... onclick="document.getElementById('favorite-{{$p->id}}').submit()"
The proper way to do it
... onclick="addToWhishList({{$p->id}})"
Then in your JS
<script>
function addToWhishList(formId) {
//console.log(formId);
document.getElementById('favorite-' + formId).submit();
}
</script>
Check working Demo

Jquery Isotope to implement data filters

I'm first time trying to implement data filter for one of my html template using Jquery Isotope plugin.Couldn't get any error in browser console but data filter doesn't work.
Here's my code:
HTML
<div class="ui-group" style="margin-left: 20%; margin-top: 2%;">
<h3 class="ui-group__title">Filter</h3>
<div class="filters button-group js-radio-button-group">
<button class="button is-checked" data-filter="*"> All </button>
<button class="button" data-filter=".instances"> Instances </button>
<button class="button" data-filter=".images"> Images </button>
<button class="button" data-filter=".deployments"> Deployments </button>
</div>
</div>
<div class="list_of_members">
{% for instance in user.instances.all %}
<div class="orders instances" style="margin-bottom: 2%;">
<div class="icon-text">
<h3>{{ instance.name }}</h3>
<p><b><strong style="color: orange">Server :</strong> </b><br>{{ instance.serverFile }} <br></p><br>
<p><b><strong style="color: orange">Package.json :</strong> </b><br>{{ instance.jsonPackageFile }}</p>
</div>
</div>
{% endfor %}
{% for image in user.images.all %}
<div class="orders images" style="margin-bottom: 2%;">
<div class="icon-text">
<h3>{{ image.tagName }}</h3>
<p><b><strong style="color: orange">Instance :</strong> </b><br>{{ image.instance }} <br></p><br>
<p><b><strong style="color: orange">Created By :</strong> </b><br>{{ image.user.username }}</p>
</div>
</div>
{% endfor %}
</div>
Javascript Part after loading Jquery
<script src="{% static 'js/isotope.pkgd.min.js' %}"></script>
<script>
// Activate isotope with Jquery filter for instances,images and deployments
$('.list_of_members').isotope({
itemSelector: '.orders',
layoutMode: 'fitRows'
});
// Isotope click function
$('.button').click(function(){
$('.button').removeClass('is-checked');
$(this).addClass('is-checked');
var selector = $(this).attr('data-filter');
$('.list_of_members').isotope({
filter: selector
});
return false;
});
</script>
is there any issue in my code or misconfiguration?
help me, please!

How to add a "required" checkbox in this code

I want a checkbox in this code. Only if the checkbox is checked it should be possible to press upload / or to allow a upload.
Could you give me a hint how it's possible to change this?
Actually I can insert a checkbox but it's always uploading if the checkbox is unchecked.
#extends('master/index')
#section('custom')
<!-- Main page -->
<div id="content-wrapper" class="snap-content">
<!-- Progress bar -->
<div class="container progress-holder">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="progress-rate">--%</div>
<div class="progress">
<div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">--% Complete</span>
</div>
</div>
</div>
</div>
</div>
<!-- Drag zone -->
#if($limitReached == true)
<div class="container text-center start-zone">
<p>{{ t('You have reached daily upload limit') }}</p>
</div>
#else
<div class="container text-center start-zone">
<form id="fileupload" action="{{ route('images.upload') }}" method="POST" enctype="multipart/form-data" accept="image/gif, image/jpeg, image/jpg, image/png">
<input type="file" id="input-browse" class="block-hide" multiple="multiple" name="files">
<p>{{ t('Drag photos from your computer in here. Select maximum 10 images') }}</p>
<div class="help-block">{{ t('Maximum file size allowed is') }} {{ maxUploadSize()*1024 < (int)siteSettings('maxImageSize')*(1024) ? maxUploadSize() : (int)siteSettings('maxImageSize') }}MB (o.O)</div>
<p>{{ t('You can also') }} <a class="browse_files" href="#">{{ t('browse') }}</a> {{ t('for photos to upload') }}.</p>
</form>
</div>
#endif
<div class="uploader block-hide">
<!-- Preview zone -->
<div class="container preview-zone">
<img src="{{ asset('static/img/mask-tran.png') }}"/>
</div>
<!-- Thumbnail zone -->
<div class="container thumbnail-zone">
<div class="row">
<div class="col-md-9">
<ul class="thumbnails-holder nav nav-tabs" id="myTab"></ul>
</div>
<div class="actions col-md-3 text-right">
<button type="button" class="btn btn-danger btn-remove"><i class="glyphicon glyphicon-trash"></i> remove</button>
<button type="button" class="btn btn-primary btn-upload"><i class="glyphicon glyphicon-open"></i> upload</button>
<p class="help-block"><span class="readyphoto"></span>/<span class="totalphoto"></span> photos are ready</p>
</div>
</div>
</div>
<!-- Edit zone -->
<div class="container-fluid tab-content edit-zone-holder"></div>
</div>
</div>
You can do this with JavaScript using the onchangeevent event to enable/disable button based on checked value
<input type="checkbox" onchange="document.getElementById('uploadButton').disabled = !this.checked;" />
<input type="submit" id="uploadButton" value=" Upload " />
you can disable and enable buttons with jQuery depending on the checkbox selection.
If you have:
<input type="checkbox" id="checkbox"/>
<button id="upload">Upload</button>
Then in your jQuery:
$("#upload").prop('disabled', true);
$("#checkbox").bind('change', function(){
var checked = this.checked;
if(checked){
$("#upload").prop('disabled', false);
} else {
$("#upload").prop('disabled', true);
}
});
JSFiddle
add a checkbox
<input type="checkbox" name="chk" id="chk" value="yourvalue">
add onclick event in your upload button
<button type="button" onclick="selected()">upload</button>
<script>
function selected()
{
if(document.getElementById('chk').checked) {
document.getElementById("fileupload").submit();
} else {
alert('YOUR CUSTOM MESSAGE');
}
}
</script>
Try this:
Add this in your html form.
<input type="checkbox" name="writeSomeName" value="value">
Then after that write some php code:
if ($_POST['writeSomeName'] == 'value')
{
//Add code for upload file here
}
else
{
echo "You have not checked the checkbox. Please make it check first"
}

Categories