Cannot read property '0' of undefined input file in bootstrap module window - javascript

I am trying to create a form inside a Bootstrap modal. it should contain the input file field and preview a chosen image, so I can use Jcrop to crop the image.
So here is what am I doing now:
<script type="text/javascript">
$('#new-menu').on('shown.bs.modal', function (event) {
var modal = $(this);
var src = modal.find(".modal-body .upload");
var target = modal.find(".image");
src.bind("change", function () {
// fill fr with image data
modal.find(".jcrop-holder").remove();
readUrl(modal,target,src);
initJcrop(target);
});
});
function readUrl(modal,target,src){
if (src.files && src.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
target.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
initJcrop(target, modal);
}
else alert(src.files[0]);
}
}
function showCoords(c) {
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
}
function initJcrop(img) {
jcrop_api = $.Jcrop(img);
jQuery(img).Jcrop({
aspectRatio: 16 / 9,
onChange: showCoords,
setSelect: [0, 90, 160, 0],
onSelect: showCoords
}, function () {
modal.find(".jcrop-holder").css({
left: "50%",
marginLeft: -img.width / 2 + "px"
});
});
}
</script>
But i get this error
'Cannot read property '0' of undefined'
HTML
<form action="place/{id}/new/service/">
<div class="input-group">
<img src="http://placehold.it/160x90" class="image"/>
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">
<i class="glyphicon glyphicon-apple"></i>
</span>
<input type="text" id="form-name" class="form-control"
placeholder="Назва" value="" aria-describedby="basic-addon1"/>
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon2">
<i class="fa fa-tag"></i>
</span>
<input type="number" id="form-price" class="form-control"
placeholder="Ціна" value="" aria-describedby="basic-addon1"/>
<span style="padding:2px 5px" class="input-group-addon"><i>.грн</i></span>
</div>
<div class="input-group">
<textarea class="form-control place_description" style="resize: none" rows="5"
placeholder="Короткий опис послуги"></textarea>
</div>
<div style="text-align: center">
<small class="description-info">Залишилося 160 символів</small>
</div>
<div class="input-group">
<input type="file" class="upload"/>
</div>
<button id="new-service" class="btn btn-primary" type="submit">Зареєструвати</button>
</form>

The src you are passing in function readUrl(modal,target,src) is a jQuery element when you need is to access the DOM element. Have
src.get(0).files && src.get(0).files
Instead of
src.files && src.files[0]

Related

JQuery File Input - Read image width & height

I'm trying to read (input type="file") image file's original width / height. My code gives me "undefined". I suppose because i'm not loading image to server or anywhere.
Here is my code;
<script>
$( document ).ready(function() {
$('#texture_modal').click(function () {
var texture_name = $('#texture_name').val();
var thumb_img = $('#thumb_img').val().replace(/^.*\\/, "");
var big_img = $('#big_img').val().replace(/^.*\\/, "");
var real_img = $('#real_img').val().replace(/^.*\\/, "");
var img_size = document.getElementById("real_img").files[0].size / (1024*1024); // Get real_img size in MB
var texture_size = img_size.toFixed(2); // get rid of decimals in real_img size MB
var texture_category = $('#texture_category').val();
var texture_description = $('#texture_description').val();
// THIS IS THE STUFF WHICH I WANT TO GET IMAGE WIDTH
var texture_dim = document.getElementById("real_img").naturalWidth;
console.log(texture_dim);
}); //End click function
}); //End document ready
</script>
And here is my input fields. I have multiple file inputs, whichs are for thumbnail image, big image and real image. I need real image width only, others will be upload to server. Here is my input fields;
<!-- this fields are inside a bootstrap modal -->
<div class="modal-body">
<div class="input-group input-group-sm">
<div class="input-group-prepend">
<span class="input-group-text"><small>Texture Name</small></span>
</div>
<input type="text" class="form-control" id="texture_name">
</div>
<div class="form-group pt-1">
<small>Thumbnail Img(200*200)</small>
<input type="file" class="form-control form-control-sm" id="thumb_img">
<small>Big Img(445*445)</small>
<input type="file" class="form-control form-control-sm" id="big_img">
<!-- this one i want to take width without post or upload anywhere -->
<small>Real Img</small>
<input type="file" class="form-control form-control-sm" id="real_img">
<!-- taking categories with php function -->
<small>Category</small>
<select id="texture_category" class="form-control form-control-sm">
<option selected disabled>----- Choose a Category -----</option>
<?php foreach($texture_categories as $key){?>
<option><?php echo $key; ?></option>
<?php } ?>
</select>
<small>Description :</small>
<textarea id="texture_description" class="form-control form-control-sm"></textarea>
</div>
</div>
can you try to assign an Image and get it
var fileUpload=document.getElementById("photoInput");
function Test(){
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var width = this.naturalWidth || this.width;
var height = this.naturalHeight || this.height;
console.log(height,width)
}
};
}
<div class="photo">
<input type="file" name="photo" id="photoInput" onchange="Test(this)"/>
</div>
in your example
$( document ).ready(function() {
$(".modal").modal()
});
function Test(){
var fileUpload=document.getElementById("thumb_img");
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var width = this.naturalWidth || this.width;
var height = this.naturalHeight || this.height;
console.log(height,width)
}
};
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<!-- this fields are inside a bootstrap modal -->
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="input-group input-group-sm">
<div class="input-group-prepend">
<span class="input-group-text"><small>Texture Name</small></span>
</div>
<input type="text" class="form-control" id="texture_name">
</div>
<div class="form-group pt-1">
<small>Thumbnail Img(200*200)</small>
<input type="file" class="form-control form-control-sm"onchange="Test(this)" id="thumb_img">
<small>Big Img(445*445)</small>
<input type="file" class="form-control form-control-sm" id="big_img">
<!-- this one i want to take width without post or upload anywhere -->
<small>Real Img</small>
<input type="file" class="form-control form-control-sm" id="real_img">
<!-- taking categories with php function -->
<small>Category</small>
<select id="texture_category" class="form-control form-control-sm">
<option selected disabled>----- Choose a Category -----</option>
<?php foreach($texture_categories as $key){?>
<option><?php echo $key; ?></option>
<?php } ?>
</select>
<small>Description :</small>
<textarea id="texture_description" class="form-control form-control-sm"></textarea>
</div>
</div>
</div>
</div>
</div>

I can't reset input file inside form after submit

I have a form with some fields and after submit finish i want to reset whole form but only reset input text areas not input type file.
I check every similar questions and solutions but none of them work for me.Some solutions refresh page which i don't want that.
<form class=" dropzone px-5" id="mydropzone">
<h2 class="text-center">Lets create your menu</h2>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCalories">Calorie</label>
<input type="text" class="form-control" id="inputCalories" required>
</div>
<div class="form-group col-md-6">
<label for="cc">Calorie Calculator</label>
<button id="cc" class="btn btn-primary btn-lg"><i class="fas fa-calculator mr-2"></i>Click Me</button>
</div>
</div>
<div class="form-row">
<div class="form-group ml-2 col-sm-6">
<label>Menu Item Image</label>
<div id="msg"></div>
<div class="progress" id="uploader">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%"></div>
</div>
<input type="file" name="img[]" class="file" accept="image/*" id="fileButton">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file" required>
<div class="input-group-append">
<button type="button" class="browse btn btn-primary"><i class="fas fa-folder-open mr-2"></i>Browse...</button>
</div>
</div>
<div class="ml-2 col-sm-6">
<img src=" " id="preview" class="img-thumbnail">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block mb-3">Submit Menu</button>
<!-- -------------------------------------------------------------------------- -->
</div>
</form>
And my create menu which clear all fields after form submit.
// create menu
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file = e.target.files[0];
var storageRef = firebase.storage().ref('foodImg/' + file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
console.error(error);
}, function() {
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
const createMenuForm = document.querySelector('#mydropzone');
createMenuForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('restaurants').add({
foodLine: {
menuTitle: createMenuForm.menuTitle.value
},
food: {
foodName: createMenuForm.foodName.value,
imageURL: downloadURL,
inputCalories: createMenuForm.inputCalories.value,
menuItemDescription: createMenuForm.menuItemDescription.value,
menuItemInfo: createMenuForm.menuItemInfo.value
}
}).then(() => {
//reset form
createMenuForm.reset();
fileButton.value = "";
var preview = document.getElementById('preview');
preview.value = "";
}).catch(err => {
console.log(err.message);
});
});
});
});
});
Can you try these things also
document.getElementById("myForm").reset();
$("#myForm").trigger("reset");
I think you try to access createMenuForm outside the scope where const createMenuForm was declared.
Try to declare it above the event listener:
// create menu
const createMenuForm = document.querySelector('#mydropzone');
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// ...
or directly with
document.querySelector('#mydropzone').reset();
i debug and find that preview need to be clean
document.getElementById("preview").src = "#";

issue in Bootstrap 4 validation on select field

I'm new to jQuery and Bootstrap, I'm using jquery and Bootstrap 4 for validation of my form modal, whenever there is an error it must show the error below the corresponding fields, but in my case the select field gets overwritten by the error and select field disappears but it works fine for input field.
here have a look and if you want to have a close look on image just click on it..
As you can see the select fields get overwritten by the fieldError but it's fine for input field.
here's my jQuery validation code:
$(function(){
setCategorySelect();
$(document).on('shown.bs.modal','#manageItemsModal', function () {
$('#manageItemsModal #btnSubmit').on('click', function(){
if (validateForm()) {
messageSuccess("Very well");
} else {
messageError("Oops!!");
}
});
});
});
function validateForm() {
var validationStatus = true;
if ($('#manageItemsForm #selectedCategory').val().length == 0) {
showFieldError(('#manageItemsForm #selectedCategory'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedCategory').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBrandModel').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBrandModel'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBrandModel').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #serialNo').val().length == 0) {
showFieldError(('#manageItemsForm #serialNo'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #serialNo').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedVendor').val().length == 0) {
showFieldError(('#manageItemsForm #selectedVendor'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedVendor').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBranch').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBranch'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBranch').focus() };
validationStatus = false;
}
return validationStatus;
}
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
function setCategorySelect() {
var $categorySelect = $('#manageItemsForm #selectedCategory').selectize({
selectOnTab: true,
closeAfterSelect: true,
persist: false,
create: false,
valueField: 'id',
labelField: 'text',
options: [],
preload: true,
onInitialize : function() {
var self = this;
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: '*'
},
error: function() {
callback();
},
success: function(res) {
self.addOption(res.data);
}
});
},
load: function(query, callback) {
if (query.length <= 2) return callback();
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: query + "*"
},
error: function() {
callback();
},
success: function(res) {
console.log(res.data);
callback(res.data);
$categorySelect.refreshItems();
},
fail : function() {
callback();
}
});
}
});
}
here's my HTML:
<div class="modal-body">
<form id="manageItemsForm">
<input type="hidden" id="id" name="id">
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="selectedCategory" class="col-form-label"><span class="text-danger">* </span>Category</label>
<select class="form-control" name="selectedCategory" id="selectedCategory"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="selectedBrandModel" class="col-form-label"><span class="text-danger">* </span>Brand & Model</label>
<select class="form-control" name="selectedBrandModel" id="selectedBrandModel"></select>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">* </span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="description" class="col-form-label">Description</label>
<input type="text" class="form-control" id="description" name="description">
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Vendor</label>
<select class="form-control" name="selectedVendor" id="selectedVendor"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="supportTillDate" class="col-form-label"><span class="text-danger">* </span>Support till date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="supportTillDate" name="supportTillDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-9">
<div class="form-group">
<label for="selectedBranch" class="col-form-label"><span class="text-danger">* </span>Branch</label>
<select class="form-control" name="selectedBranch" id="selectedBranch"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<label for="purchasePrice" class="col-form-label">Purchase Price</label>
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text input-group-addon" style="padding: 0.4rem 0.75rem 0.3rem 0.75rem;">₹</span></div>
<input id="purchasePrice" name="purchasePrice" type="text" class="form-control" aria-label="Amount" style="text-align:right;">
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="btnSubmit" type="button" class="btn btn-primary">Save</button>
</div>
</div>
By the way I am using jQuery in Spring boot and everything is working fine(save, update, delete) except for validation from jQuery.
Please help!!
I can't see working code because you using some external references like selectize.
I suggest you get used to "snippets" to provide code.
Bytheway, your problem seems to be just about styles. I can't know, but my bet is you just need to provide a css style for
.select::after.error {
color:red;
}
You can inspect and copy CSS code.
The problem is in Your HTML, the nodes of your .input-group does not have allways the same structure. In some cases you have .invalid-feedback just after the input such as this HTML
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">*
</span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
For other fields the .invalid-feedback isn't after the input but outside from .form-group. take a look
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div class="invalid-feedback"></div>
This difference in HTML structure of the form made your showFieldError() and clearFieldError() not working allways as you expected, because $(element).next() don't catch the right DOM node for insert/remove the validation message. So in some cases clearFieldError remove the wrong HTML tag and this can make your selects disappear
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
So you have to fix Your HTML to obtain the same structure for all fields. Put the <div class="invalid-feedback"></div> allways just below the select or input field. Otherwise you have to change the selector that you pass to showFieldError() and clearFieldError() functions according to your HTML
Otherwise a simply approach is to add a ID to divs with class .invalid-feedback, an ID which you can easily manage by his related input ID, something like
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div id="purchaseDate_err_mex" class="invalid-feedback"></div>
in this way you can pass the input name to your functions and them becomes
function showFieldError(input_id, message) {
$('#'+input_id).addClass('is-invalid');
$('#'+ input_id +'_err_mex').html(message).show();
}
function clearFieldError(input_id) {
$('#'+input_id).removeClass('is-invalid');
//$('#'+input_id).removeAttr('required');
/* don't need to remove required attribute from mandatory fields */
$('#'+ input_name +'_err_mex').html('').hide();
}
and the validation function
function validateForm() {
var validationStatus = true;
if ($('#selectedCategory').val().length == 0) {
showFieldError('selectedCategory', 'Must not be blank');
if (validationStatus) { $('#selectedCategory').focus() };
validationStatus = false;
}
........
return validationStatus;
}
You only check if the length of all fields is more than 0, so you can validate the entire form within a loop
function validateForm() {
var validationStatus = true;
var form_inputs = $('#manageItemsForm input, #manageItemsForm select')
$.each(form_inputs,function(){
var input_id = $(this).attr('name');
clearFieldError(input_id);
if ($.trim($(this).val()).length == 0 && $(this).is("[required]")) {
showFieldError(input_id, 'Must not be blank');
if (validationStatus) { $('#'+input_id).focus() };
validationStatus = false;
}
});
return validationStatus;
}

Passing Data from Kendo UI Command Buttons

I have a kendo grid with 6 command buttons on each row, with the structure below, but calling different functions. I'm looking for a way to pass data down to the function, based on which button is pressed. Right now, I have 6 functions on the java side and 6 popups on the aspx side. I'm not even sure it can be done, but it's just a lot of duplicated code. Here's the command structure for each button:
command: [{
name: "Edit",
title: "Alert Email",
width: "180px",
click: onDataBound75
}],
This is one of the 6 functions:
function onDataBound75(e) {
e.preventDefault();
$("#txtAlert").kendoEditor({
resizable: {
content: true,
toolbar: true,
encoded: false
}
});
var window = $("#emailAlert_popup").kendoWindow({
width: "600px",
visible: false,
modal: true,
actions: [
"Maximize",
"Close"
],
});
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var viewModelAlert75 = kendo.observable({
Alert75EmailSubject: dataItem.Alert75EmailSubject,
Alert75EmailBody: dataItem.Alert75EmailBody,
Alert75FromAddress: dataItem.Alert75FromAddress,
});
kendo.bind($("#emailAlert_popup"), viewModelAlert75);
window.data("kendoWindow").center().open();
};
And here is one of the 6 popups for the aspx side:
<div id="emailAlert_popup" class="TT_PopupWindow">
<div class="SearchParam">
<label class="control-label" for="txtAlert75EmailSubject" style="width:200px">Email Subject</label>
<input name="txtEmailSubject" id="txtAlert75EmailSubject" class="k-textbox" style="width:430px"
data-bind="value: Alert75EmailSubject" />
</div>
<div class="SearchParam">
<label class="control-label" for="txtAlert75EmailBody" style="width:200px">Email Body</label>
<textarea id="txtAlert" rows="10" cols="30" style="height:440px" aria-label="editor" data-bind="value: Alert75EmailBody"></textarea>
</div>
<div class="SearchParam">
<label class="control-label" for="txtAlert75FromAddress" style="width:200px">From Address</label>
<input name="txtFromAddress" id="txtAlert75FromAddress" class="k-textbox" style="width:430px"
data-bind="value: Alert75FromAddress"
/>
</div>
<div class="k-edit-buttons k-state-default">
<button type="button" id="btnAlert75EmailUpdate" data-role="button" class="k-button k-button-icontext k-primary k-grid-update" role="button" aria-disabled="false" tabindex="0" style="float:right"><span class="k-icon k-i-check"></span>Update</button>
<button type="button" id="btnAlert75Cancel" data-role="button" class="k-button k-button-icontext k-grid-cancel" role="button" aria-disabled="false" tabindex="1" style="float:right"><span class="k-icon k-i-cancel"></span>Cancel</button>
</div>
</div>
Is there a way to have only 1 javascript function passing data over to the aspx side and only 1 popup on the aspx page?
I figured out how to do it, for anyone else looking for the same scenario. This is how I achieved it with 1 function and 1 kendowindow:
command: [{
name: "Alert75Edit",
title: "Alert Email",
width: "180px",
click: AlertEmails
}],
DataSource:
DataSources = {
EditorWindow:{
EmailSubject:null,
EmailBody:null,
EmailFromAddress:null
}
};
Single function:
function (e) {
e.preventDefault();
var AlertType = e.data.commandName.replace("Edit", "");
if (!$("#txtAlertEmailBody").data("kendoEditor")) {
$("#txtAlertEmailBody").kendoEditor({
resizable: {
content: true,
toolbar: true,
encoded: false
}
});
}
var window = $("#emailAlert_popup").kendoWindow({
width: "600px",
visible: false,
modal: true,
actions: [
"Maximize",
"Close"
],
});
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
EditorWindow.EmailSubject = dataItem[AlertType + "EmailSubject"];
EditorWindow.EmailBody = dataItem[AlertType + "EmailBody"];
EditorWindow.EmailFromAddress = dataItem[AlertType + "FromAddress"];
var viewModelAlert = kendo.observable({
AlertEmailSubject: EditorWindow.EmailSubject,
AlertEmailBody: EditorWindow.EmailBody,
AlertFromAddress: EditorWindow.EmailFromAddress,
});
kendo.bind($("#emailAlert_popup"), viewModelAlert);
window.data("kendoWindow").center().open();
};
Single kendoWindow popup in aspx file:
<div id="emailAlert_popup" class="TT_PopupWindow">
<div class="SearchParam">
<label class="control-label" for="txtAlertEmailSubject" style="width:200px">Email Subject</label>
<input name="txtEmailSubject" id="txtAlertEmailSubject" class="k-textbox" style="width:430px"
data-bind="value: AlertEmailSubject" />
</div>
<div class="SearchParam">
<label class="control-label" for="txtAlertEmailBody" style="width:200px">Email Body</label>
<textarea id="txtAlertEmailBody" rows="10" cols="30" style="height:440px" aria-label="editor" data-bind="value: AlertEmailBody"></textarea>
</div>
<div class="SearchParam">
<label class="control-label" for="txtAlertFromAddress" style="width:100px">From Address</label>
<input name="txtFromAddress" id="txtAlertFromAddress" class="k-textbox" style="width:430px"
data-bind="value: AlertFromAddress"
/>
</div>
<div class="k-edit-buttons k-state-default">
<button type="button" id="btnAlertCancel" data-role="button" class="k-button k-button-icontext k-grid-cancel" role="button" aria-disabled="false" tabindex="1" style="float:right; margin:5px"><span class="k-icon k-i-cancel"></span>Cancel</button>
<button type="button" id="btnAlertEmailUpdate" data-role="button" class="k-button k-button-icontext k-primary k-grid-update" role="button" aria-disabled="false" tabindex="0" style="float:right; margin:5px"><span class="k-icon k-i-check"></span>Update</button>
</div>
</div>

Get the ID of the label associated with the input type file field

I have a requirement where I have to get the ID of the label associated with the input type file field. I have a set of 4 input type file fields with id's photo1, photo2, photo3, photo4. The labels associated with these file fields are label-1, label-2, label-3 and label-4 respectively. My requirement is that I want to get the respective label fields and update the text of the label. This is what I have tried so far.
<div class="koh-contact-photo">
<span><fmt:message key='photo1' /></span> <label id="upload-1" class="button-default" ><fmt:message
key='photo.upload' /></label>
<div id="preview-1" class="preview"></div>
<button type="button" class="koh-photo-remove remove-button">
<span class="icon" data-icon="&#xe605"></span> <span
class="label"><fmt:message key='photo.remove.text' /></span>
</button>
<!-- The Modal -->
<div id="myModal1" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<h3 class="modal-title"> Upload Photo </h3>
<div class="modal-inner">
<span>Browse for a photo</span> <label id="label-1" style="margin-bottom:20px;" class="button-default browse" for="photo1">BROWSE</label><input id="photo1" type="file"
name="photo1" data-parsley-filesize="3"
data-parsley-filetype="image/jpeg, image/png, image/gif, image/bmp"
data-parsley-trigger="change" />
<hr class="modal-hr" />
<div class="guidelines-modal">
<p> GENERAL GUIDELINES </p>
<p> Supported files are: .jpg, .gif, .png, .bmp </p>
<p> Maximum File Size: 3MB</p>
<p style="margin-bottom:10px;"> For best results: upload at 400 x 300</p>
<p> Note: images are automatically resized</p>
</div>
<div class="koh-contact-captcha modal-hr">
<!--div class="g-recaptcha" data-sitekey=<fmt:message key='kohlerSterling.google.captcha.key' />></div-->
<!--div class="g-recaptcha" id="recaptcha1"></div-->
<div id="recaptcha3" class="captcha"></div>
<div class="error-message">
<span><fmt:message key='required.field.text' /></span>
</div>
</div>
<div class="terms-modal">
<div class="checkbox">
<input type="checkbox" id="terms-condns" required/>
<label style="font-family:Helvetica Neue LT Pro Roman !important;font-size:12px !important;color:#000 !important;font-weight:400 !important;" for="terms-condns">I agree to the <a class="modal-anchor" href="#">Terms and Conditions</a></label>
</div>
</div>
<hr class="modal-hr" />
<div class="modal-buttons">
<label class="button-default-modal" style="margin-right:20px;">CANCEL</label>
<label id="input-button-modal-1" class="input-button-modal">UPLOAD</label>
</div>
</div>
</div>
<input type="hidden" id="captchaKey" value="<fmt:message key='google.recaptcha.site.key'/>">
</div>
</div>
I have 4 such div classes. and this is the javascript.
$contactPhotos.each(function () {
var $photoInput = $(this).find("input[type=file]");
var img = $("<img />");
var photoPreview = $photoInput.parent().parent().parent().parent().find(".preview").attr("id");
var photoPreviewImg = $("#" + photoPreview);
function readURL(input) {
if (input.files && input.files[0]) {
photoPreviewImg.html("");
//alert(JSON.stringify(photoPreviewImg, null, 4));
var reader = new FileReader();
reader.onload = function (e) {
img.attr("style", "height:41px;");
img.attr("style", "width:210px;");
img.attr("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(this).on('click','.input-button-modal', function(e) {
var contactModal = $(this).parent().parent().parent().parent().parent().find(".modal").attr('id');
var currentModal = $('#' + contactModal);
currentModal.attr("style", "display:none");
photoPreviewImg.append(img);
});
$photoInput.parsley().on('field:success', function() {
var inputID = $photoInput.attr('id');
var inputTarget = '#' + inputID;
var inputValue = document.getElementById(inputID);
//inputLabel.attr("style", 'width:70%;');
readURL(inputValue);
$(inputTarget).parent().parent().parent().parent().find('.koh-photo-remove').show();
$contactForm.find('#terms').prop('required',true);
});
});
Any help is appreciated. I want to get the ID of the label associated with each of the input type file field. Thanks in advance.
Label and input fields are linked by the for of the label being the id of input. You can simply take advantage of that link
function getLabelID(input){
return $("label['for=" + $(input).attr("id") + "']").attr("id");
}

Categories

Resources