Using jQuery with meteor giving errors - javascript

Omitting the keydown input : function(event) { and } gives me an error along the lines of
"While building the application:
client/client.js:33:11: Unexpected token ("
which is basically the starting. I'm wondering why I need the javascript function right at the start. To not get the error. This is an issue especially because I don't want the click function to run every time the key is pressed. In any case it would be great to either figure out how I can just use jQuery instead of javascript here or change the keydown input.
Template.create_poll.events = {
'keydown input' : function(event) {
$("input").keypress(function() {
var active_element = $(this).parent().attr("id");
var last_child = $('ul li:last').attr("id");
var option_number_index = last_child.lastIndexOf("-");
var option_number = last_child.substring(option_number_index+1);
option_number = option_number/1;
//console.log(option_number);
//console.log(last_child);
if (last_child == active_element) {
console.log(active_element);
option_number += 1;
console.log(option_number);
$('ul').append('<li id="poll-choice-' + option_number + '"><input name="choice" type="text" placeholder="Option ' + option_number + '">');
}
});
$("#poll_create").click(function() {
console.log("Button works");
var choices = new Array();
var counter = 0;
$("ul li input").each(function() {
choices[counter] = $(this).val();
counter++;
});
console.log(choices[1]);
console.log(choices[5]);
});
}
}

Template.create_poll.events expects an eventMap which is:
An event map is an object where the properties specify a set of events to handle, and the values are the handlers for those events. The property can be in one of several forms:
Hence, you need to pass in the 'keydown input' : function (event, templ) { ... } to make it a valid Javascript object.
In this case, you should follow #Cuberto's advice and implement the events using Meteor's event map:
Template.create_poll.events = {
'press input' : function(event) {
var active_element = $(this).parent().attr("id");
var last_child = $('ul li:last').attr("id");
var option_number_index = last_child.lastIndexOf("-");
var option_number = last_child.substring(option_number_index+1);
option_number = option_number/1;
//console.log(option_number);
//console.log(last_child);
if (last_child == active_element) {
console.log(active_element);
option_number += 1;
console.log(option_number);
$('ul').append('<li id="poll-choice-' + option_number + '"><input name="choice" type="text" placeholder="Option ' + option_number + '">');
}
},
'click #poll_create' : function (event) {
console.log("Button works");
var choices = new Array();
var counter = 0;
$("ul li input").each(function() {
choices[counter] = $(this).val();
counter++;
});
console.log(choices[1]);
console.log(choices[5]);
}
}
However, if you want to use certain jQuery specific events, then you can attach them in the rendered function:
Template.create_poll.rendered = function () {
$("input").keypress(function() {
var active_element = $(this).parent().attr("id");
var last_child = $('ul li:last').attr("id");
var option_number_index = last_child.lastIndexOf("-");
var option_number = last_child.substring(option_number_index+1);
option_number = option_number/1;
//console.log(option_number);
//console.log(last_child);
if (last_child == active_element) {
console.log(active_element);
option_number += 1;
console.log(option_number);
$('ul').append('<li id="poll-choice-' + option_number + '"><input name="choice" type="text" placeholder="Option ' + option_number + '">');
}
});
$("#poll_create").click(function() {
console.log("Button works");
var choices = new Array();
var counter = 0;
$("ul li input").each(function() {
choices[counter] = $(this).val();
counter++;
});
console.log(choices[1]);
console.log(choices[5]);
});
};

Related

'DOMException: Failed to execute 'querySelectorAll' on 'Element' when using an 'option:selected' selector

I'm running a page which throws an error at the following line:
var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
For the sake of completeness, here is the full jQuery function (country-select.js):
(function($) {
$.fn.countrySelect = function (callback) {
$(this).each(function(){
var $select = $(this);
var lastID = $select.data('select-id'); // Tear down structure if Select needs to be rebuilt
if (lastID) {
$select.parent().find('span.caret').remove();
$select.parent().find('input').remove();
$select.unwrap();
$('ul#select-options-'+lastID).remove();
}
// If destroying the select, remove the selelct-id and reset it to it's uninitialized state.
if(callback === 'destroy') {
$select.data('select-id', null).removeClass('initialized');
return;
}
var uniqueID = Materialize.guid();
$select.data('select-id', uniqueID);
var wrapper = $('<div class="select-wrapper"></div>');
wrapper.addClass($select.attr('class'));
var options = $('<ul id="select-options-' + uniqueID +'" class="dropdown-content select-dropdown country-select"></ul>'),
selectChildren = $select.children('option, optgroup'),
valuesSelected = [],
optionsHover = false;
var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
// Function that renders and appends the option taking into
// account type and possible image icon.
var appendOptionWithIcon = function(select, option, type) {
// Add disabled attr if disabled
var disabledClass = (option.is(':disabled')) ? 'disabled ' : '';
var optgroupClass = (type === 'optgroup-option') ? 'optgroup-option ' : '';
var classes = option.attr('class');
var data = option.data('phone-code');
var opt = '<li class="' + disabledClass + optgroupClass + '"><span>';
if (option.val() !== '') {
opt += '<b class="flag flag-' + option.val().toLowerCase() + '"></b>';
}
opt += '<span class="option-label">' + option.html() + '</span>';
if (data && data !== '') {
opt += '<small>' + data + '</small>';
}
opt += '</span></li>';
options.append($(opt));
};
/* Create dropdown structure. */
if (selectChildren.length) {
selectChildren.each(function() {
if ($(this).is('option')) {
appendOptionWithIcon($select, $(this));
} else if ($(this).is('optgroup')) {
// Optgroup.
var selectOptions = $(this).children('option');
options.append($('<li class="optgroup"><span>' + $(this).attr('label') + '</span></li>'));
selectOptions.each(function() {
appendOptionWithIcon($select, $(this), 'optgroup-option');
});
}
});
}
options.find('li:not(.optgroup)').each(function (i) {
$(this).click(function (e) {
// Check if option element is disabled
if (!$(this).hasClass('disabled') && !$(this).hasClass('optgroup')) {
var selected = true;
options.find('li').removeClass('active');
$(this).toggleClass('active');
$newSelect.val($(this).find('.option-label').text());
activateOption(options, $(this));
$select.find('option').eq(i).prop('selected', selected);
// Trigger onchange() event
$select.trigger('change');
if (typeof callback !== 'undefined') callback();
}
e.stopPropagation();
});
});
// Wrap Elements
$select.wrap(wrapper);
// Add Select Display Element
var dropdownIcon = $('<span class="caret">▼</span>');
if ($select.is(':disabled'))
dropdownIcon.addClass('disabled');
// escape double quotes
var sanitizedLabelHtml = label.replace(/"/g, '"');
var $newSelect = $('<input type="text" class="select-dropdown" readonly="true" ' + (($select.is(':disabled')) ? 'disabled' : '') + ' data-activates="select-options-' + uniqueID +'" value="'+ sanitizedLabelHtml +'"/>');
$select.before($newSelect);
$newSelect.before(dropdownIcon);
$newSelect.after(options);
// Check if section element is disabled
if (!$select.is(':disabled')) {
$newSelect.data('constrainwidth', false)
$newSelect.dropdown({'hover': false, 'closeOnClick': false});
}
// Copy tabindex
if ($select.attr('tabindex')) {
$($newSelect[0]).attr('tabindex', $select.attr('tabindex'));
}
$select.addClass('initialized');
$newSelect.on({
'focus': function (){
if ($('ul.select-dropdown').not(options[0]).is(':visible')) {
$('input.select-dropdown').trigger('close');
}
if (!options.is(':visible')) {
$(this).trigger('open', ['focus']);
var label = $(this).val();
var selectedOption = options.find('li').filter(function() {
return $(this).find('.option-label').text().toLowerCase() === label.toLowerCase();
})[0];
activateOption(options, selectedOption);
}
},
'click': function (e){
e.stopPropagation();
}
});
$newSelect.on('blur', function() {
$(this).trigger('close');
options.find('li.selected').removeClass('selected');
});
options.hover(function() {
optionsHover = true;
}, function () {
optionsHover = false;
});
// Make option as selected and scroll to selected position
var activateOption = function(collection, newOption) {
if (newOption) {
collection.find('li.selected').removeClass('selected');
var option = $(newOption);
option.addClass('selected');
options.scrollTo(option);
}
};
// Allow user to search by typing
// this array is cleared after 1 second
var filterQuery = [],
onKeyDown = function(e){
// TAB - switch to another input
if(e.which == 9){
$newSelect.trigger('close');
return;
}
// ARROW DOWN WHEN SELECT IS CLOSED - open select options
if(e.which == 40 && !options.is(':visible')){
$newSelect.trigger('open');
return;
}
// ENTER WHEN SELECT IS CLOSED - submit form
if(e.which == 13 && !options.is(':visible')){
return;
}
e.preventDefault();
// CASE WHEN USER TYPE LETTERS
var letter = String.fromCharCode(e.which).toLowerCase(),
nonLetters = [9,13,27,38,40];
if (letter && (nonLetters.indexOf(e.which) === -1)) {
filterQuery.push(letter);
var string = filterQuery.join(''),
newOption = options.find('li').filter(function() {
return $(this).text().toLowerCase().indexOf(string) === 0;
})[0];
if (newOption) {
activateOption(options, newOption);
}
}
// ENTER - select option and close when select options are opened
if (e.which == 13) {
var activeOption = options.find('li.selected:not(.disabled)')[0];
if(activeOption){
$(activeOption).trigger('click');
$newSelect.trigger('close');
}
}
// ARROW DOWN - move to next not disabled option
if (e.which == 40) {
if (options.find('li.selected').length) {
newOption = options.find('li.selected').next('li:not(.disabled)')[0];
} else {
newOption = options.find('li:not(.disabled)')[0];
}
activateOption(options, newOption);
}
// ESC - close options
if (e.which == 27) {
$newSelect.trigger('close');
}
// ARROW UP - move to previous not disabled option
if (e.which == 38) {
newOption = options.find('li.selected').prev('li:not(.disabled)')[0];
if(newOption)
activateOption(options, newOption);
}
// Automaticaly clean filter query so user can search again by starting letters
setTimeout(function(){ filterQuery = []; }, 1000);
};
$newSelect.on('keydown', onKeyDown);
});
function toggleEntryFromArray(entriesArray, entryIndex, select) {
var index = entriesArray.indexOf(entryIndex),
notAdded = index === -1;
if (notAdded) {
entriesArray.push(entryIndex);
} else {
entriesArray.splice(index, 1);
}
select.siblings('ul.dropdown-content').find('li').eq(entryIndex).toggleClass('active');
// use notAdded instead of true (to detect if the option is selected or not)
select.find('option').eq(entryIndex).prop('selected', notAdded);
setValueToInput(entriesArray, select);
return notAdded;
}
function setValueToInput(entriesArray, select) {
var value = '';
for (var i = 0, count = entriesArray.length; i < count; i++) {
var text = select.find('option').eq(entriesArray[i]).text();
i === 0 ? value += text : value += ', ' + text;
}
if (value === '') {
value = select.find('option:disabled').eq(0).text();
}
select.siblings('input.select-dropdown').val(value);
}
};
$(function() {
$('.js-country-select').countrySelect();
});
$(document).on('change', '[data-country-select]', function() {
var target = 'select' + $(this).data('country-select');
var val = $(this).val();
var label = 'State';
var options = [
'<option value="" selected="" disabled="">Select State</option>'
];
if (val !== '') {
var country = window.__COUNTRIES[val];
var subdivisions = country.subdivisions;
var keys = Object.keys(subdivisions);
label = country.subdivisionName;
options = [
'<option value="" selected="" disabled="">Select ' + label + '</option>'
];
keys = keys.sort(function(a, b) {
var valA = subdivisions[a].toLowerCase();
var valB = subdivisions[b].toLowerCase();
if (valA < valB) return -1;
if (valA > valB) return 1;
return 0;
});
keys.forEach(function(key) {
options.push('<option value="' + key + '">' + subdivisions[key] + '</option>');
});
$(target).removeAttr('disabled');
} else {
$(target).attr('disabled', 'disabled');
}
$(target).parents('.input-field').find('label').html(label);
$(target).val('').html(options);
$(target).select2();
});
})(jQuery);
Here is the exception that I see in debug mode:
From what I understand from Failed to execute 'querySelectorAll' on 'Element' in ExtJS 5, :selected is not part of the CSS specification.
How should I fix this? Should I use:
var label = $select.find('option').filter(':selected').html() || $select.find('option').filter(':first').html() || "";
?
Converting Phil's comment to an answer, my debugger was set to pause on all exceptions (including caught ones). I had to de-activate the 'stop sign' button shown below to make the debugger work normally again.

I'm not sure why my click event won't work

I'm trying to add a click event to .user that will change the background color of the entire page to green. I'm very new to jQuery, but the code looks right to me. When I click the .users button, nothing happens. Anyone have any ideas?
$(document).ready(function() {
var $body = $('body')
/*$body.html('');*/
// var currentView = "Twittler Feed"
var currentView = $('<p>Twittler Feed</p>');
var refreshTweet = function() {
var index = streams.home.length - 1;
var endInd = index - 10;
while (index >= endInd) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweets"><p class="posted-by"><button class="user">#' +
tweet.user + '</button><p class="message">' + tweet.message +
'</p><p class="time">' + /*$.timeago(tweet.created_at)*/ tweet.created_at + '</p></div>');
currentView.appendTo('#sidebar')
$tweet.appendTo($body);
index -= 1;
}
}
refreshTweet();
$('.refresh').on('click', function() {
if (document.getElementsByClassName('tweets')) {
$('.tweets').remove();
}
var result = refreshTweet();
$body.prepend(result);
})
$('.user').on('click', 'button', function() {
currentView = this.user
$('body').css('background-color', 'green');
});
});

Change label to match numeric part from ID

I have this HTML code:
<div id="wrapper">
<div class="row">
<label for="additional_1">Additional #1 :</label>
<input type="text" id="additional_1" name="pnr_remarks_modify[additional][]">
New - Remove
</div>
</div>
And I am adding (cloning) / removing the complete '.row' element with this code:
var cloneCntr = 2;
$('#wrapper').on('click', '.addInput', function() {
// clone the div
var row = $(".row").last();
var clone = row.clone();
// change all id and name values to a new unique value
$("*", clone).add(clone).each(function() {
if (this.id) {
this.id = (this.id).slice(0, -1) + cloneCntr;
}
if (this.name) {
this.name = this.name;
}
});
++cloneCntr;
$('#wrapper').append(clone);
});
$('#wrapper').on('click', '.removeInput', function(e) {
e.preventDefault();
var target = $(e.currentTarget);
target.parent().remove();
})
Every time I click on New I got a clone from the previous object but changing its ID. For example:
First Click on New
Additional #1 :
New - Remove
Second Click on New
Additional #1 :
New - Remove
But as you can see the for attr and the label text remain the same. I need to change them to (on each new clone):
for needs to be the same as the new ID
label text needs to be Additional # + cloneCntr
But I don't know how to achieve this part, can I get some help?
Here is the jsFiddle where I am playing around this
You can loop through all the rows each time one is added or removed and update based on row index. Use one function that gets called within both event handlers
$('#wrapper').on('click', '.addInput', function() {
var clone = $(".row").last().clone();
clone.find('input').val(''); // clear value on clone input
$('#wrapper').append(clone);
updateCounts();
});
$('#wrapper').on('click', '.removeInput', function(e) {
e.preventDefault();
var target = $(e.currentTarget);
target.parent().remove();
updateCounts();
});
function updateCounts() {
$('#wrapper .row').each(function(i) {
var num = i + 1,
$row = $(this),
inputId = 'additional_' + num;
$row.find('label').text('Additional #' + num + ' :').attr('for', inputId);
$row.find('input').attr('id', inputId)
});
}
DEMO
You can use another function to generate html with new id and for attribute like following.
function getRow(index){
return '<div class="row">' +
'<label for="additional_'+index+'">Additional #'+index+' :</label>' +
'<input type="text" id="additional_' + index + '" name="pnr_remarks_modify[additional][]">' +
'New - Remove' +
'</div>';
}
var cloneCntr = 2;
$('#wrapper').on('click', '.addInput', function () {
var clone = getRow(cloneCntr);
++cloneCntr;
$('#wrapper').append(clone);
});
DEMO

jQuery price calculator function is not working with tabs

I have been trying to get this working from last couple of days without any success. I have this price calculator function developed by a freelancer who is not reachable from last few weeks.
This function works fine without any JavaScript tabs but not quite right with them. I need to have tabs on page because there are tons of options in this calculator.
This is the jQuery function.
$(document).ready(function() {
// For tabs
var tabContents = $(".tab_content").hide(),
tabs = $("ul.nav-tabs li");
tabs.first().addClass("active").show();
tabContents.first().show();
tabs.click(function() {
var $this = $(this),
activeTab = $this.find('a').attr('href');
if (!$this.hasClass('active')) {
$this.addClass('active').siblings().removeClass('active');
tabContents.hide().filter(activeTab).fadeIn();
}
return false;
});
// For Calculator
function Cost_Calculator() {
var Currency = '$';
var messageHTML = 'Please contact us for a price.';
function CostFilter(e) {
return e;
}
//Calculate function
function calculate() {
//Blank!
var CalSaveInfo = [];
$('#cost_calc_custom-data, #cost_calc_breakdown').html('');
//Calculate total
var calCost = 0;
var calculate_class = '.cost_calc_calculate';
$('.cost_calc_active').each(function() {
//Calculation
calCost = calCost + parseFloat($(this).data('value'));
//Add to list
var optionName = $(this).attr('value');
var appendName = '<span class="cost_calc_breakdown_item">' + optionName + '</span>';
var optionCost = $(this).attr('data-value');
var appendCost = '<span class="cost_calc_breakdown_price">' + Currency + optionCost + '</span>';
if (optionCost != "0") {
var appendItem = '<li>' + appendName + appendCost + '</li>';
}
//hidden data
var appendPush = ' d1 ' + optionName + ' d2 d3 ' + optionCost + ' d4 ';
$('#cost_calc_breakdown').append(appendItem);
CalSaveInfo.push(appendPush);
});
//Limit to 2 decimal places
calCost = calCost.toFixed(2);
//Hook on the cost
calCost = CostFilter(calCost);
var CustomData = '#cost_calc_custom-data';
$.each(CalSaveInfo, function(i, v) {
$(CustomData).append(v);
});
//Update price
if (isNaN(calCost)) {
$('#cost_calc_total_cost').html(messageHTML);
$('.addons-box').hide();
} else {
$('#cost_calc_total_cost').html(Currency + calCost);
$('.addons-box').show();
}
}
//Calculate on click
$('.cost_calc_calculate').click(function() {
if ($(this).hasClass('single')) {
//Add cost_calc_active class
var row = $(this).data('row');
//Add class to this only
$('.cost_calc_calculate').filter(function() {
return $(this).data('row') == row;
}).removeClass('cost_calc_active');
$(this).addClass('cost_calc_active');
} else {
// Remove class if clicked
if ($(this).hasClass('cost_calc_active')) {
$(this).removeClass('cost_calc_active');
} else {
$(this).addClass('cost_calc_active');
}
}
//Select item
var selectItem = $(this).data('select');
var currentItem = $('.cost_calc_calculate[data-id="' + selectItem + '"]');
var currentRow = currentItem.data('row');
if (selectItem !== undefined) {
if (!$('.cost_calc_calculate[data-row="' + currentRow + '"]').hasClass('cost_calc_active'))
currentItem.addClass('cost_calc_active');
}
//Bring in totals & information
$('#cost_calc_breakdown_container, #cost_calc_clear_calculation').fadeIn();
$('.cost_calc_hide').hide();
$('.cost_calc_calculate').each(function() {
if ($(this).is(':hidden')) {
$(this).removeClass('cost_calc_active');
}
calculate();
});
return true;
});
$('#cost_calc_clear_calculation').click(function() {
$('.cost_calc_active').removeClass('cost_calc_active');
calculate();
$('#cost_calc_breakdown').html('<p id="empty-breakdown">Nothing selected</p>');
return true;
});
}
//Run cost calculator
Cost_Calculator();
});
You can see this working on jsfiddle without tabs. I can select options from multiple sections and order box will update selected option's price and details dynamically.
But when I add JavaScript tabs, it stop working correctly. See here. Now if I select option from different sections, order box resets previous selection and shows new one only.
I think the problem is with calculator somewhere.
You are removing the active class from hidden elements. This means that when you move to the second tab you disregard what you've done in the first.
line 120 in your fiddle:
if ($(this).is(':hidden')) {
$(this).removeClass('cost_calc_active');
}
I haven't taken the code in depth enough to tell if you can just remove this.

how to limit the click event in jquery loop?

I would like to limit click event loop in jquery. I have categories list which will have in the following format and also after 5 click in the loop i have to disable click event.
<div class="col-md-2 col-sm-4 col-xs-6 home_s">
<a class="get_category" id="36" href="javascript:void(0)">
<img class="img-responsive img-center" src="">
<span>xxxxx</span>
</a>
<input type="hidden" value="36" id="categories36" name="categories[]">
</div>
$(document).ready(function() {
$(".get_category").on('click', function() {
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
})
});
You can use off() to unbind event handler
$(document).ready(function() {
// variable for counting clicks
var i = 1;
var fun = function() {
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
// checking and increment click count
if (i++ == 5)
// unbinding click handler from element
$(".get_category").off('click', fun);
};
$(".get_category").on('click', fun);
});
Example :
$(document).ready(function() {
var i = 1;
var fun = function() {
alert('clicked'+i);
if (i++ == 5)
$(".get_category").off('click', fun);
};
$(".get_category").on('click', fun);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="get_category">click</button>
If you have multiple .get_category in your html the solution from Pranav C Balan won't work.
$(document).ready(function() {
function clickFunc() {
var click_count = $(this).data('click-count') || 0;
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
if (++click_count >= 5)
$(this).off('click', clickFunc);
$(this).data('click-count', click_count);
});
$(".get_category").on('click', clickFunc);
});
This way you store the click count on the data-click-count attribute of each .get_category

Categories