HTML required functions with javascript which required function doesnt work - javascript

Can anyone help me with this required function doesnt work. i am uploading a picture in my html/php web page and before i upload a picture i set a dropdown option which is to upload or not, and this is my code:
<script>
function papeles()
{
var x = document.getElementById('tagoan1').value;
if (x == "YES")
{
// alert('aaaa');
$('#imgInp').addClass("required");
$('#imgInp').removeClass("hidden");
$('#blah').removeClass("hidden");
} else
{
//alert('bbbbb');
$('#imgInp').addClass("hidden");
$('#imgInp').removeClass("required");
$('#blah').addClass("hidden");
}
}
</script>
<div class="col col-sm-5">
<label>Attachment </label>
<select class="form-control" id="tagoan1" name="taguan" onchange="papeles()" required disabled>
<option value="">With Attachment?</option>
<option value="YES">Yes</option>
<option value="NO">No</option>
</select>
</div>
<div class="row text-center">
<div class="col col-sm-6">
<div class="form-group" style="margin:0;">
<input type='file' name="image" id="imgInp" value="" class="hidden required btn btn-block btn-sm" style="padding-left:3em;width:300px"/>
</div>
<img id="blah" src="customer/tagoan/images/noimage.png" height="200px" width="300px" name="tae" border-color="white" placeholder="" class="hidden"/>
</div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function () {
readURL(this);
});
</script>
The problem is that when i click yes but i dont choose a file, the picture will still submit it should not submit because of the add class required how to solve this.

when you hide an input, it is not removed from the page. So, the file input stays in the form, and sumbitted regardless if it's hidden or not. What you need is to remove the input from DOM:
if (x == "YES")
{
$('#imgInp').remove() // file input gone
$('#blah').removeClass("hidden");
} else
{
//you should add an ID to the parent of imgInp instead of referring as .form-group
$('.form-group').prepend("<input type='file' name='image' id='imgInp' value='' class='required btn btn-block btn-sm' style='padding-left:3em;width:300px'/>")
$('#blah').addClass("hidden");
}

is it okay if you just use .hide() and .show() of jQuery?

Related

How to Upload image with some field?

I am trying to upload image with some required field like name, description. When i am inserting data without the image field it works, but when trying to upload the image file as well its not inserting data to database. Could anyone tell me what may be wrong with my code?
Controller
public function store(Request $request)
{
$this->validate($request, [
'cat_name' => 'required|max:255',
'description' => 'required|min:6',
'cat_pic' => 'required|image|mimes:jpg,jpeg,png',
]);
$fileName = null;
if ($request()->hasFile('cat_pic')) {
$file = $request()->file('cat_pic');
$fileName = time().'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('/uploads/products/cats/');
$file->move($destinationPath, $fileName);
$this->save();
}
Catagories::create([
'cat_name' => $request->input('cat_name'),
'description' => $request->input('description'),
'cat_pic' => $fileName,
]);
Session::flash('alert', __('messages.created'));
Session::flash('alertClass', 'success');
return redirect()->route('catagories');
}
View
<div class="col-md-4 offset-5">
<div class="form-group">
<form role="form" action="<?php echo e('/products/cats') ?>" method="POST" id="createcat" >
{{ csrf_field() }}
<p>
Create New Product Category
</p>
<div class="form-group">
<label for="cat_name">
Name*:</label>
<input type="text" class="form-control"
id="cat_name" name="cat_name" required maxlength="50">
</div>
<div class="form-group">
<label for="cat_pic">Category Image* </label>
<input data-preview="#preview" class="form-control" name="cat_pic" type="file" id="cat_pic">
<img class="col-md-6" id="preview" height="100px" width="20px" src="">
</div>
<div class="form-group">
<label for="description">
Description*:</label>
<textarea class="form-control" type="textarea" name="description"
id="description" placeholder="Category Description"
maxlength="600" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-lg btn-success btn-block" id="btncreatecat">Create</button>
</form>
</div>
</div>
#endsection
#push('scripts')
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#cat_pic").change(function(){
readURL(this);
});
</script>
Route
Route::resource('products/cats', 'Admin\CatController');
and some JQuery to preview the image
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#cat_pic").change(function(){
readURL(this);
});
</script>
you need to add enctype="multipart/form-data" to the <form> tag.
Like this:
<form role="#" action="#" method="#" id="#" enctype="multipart/form-data">
So your form can send other things than text.
I realized the problem is I just forgot to add enctype="multipart/form-data" inside the form tag.

Laravel Dropzone without class form Invalid element

i am trying to make a multiple upload with dropzone on laravel and i take a look on documentation of dropzone.
The example must be using form and give class dropzone , here my case i want to use dropzone and others text field
and got error Uncaught Error: Invalid dropzone element. here is the screenshot : error screenshot
here is my html code :
<form method="POST" action="/backend/blog" enctype="multipart/form-data" id="formku">
<div class="form-group label-floating">
<label class="control-label">Title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group label-floating">
<label class="control-label">Written By</label>
<input type="text" name="written_by" class="form-control">
</div>
<div class="form-group" id="place_image" style="display: none;">
<img src="" id="image_category" style="width: 95px;height: 50px;">
</div>
<div class="form-group">
<a class="btn btn-primary" id="btn_choose_image" onclick="$('#choose_image').click();">Choose Image</a>
<input style="display: none;" type="file" id="choose_image" name="image"></input>
</div>
<textarea id="bodyField" name="description"></textarea>
#ckeditor('bodyField', ['height' => 250])
<div class="form-group label-floating">
<div class="row">
<label class="control-label">Category</label>
<select class="selectpicker" data-style="btn btn-primary btn-round" title="Single Select" data-size="7" name="category">
<option disabled selected>Choose Category</option>
#foreach( $categories as $key => $category):
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach;
</select>
</div>
</div>
<div class="dropzone" id="imageUpload">
<h3>Upload Multiple Image By Click On Box</h3>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="status"> Status
</label>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-fill btn-rose" value="Submit">
</form>
and here is my JS code :
Dropzone.autoDiscover = false;
var imageUpload = new Dropzone("div#imageUpload", {
url: "dropzone/store",
autoProcessQueue:false,
uploadMultiple: true,
maxFilesize:5,
maxFiles:3,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
init: function() {
var submitButton = document.querySelector("#submit-all")
//imageUpload = this; // closure
submitButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
imageUpload.processQueue(); // Tell Dropzone to process all queued files.
});
// You might want to show the submit button only when
// files are dropped here:
this.on("addedfile", function() {
// Show submit button here and/or inform user to click it.
});
}
});
anyone have solution of this trouble ?
You could try to check if the imageUpload element is there first :
Dropzone.autoDiscover = false;
if (document.getElementById('imageUpload')) {
var imageUpload = new Dropzone("div#imageUpload", {
url: "dropzone/store",
autoProcessQueue:false,
uploadMultiple: true,
maxFilesize:5,
maxFiles:3,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
init: function() {
var submitButton = document.querySelector("#submit-all")
//imageUpload = this; // closure
submitButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
imageUpload.processQueue(); // Tell Dropzone to process all queued files.
});
// You might want to show the submit button only when
// files are dropped here:
this.on("addedfile", function() {
// Show submit button here and/or inform user to click it.
});
}
});
}

Submit form not working when using jQuery

I have a form and when the user clicks submit, I would like the form to hide and a thank you message to appear. Unfortunately with the code I have, it's not working and I can't figure out why. I think it might be something with the jQuery so I'd like to try and re-write this function using vanilla JS, but I'm not sure how.
It is the last part of the function, the if (empty.length), hide form, show thank you message that is causing me problems. Everything else is working fine, so its this function I would like to try and write in JavaScript, or try another way using jquery to make it work. The problem is it doesn't work in my code, but when I open this in a jsfiddle, it doesnt just hide the form it opens a new page and I get an error. I don't want the user to be directed to a new page, I just want the form to close and thank-you message to appear. I am very new to this so I apologize if my code is messy.
UPDATE: I really think the issue here is the jQuery, can I write this in plain JS and would that fix it?
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
})
var $form = $('#signup-form'),
$signupForm = $('.form-show'),
$formReplace = $('#thank-you');
$formReplace.hide();
$form.on('submit', function() {
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if (empty.length <= 0) {
$signupForm.hide();
$formReplace.show();
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-subscribe">Show / hide form</button>
<div id="subscribe-content">
<div class="subscription-signup">
<div class="subscription-close" id="subscription-close"></div>
<div class="email-signup">
<p class="cat-title subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<div class="subscription-form">
<form id="signup-form" class="form-show" name="signup-form" method="post" action="${URLUtils.url('Newsletter-SubscribeMobile')}">
<div class="form-row salutation header">
<label for="salutation">Title</label>
<div class="chzn-row valid salutation">
<select id="title" name="title" class="chzn-global-select input-select optional required">
<option value="">--</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss</option>
</select>
</div>
</div>
<div class="form-row required">
<label for="firstname">
<span aria-required="true">First Name</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="firstname" type="text" name="firstname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="lastname">
<span aria-required="true">Surname</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="lastname" type="text" name="lastname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="signup-email" style="display:none;">Email</label>
<input class="header-signup-email" type="text" id="signup-email-header" name="signup-email" value="" placeholder="Email" />
</div>
<div class="form-row text-center">
<input type="submit" name="signup-submit" id="signup-submit" class="subscribe-submit" value="Submit" />
</div>
</form>
<div id="thank-you">
<p>Thanks for subscribing!</p>
</div>
</div>
</div>
</div>
</div>
I think some other javascript/jQuery code are making issues to run the codes, for simple solution make your code as plugin and called it like following.
create new js file called validation.js
(function($){
$.fn.validation = function(){
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
var $form = $('#signup-form'), $signupForm = $('.form-show'), $formReplace = $('#thank-you'); $formReplace.hide();
this.on('submit', function(e){
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if(empty.length == 0){
$signupForm.hide();
$formReplace.show();
}
e.preventDefault();
});
};
})(jQuery);
Now, call the validation.js at the head like below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="validation.js"></script>
<script type="text/javascript">
$(function(){
$('#signup-form').validation();
});
</script>

How to specify minlength in jquery?

If the status value is completed then comment field is required is working good.But the problem is, I want to specify comment field is required for minimum of 50 character.
The Below code: index.php
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="selectbasic">Status</label>
<div class="col-md-4">
<select id="status" name="status[]" class="form-control" >
<option value="Pending">Pending</option>
<option value="Work in process">Work in process</option>
<option value="Completed">Completed</option>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Comment</label>
<div class="col-md-4">
<input id="commentss" name="comment[]" type="text" placeholder="" class="form-control input-md" />
</div>
</div>
<div class="col-md-8 col-sm-12 col-24">
<div class="input_fields" style="color:black">
<button class="add_field btn " onclick="incrementValue()" >Add More</button>
<div>
<input type="text" name="mytextt[]" hidden="" ></div>
</div>
</div>
Javascript
<script type="text/javascript">
$(document).ready(function () {
$("#status").click(function () {
if ($("#status").val() == "Completed") {
$("#commentss").attr("required", "required");
}
else
$("#commentss").attr("required", false);
});
});
</script>
Use length to find the length of the string
if($('#commentss').val().length < 50){
alert("Please enter 50 characters atleast");
} else {
//submit
}
For this please use below code :
<script type="text/javascript">
$(document).ready(function () {
$("#status").click(function () {
var commenttext = document.getElementById('commentss').value;
if (commenttext.length < 50)
{
alert("Please Enter minimum 50 character!")
}
else
{
//Add code
}
});
});
</script>
In Jquery ...
For Dynamic Tracking ...
(You can use blur or keyup even too.)
$(function() {
//disable submit if you want to
$('#commentss').on('input', function(e) {
if(this.value.length >= 50) {
//success
} else {
//fail?
}
});
});
To Validate on Click only ...
Go with the answer of Thamaraiselvam.

Validate div is not empty with jquery

I need to validate that both the text input, .search-results div within the "Current Images" fieldset and dropdown selection are all not empty. I have the logic for the text input and dropdown working, but can't figure out why the empty div logic is not working:
<div class="input-group col-md-6">
<input type="text" class="form-control" placeholder="Search by Asset ID" maxlength="64" class="form-control" id="imageid" name="imageid"> <span class="input-group-btn">
<button class="btn btn-default image-search" type="button">Search</button>
</span>
</div>
<fieldset class="scheduler-border">
<legend class="scheduler-border">Current Images</legend>
<div class="scheduler-broder">
<div class="search-results"></div>
</div>
</fieldset>
</div>
<div class="form-group">
<label for="image">Select Asset Type:</label>
<select id='crop' class="btn btn-default" data-toggle="dropdown">
<option value="default">Choose Type</option>
<option value="now">Now</option>
<option value="livefeeds">Live Feeds</option>
</select>
</div>
<div class="form-group">
<label for="imageid">Select an image</label>
<input type="file" name="file" class="btn btn-default form-control" id="file" accept="image/jpg, image/png, image/jpeg" />
</div>
function checkForInputs() {
var filledUp = $("#imageid").val() != '' && $("#crop").val() != "default" && $(".search-results").val() != '';
if (!filledUp) {
$("#file").attr("disabled", true);
} else if (filledUp) {
$("#file").attr("disabled", false);
}
}
$("#imageid").keyup(function () {
checkForInputs();
});
$("#crop").change(function () {
checkForInputs();
});
checkForInputs();
JSfiddle: link
Use $(".search-results").text() instead of $(".search-results").val()
Do the same for all the elements that don't belong to a form, like div, span, p, etc.
Take a look at the doc: http://api.jquery.com/val/
Method .val() as it described on jquery website:
Get the current value of the first element in the set of matched elements or set the value of every matched element.
You should use .text() instead of .val()
In this case your validation should be
var filledUp = $("#imageid").val() != '' && $("#crop").val() != "default" && $(".search-results").text() != '';
So this jsfiddle is working
you can use
if($('#mydiv').html().length() == 0)
{
//do something
}
this is for compare with empty value
other way to do this task is compare with function "children", example.
if($('.search-results').children.length == 0)
{
// dosomething
}
good luck !

Categories

Resources