I have contact form, and Js which validates the size of selected files. Also I want to add extension check. My code so far is
var inputs = $('input[type="file"]')
inputs.on('change', function () {
var size = 0;
inputs.each(function () {
$.each(this.files, function () {
size += this.size;
var names = [];
alert(x);
});
});
if (size > 19000000) {
alert('Ukupna dozvoljena veličina fajlova za upload je 20mb!');
$('.inputDugme').attr('disabled', 'disabled');
} else {
$('.inputDugme').removeAttr('disabled', 'disabled')
}
});
Is there I way to get extension of files, and save it in array. And then check content of array.
You can collect extension names like this:
var size = 0,
etx = [];
inputs.each(function () {
$.each(this.files, function () {
size += this.size;
ext.push(this.name.split('.').pop());
});
});
x[] = this.name; is not valid syntax in Javascript, you should use Array.prototype.push method.
try this.
var ext = filename.split('.')[filename.split('.').length - 1];
Related
I am trying to change some jQuery code to plain JS for an on call function. I keep getting the following error - Failed to execute 'addEventListener' on 'EventTarget': parameter 2 is not of type 'Object'.
Old
$(document).on('change', '.js-variant-radio', onVariantRadioChange);
New
document.querySelector('.js-variant-radio').addEventListener("change", onVariantRadioChange);
Complete code block here
(function(){
//START QUANTITY INPUT VALIDATION FUNCTION
let
onVariantRadioChange = function(event) {
let
$radio = document.querySelector(this),
$form = $radio.closest('form'),
max = $radio.attr('data-inventory-quantity'),
$quantity = $form.querySelector('.js-quantity-field'),
$addToCartButton = $form.querySelector('.add-to-cart-button');
if($addToCartButton.prop('disabled') === true) {
$addToCartButton.prop('disabled', false);
}
$quantity.attr('max', max);
if (parseInt($quantity.value) > max) {
$quantity.val(max).change();
}
};
//END QUANTITY INPUT VALIDATION FUNCTION
})();
Here is your code in vanillaJS. The only thing I didn't do is mimic the change() trigger that was appended
document.addEventListener('DOMContentLoaded', () => {
let
onVariantRadioChange = function(event) {
let
$radio = event.target,
$form = $radio.closest('form'),
max = $radio.dataset['inventory-quantity'],
$quantity = $form.querySelector('.js-quantity-field'),
$addToCartButton = $form.querySelector('.add-to-cart-button');
if ($addToCartButton.getAttribute('disabled')) {
$addToCartButton.removeAttribute('disabled');
}
$quantity.setAttribute('max', max);
if (parseInt($quantity.value) > max) {
$quantity.value = max;
}
};
document.querySelectorAll('.js-variant-radio').foreach(el => el.addEventListener("change", onVariantRadioChange));
})
You're still adding the event listener with jQuery. Try changing it to:
const jsVariantRadio = document.getElementsByClassName('.js-variant-radio')[0];
jsVariantRadio.addEventListener('change', onVariantRadioChange);
I have a server that dynamically(asp.net ) generate webpages that I can't alter.
On all pages I would like to capture all buttons clicked.
In JSFiddle https://jsfiddle.net/forssux/aub2t6gn/2/ is an example..
$(".checkout-basket").click (function ()
The first alert shows the 3 possible values,
but not the chosen item..
$(".button.button-dl").click(function ()
In jsfiddle this part doesn't get executed
Strangely on my real webpage I get the button clicked...but when I put it in the If then construction it fails to console.log the chosen item..
I hope somebody can explain me how to get these..
Kind Regards
Guy Forssman
//$("div.detail-info,table.checkout-basket").click(function () {
// var knopje = $(this).attr("class")//.split(" ");
// console.log(knopje + " knopje was clicked");
// if(knopje.indexOf("detail-info") > -1) {
// console.log("div class detail-info is clicked");
// }
// else if (knopje.indexOf("checkout-basket") > -1) {
// console.log("table class checkout-basket is clicked");
// }
// else {
// alert ("er is op iets anderes gedrukt");
// }
// capture click on download button in checkout-basket page
$(".checkout-basket").click (function () {
basket =[];
item="";
str = $(this).text();
str = str.replace(/\s\s+/g, ' ');
var str = str.match(/("[^"]+"|[^"\s]+)/g);
console.log("Array ",str);
for(var i=0;i<str.length;i++){
if(str[i] === "verwijder"){
console.log("Item= ",str[i+1]);
item = str[i+1];
basket.push(item);}
}
console.log("Basket contains ",basket);
//console.log("idValBasket ",idVal);
var test = idVal.replace(/\$/gi, "_").slice(0,-6);
console.log("test ",test);
var element = test.substr(test.length - 2)-1;
console.log("element ",element);
element=element-1;
item = basket[element];
console.log("Item finaal is ",item);
});
$(".button.button-dl").click(function () {
var addressValue = $(this).attr('href');
console.log("addresValue Basket",addressValue );
var re = /'(.*?)'/;
var m = addressValue.match(re);
console.log (" m basket is ",m);
if (m != null)
idVal = (m[0].replace(re, '$1'));
console.log("idVal Basket",idVal);
});
//This section captures the download in the detail page
$(".button").click(function () {
var downloadItem = document.getElementsByTagName("h1")[0].innerHTML
console.log("addresValue detail",downloadItem );
});
I never use click function, use on(*event*,...) instead:
$(".checkout-basket").on("click", function (){ /* CODE */ });
Check if visually there are a layout over the a layuot (a div, span, etc.)
Maybe a strange question and maybe i got it wrong, but why do you use push ?? if you want to delete an item ? btw also the example isn't working so maybe that is your problem
We ask the user here to define html, so add a div or a section or something like that. So, I want the validation-tooltips when editing my HTML. But don't wanna have the doc-type warning.
Try this
var session = editor.getSession();
session.on("changeAnnotation", function() {
var annotations = session.getAnnotations()||[], i = len = annotations.length;
while (i--) {
if(/doctype first\. Expected/.test(annotations[i].text)) {
annotations.splice(i, 1);
}
}
if(len>annotations.length) {
session.setAnnotations(annotations);
}
});
With "Unexpected End of File. Expected DOCTYPE." warning filtered.
var session = editor.getSession();
session.on("changeAnnotation", function () {
var annotations = session.getAnnotations() || [], i = len = annotations.length;
while (i--) {
if (/doctype first\. Expected/.test(annotations[i].text)) {
annotations.splice(i, 1);
}
else if (/Unexpected End of file\. Expected/.test(annotations[i].text)) {
annotations.splice(i, 1);
}
}
if (len > annotations.length) {
session.setAnnotations(annotations);
}
});
If instead you operate on the annotations directly and call the editor onChangeAnnotation method directly to update the annotations on the page you can prevent firing another changeAnnotation event and calling this event handler twice as Chris's answer does.
var editor = Application.ace.edit(element),
session = editor.getSession();
session.on('changeAnnotation', function () {
session.$annotations = session.$annotations.filter(function(annotation){
return !(/doctype first\. Expected/.test(annotation.text) || /Unexpected End of file\. Expected/.test(annotation.text))
});
editor.$onChangeAnnotation();
});
Hi I am using this code to restrict user from uploading the heavy files above 5mb. But this is only working for first file filed not for the rest of file fileds.
var n=1;
$(document).ready(function()
{
$('.add_field').click(function(){
if(n < 5)
{
n=n+1;
var newid="file"+n;
var input = $('#file1');
var clone = input.clone(true);
//clone.removeAttr ('id');
clone.attr('title','file'+n);
clone.attr('id','file'+n);
clone.val('');
clone.appendTo('.input_holder');}
});
$('.remove_field').click(function(){
if(n!=1)
{
n=n-1;
if($('.input_holder input:last-child').attr('id') != 'input_clone'){
$('.input_holder input:last-child').remove();
}
}
});
$("#file1").change(function ()
{
var iSize = ($("#file1")[0].files[0].size / 1024);
if(iSize>5000)
{
alert("Too Large FIle");
example_reset_html('file1d');
}
});
$("#file2").change(function ()
{
var iSize = ($("#file2")[0].files[0].size / 1024);
if(iSize>5000)
{
alert("Too Large FIle");
example_reset_html('file1d');
}
});
});
function example_reset_html(id) {
$('#'+id).html($('#'+id).html());
}
I checked this all browser and tried hacks but it seems that something is wrong and not working properly.
Can you bind your event on $('.input_holder')? It seems that element holds all file inputs so you only have to bind the change event to their parent.
$(".input_holder").change(function (e)
{
if(e.target.type==="file"){
var iSize = (e.target.files[0].size / 1024);
if(iSize>5000)
{
alert("Too Large FIle");
example_reset_html(e.target.id);
}
}
});
For internationalization support, I wrote code that changes the URL from #lang-select dropdown .The code is
$(document).ready(function(){
var sel = document.getElementById('lang-select');
sel.onchange = function(){window.location.replace($('#lang-select').val());};
});
the above code works fine and it changes the URL from http://0.0.0.0:3000/fr to http://0.0.0.0:3000/en.
Now I want to preserve the changed value, but without success. I have written the code below. I don't know why it is wrong/not working .
function langSelect(){
var available_languages = {
"en":"English",
"de":"Deutsch",
"ru" :"Россию",
"fr" : "Française"
};
var languageInUrl= document.URL.split("/")[3];
for(var shortLanguage in available_languages){
if(shortLanguage === languageInUrl) {
var langaugeOptionArray = $("#lang-select>option");
for(var i = 0 ; langaugeOptionArray.length > i ; i++){
if(langaugeOptionArray[i].label === available_languages[shortLanguage]){
langaugeOptionArray[i].selected = true;
return;
}
}
}
}
}
Please tell me what's wrong in above code and since what I am doing is not a new thing, please share what is the best practice to overcome this scenario.
Currently, I am using backend to accomplish this.
$(function() {
$('#lang-select').on("change",function(){
window.location.replace($(this).val());
});
});
function langSelect(){
var available_languages = {
"en":"English",
"de":"Deutsch",
"ru" :"Россию",
"fr" : "Française"
};
var languageInUrl= document.URL.split("/")[3];
var lang = available_languages[languageInUrl];
if (lang) {
var langaugeOptionArray = $("#lang-select>option");
langaugeOptionArray.each(function() {
if($(this).text() === lang){
$("#lang-select").val(lang);
return false;
}
});
}
}
I believe we can even do
if (lang) {
var opt = $("#lang-select").find('option[text="'+lang+'"]').val();
if (opt) $("#lang-select").val(opt);
}
Good luck