Add more values - javascript

$.starRating = function(options) {
var defaults = {
onClickCallBack: null,
};
var settings = $.extend({}, defaults, options);
var onClickCallBack = settings.onClickCallBack;
$(".rating-star span").hover(function() {
var hoverValue = parseInt($(this).attr('data-val'));
highlightStars(hoverValue, 'hover');
});
$(".rating-star span").mouseout(function() {
$(".rating-star span").each(function() {
$(this).removeClass("hover");
});
});
$(".rating-star span").click(function() {
if (onClickCallBack != null) {
var rate = parseInt($(this).attr('data-val'));
var id = parseInt($(this).attr('data-id'));
highlightStars(rate, 'clicked');
onClickCallBack(rate, id);
}
});
function highlightStars(count, cssClass) {
var itemValue = 0;
$(".rating-star span").each(function() {
itemValue = parseInt($(this).attr('data-val'));
if (itemValue <= count) {
$(this).addClass(cssClass);
} else {
$(this).removeClass(cssClass);
}
});
}
function highlightRating(rate) {
var roundedRate = Math.round(rate);
highlightStars(roundedRate, 'clicked');
}
return {
highlightRatingStars: function(rate) {
highlightRating(rate);
}
}
}
$(function() {
var starRatingFunction = $.starRating({
onClickCallBack: onRatingStar
});
function onRatingStar(rate, id) {
$("#1_star_input").val(rate);
$("#2_star_input").val(rate);
$("#3_star_input").val(rate);
loadData();
}
});
Hi guys, I have some star rating jquery code, right now I can use one set of stars and retrieve the values but, I want to be able to get values for three different sets of stars. i'm only getting values for #1_star_input and it does the same for the other two.

Related

Using javascript like a function with button

I want to use this code as a function () to be run only when I click a button and not automatically when dropdown is changed. When click on <button onclick="CalendarFilter">Cercar</button> it runs the function. I tried putting the code into this but not working.
function myFunction()
{
CODE HERE
}
$(document).ready(function () {
$('.filter').change(function () {
var values = [];
$('.filter').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push( {
text: $(this).text(),
colId : colIdx
});
});
});
filter('table > tbody > tr', values);
});
function filter(selector, values) {console.log(values);
$(selector).each(function () {
var sel = $(this);
var tokens = sel.text().trim().split('\n');
var toknesObj = [], i;
for(i=0;i<tokens.length;i++){
toknesObj[i] = {
text:tokens[i].trim(),
found:false
};
}
var show = false;
//console.log(toknesObj);
$.each(values, function (i, val) {
if (toknesObj[val.colId].text.search(new RegExp("\\b"+val.text+"\\b")) >= 0) {
toknesObj[val.colId].found = true;
}
});
console.log(toknesObj);
var count = 0;
$.each(toknesObj, function (i, val) {
if (val.found){
count+=1;
}
});
show = (count === values.length);
show ? sel.show() : sel.hide();
});
}
});
When click on Cercar it runs the CalendarFilter
Thanks.
I need a way to run this like this:
function myFunction()
{
$(document).ready(function () {
$('.filter').change(function () {
var values = [];
$('.filter').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push( {
text: $(this).text(),
colId : colIdx
});
});
});
filter('table > tbody > tr', values);
});
function filter(selector, values) {console.log(values);
$(selector).each(function () {
var sel = $(this);
var tokens = sel.text().trim().split('\n');
var toknesObj = [], i;
for(i=0;i<tokens.length;i++){
toknesObj[i] = {
text:tokens[i].trim(),
found:false
};
}
var show = false;
//console.log(toknesObj);
$.each(values, function (i, val) {
if (toknesObj[val.colId].text.search(new RegExp("\\b"+val.text+"\\b")) >= 0) {
toknesObj[val.colId].found = true;
}
});
console.log(toknesObj);
var count = 0;
$.each(toknesObj, function (i, val) {
if (val.found){
count+=1;
}
});
show = (count === values.length);
show ? sel.show() : sel.hide();
});
}
});
}
To call that function using a button.
<button onclick="myFunction()">Cercar</button>
The problem is that this way is not working.
Thanks.

i have a tempermonkey script which read data from csv file .....i want to change it based on fields on webpage

The script loads data from a CSV file. Page sometimes has five fields,
sometimes four. The script needs to adjust based on the number of fields.
forexample I need to modify this tempermonkey script
enter 4 pieces of data if there are 4 fields or enter 5 pieces of data if
there are 5 fields on the web page.
$(window).ready(function($) {
var file = GM_getResourceText('csvFile');
var csv = $.csv.toArrays(file);
var row = 0;
//var interval = setInterval(fillFormInterval, 3000);
var scope = angular.element($('body')).scope();
// scope.$on('$includeContentLoaded', function(){
// fillForm(csv[row]);
//setTimeout(fillForm(csv[row]));
//});
var interval = setInterval(fillFormInterval, 1000);
functionfillFormInterval() {
if($('#applicant-preferredCommunicationMethod').length) {
clearInterval(interval);
setTimeout(function() {
fillForm(csv[row]);
},3000);
}
}
functionfillForm(tempRow) {
var scope = angular.element($('#applicant-firstName')).scope();
if(!scope.applicant || !scope.applicant.phone1) {
return;
}
var row = new Array(5).fill(undefined);
row[1] = "NMN";
tempRow.forEach(function(data,i) {
if(data != '') {
row[i] = data;
}
});
scope.$apply(function() {
scope.applicant.firstName = row[0];
scope.applicant.middleName = row[1];
scope.applicant.lastName = row[2];
scope.applicant.dateOfBirth = row[3];
scope.applicant.dateOfBirth2 = row[3];
scope.applicant.phone1.number = row[4];
scope.applicant.preferredCommunicationMethod = "PHONE1";
scope.inherited.next();
});
//scope.applicant.countryOfBirth = "CD";
}
var interval_2 = setInterval(fillFormInterval_2, 1000);
function fillFormInterval_2() {
if($('#applicant-countryOfBirth').length) {
clearInterval(interval_2);
setTimeout(function() {
fillForm_2(csv[row]);
},3000);
}
}
functiondropDownVal(id, text) {
var value = null;
$(id).each(function() {
if(this.text.toLowerCase() == text) {
value = this.value;
value = value.split(':');
if(value.length> 1) {
value = value[1];
}else {
value = value[0];
}
}
});
return value;
}
function fillForm_2(data) {
var scope = angular.element($('#applicant-
countryOfBirth')).scope();
var country = '';
country = dropDownVal('#applicant-countryOfBirth option',
data[5].toLowerCase());
//scope.applicant.countryOfBirth = country;
var state = null;
scope.$apply(function() {
scope.applicant.countryOfBirth = country;
scope.updateStateProvince(scope.applicant.countryOfBirth);
setTimeout(function() {
if(country == "US" || country == "CD" || country == "MM") {
state = dropDownVal('#applicant-stateProvinceOfBirth
option', data[6].toLowerCase());
}
var citizen = dropDownVal('#applicant-countryOfCitizenship
option', data[7].toLowerCase());
console.log(country + " " + state + " " + citizen);
scope.applicant.countryOfCitizenship = citizen;
scope.applicant.stateProvinceOfBirth = state;
scope.$apply();
scope.inherited.next();
});
});
}
var interval_3 = setInterval(fillFormInterval_3, 1000);
function fillFormInterval_3() {
if($('.personal-questions').length) {
clearInterval(interval_3);
setTimeout(function() {
fillForm_3(csv[row]);
},3000);
}
}
function fillForm_3(data) {
e.applicant.hasMaidenPreviousName = false;
scope.applicant.hasAliasName = false;
scope.applicant.hasSameMailingResidentialAddress = true;
scope.applicant.doYouHaveAuthCode = false;
scope.applicant.viewEcNearYou = false;
scope.inherited.next();
});
}
var interval_4 = setInterval(fillFormInterval_4, 1000);
function fillFormInterval_4() {
if($('#ue-btn-US').length) {
clearInterval(interval_4);
setTimeout(function() {
fillForm_4(csv[row]);
},3000);
}
}
function fillForm_4(data) {
var scope = angular.element($('#applicant-eyeColor')).scope();
scope.$apply(function() {
scope.heightFt = parseInt(data[8].substr(0,1));
scope.heightIn = parseInt(data[8].substr(1,3));
scope.weightLb = parseInt(data[9]);
scope.applicant.hairColor = dropDownVal('#applicant-hairColor
option',
data[10].toLowerCase());
scope.applicant.eyeColor = dropDownVal('#applicant-eyeColor
option',
data[11].toLowerCase());
scope.applicant.gender = dropDownVal('#applicant-gender
option',
data[12].toLowerCase());
if(data[13].toLowerCase() == 'mixed race') {
data[13] = 'Unknown';
}else if(data[13].toLowerCase() == 'white' ||
data[13].toLowerCase() ==
'hispanic') {
data[13] = 'Caucasian/Latino';
}
scope.applicant.race = dropDownVal('#applicant-race option',
data[13].toLowerCase());
scope.inherited.next();
});
}
var interval_5 = setInterval(fillFormInterval_5, 1000);
function fillFormInterval_5() {
if($('#applicant-mailingAddress-country').length) {
clearInterval(interval_5);
setTimeout(function() {
fillForm_5(csv[row]);
},3000);
}
}
function fillForm_5(data) {
var scope = angular.element($('#applicant-mailingAddress-
country')).scope();
scope.$apply(function() {
scope.applicant.mailingAddress = {};
scope.applicant.mailingAddress.country = "US";
scope.updateStates('mailingAddress');
scope.applicant.mailingAddress.addressLine1 = data[14];
scope.applicant.mailingAddress.addressLine2 = data[15];
scope.applicant.mailingAddress.city = data[16];
setTimeout(function() {
scope.$apply(function() {
scope.applicant.mailingAddress.state = dropDownVal('#applicant-
mailingAddress-state option', data[17].toLowerCase());
scope.applicant.mailingAddress.postalCode = data[18];
scope.inherited.next();
});
});
//scope.inherited.next();
});
}
var interval_6 = setInterval(fillFormInterval_6, 1000);
function fillFormInterval_6() {
if($('#designatedRecipient-name').length) {
clearInterval(interval_6);
setTimeout(function() {
fillForm_6(csv[row]);
},3000);
}
}
function fillForm_6(data) {
var scope = angular.element($('#designatedRecipient-
name')).scope();
scope.$apply(function() {
scope.applicant.designatedRecipientName = "BIOVERIFY INC";
scope.applicant.designatedRecipientAddress = {};
scope.applicant.designatedRecipientAddress.country = "US";
scope.applicant.designatedRecipientAddress.addressLine1 = "2535
Manana
Dr.";
scope.applicant.designatedRecipientAddress.city = "Dallas";
setTimeout(function() {
scope.$apply(function() {
scope.applicant.designatedRecipientAddress.state =
dropDownVal('#applicant-designatedRecipientAddress-state
option', 'texas');
scope.applicant.designatedRecipientAddress.postalCode =
"75220";
scope.inherited.next();
});
});
scope.updateStates();
});
}
var interval_7 = setInterval(fillFormInterval_7, 1000);
function fillFormInterval_7() {
if($('#payment-nameOnCard').length) {
clearInterval(interval_7);
setTimeout(function() {
fillForm_7(csv[row]);
},3000);
}
}
function fillForm_7(data) {
var scope = angular.element($('#payment-nameOnCard')).scope();
scope.$apply(function() {
scope.applicant.payment.nameOnCard = "Brendan J Berrells";
scope.applicant.payment.cardNumber = "4246315197117185";
scope.applicant.payment.expiration = {};
scope.applicant.payment.expiration.month = 11;
scope.applicant.payment.expiration.year = "19";
scope.applicant.payment.csc = "255";
});
}
});

IndexedDB query to get individual page

I am trying to load a new page in my IndexedDB application.
I have a list of rooms, and when the user clicks on the next room in the list, it should load that room's details on the page.
Currently it just skips over the itemStore.openCursor().onsuccess = function(event) and goes to the end (I know this because I added breakpoints in Developer Tools).
HTML (added dynamically, which is why there's an onclick attribute)
<li id="124">
<small>2. </small>
FH102
</li>
JS
function getPage(roomId) {
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
openRequest = window.indexedDB.open("rooms", 1);
openRequest.onupgradeneeded = function() {
var db = openRequest.result;
var itemStore = db.createObjectStore("rooms", {keyPath: "room_id"});
var index = itemStore.createIndex("rooms", ["room_id"]);
};
openRequest.onerror = function(event) {
console.error(event);
};
openRequest.onsuccess = function (event) {
var db = openRequest.result;
db.onerror = function(event) {
// Generic error handler for all errors targeted at this database's requests
console.error(event.target);
console.log("Database error: " + event.target.error.name || event.target.error || event.target.errorCode);
};
var transaction = db.transaction(['rooms'], "readonly");
var itemStore = transaction.objectStore("rooms");
var index = itemStore.index("rooms", ["room_id"]);
console.log('DB opened');
itemStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
alert(cursor);
if(cursor) {
if(cursor.value.room_id == roomId) {
resetForm($('#room-usage'));
/* populate form with data */
$('#room-name').each(function () {
$(this).html(cursor.value.room_name); //page header
});
$('#prevroom').each(function () {
$(this).val(parseInt(cursor.value.room_seq) - 1);
});
$('#nextroom').each(function () {
$(this).val(parseInt(cursor.value.room_seq) + 1);
});
$('#sequence').each(function () {
$(this).val(parseInt(cursor.value.room_seq));
$.jStorage.set('currentSeqNo', cursor.value.room_seq, { TTL: 28800000 });
});
$('#route_number').each(function () {
$(this).val(parseInt(cursor.value.route_number));
$.jStorage.set('currentRouteNumber', cursor.value.route_number, { TTL: 28800000 });
});
$('#room_name').each(function () {
$(this).val(cursor.value.room_name); //hidden field
$.jStorage.set('currentRoomName', cursor.value.room_name, { TTL: 28800000 });
});
$('#room_id').each(function () {
$(this).val(cursor.value.room_id);
$.jStorage.set('currentRoomId', cursor.value.room_id, { TTL: 28800000 });
});
$('#countslider').each(function () {
$(this).attr('max',parseInt(cursor.value.capacity));
$.jStorage.set('currentCap', cursor.value.capacity, { TTL: 28800000 });
});
$('#rangesettings span').each(function () {
$(this).html(cursor.value.capacity);
});
window.location.assign('/static#/view/'+cursor.value.room_id);
cursor.continue();
} else {
resetForm($('#room-usage'));
}
cursor.continue();
} else {
console.log('Entries all displayed.');
if(!($.jStorage.get('reverseroute', ''))) {
reverseroute = 'asc';
} else {
reverseroute = $.jStorage.get('reverseroute', '');
}
var $list = $('#mylist');
var directionSort = {
asc: function (a, b) {
return parseInt(a.id) < parseInt(b.id) ? -1 : 1;
},
desc: function (a, b) {
return parseInt(a.id) > parseInt(b.id) ? -1 : 1;
}
}
var $items = $list.children();
$list.empty().append($items.sort(directionSort[reverseroute]));
appendHref(reverseroute);
//asyncCallToPouchDb();
}
};
// Close the db when the transaction is done
transaction.oncomplete = function() {
db.close();
};
};
}
It turned out that the above was nearly correct, except that it didn't need cursor.continue(); - instead it needed cursor.advance(1); - which should have been obvious because it is only retrieving one record from IndexedDB.
Here's the revised code. (The reason there's a 1 tacked on the end of the variable names is that I have already run one IndexedDB query on the page and I thought the variable names being the same was a bit risky.)
function getPage(roomId) {
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
openRequest1 = window.indexedDB.open("rooms", 1);
openRequest1.onupgradeneeded = function() {
var db1 = openRequest1.result;
var itemStore1 = db1.createObjectStore("rooms", {keyPath: "room_id"});
var index1 = itemStore1.createIndex("rooms", ["room_id"]);
};
openRequest1.onerror = function(event) {
console.error(event);
};
openRequest1.onsuccess = function (event) {
var db1 = openRequest1.result;
db1.onerror = function(event) {
// Generic error handler for all errors targeted at this database's requests
console.error(event.target);
console.log("Database error: " + event.target.error.name || event.target.error || event.target.errorCode);
};
var transaction1 = db1.transaction(['rooms'], "readonly");
var itemStore1 = transaction1.objectStore("rooms");
var index1 = itemStore1.index("rooms", ["room_id"]);
console.log('DB opened');
//setTimeout(function(){ alert("Hello"); }, 3000);
itemStore1.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
if(cursor.value.room_id == roomId) {
resetForm($('#room-usage'));
/* populate form with data */
$('#room-name').each(function () {
$(this).html(cursor.value.room_name); //page header
});
$('#prevroom').each(function () {
$(this).val(parseInt(cursor.value.room_seq) - 1);
});
$('#nextroom').each(function () {
$(this).val(parseInt(cursor.value.room_seq) + 1);
});
$('#sequence').each(function () {
$(this).val(parseInt(cursor.value.room_seq));
$.jStorage.set('currentSeqNo', cursor.value.room_seq, { TTL: 28800000 });
});
$('#route_number').each(function () {
$(this).val(parseInt(cursor.value.route_number));
$.jStorage.set('currentRouteNumber', cursor.value.route_number, { TTL: 28800000 });
});
$('#room_name').each(function () {
$(this).val(cursor.value.room_name); //hidden field
$.jStorage.set('currentRoomName', cursor.value.room_name, { TTL: 28800000 });
//alert($.jStorage.get('currentRoomName',''));
});
$('#room_id').each(function () {
$(this).val(cursor.value.room_id);
$.jStorage.set('currentRoomId', cursor.value.room_id, { TTL: 28800000 });
});
$('#countslider').each(function () {
$(this).attr('max',parseInt(cursor.value.room_capacity));
$.jStorage.set('currentCap', cursor.value.room_capacity, { TTL: 28800000 });
});
$('#rangesettings span').each(function () {
$(this).html(cursor.value.room_capacity);
});
window.location.assign('/static#/view/'+cursor.value.room_id);
//cursor.continue();
cursor.advance(1);
} else {
resetForm($('#room-usage'));
}
// cursor.continue();
// cursor.advance(1);
} else {
console.log('Entries all displayed.');
if(!($.jStorage.get('reverseroute', ''))) {
reverseroute = 'asc';
} else {
reverseroute = $.jStorage.get('reverseroute', '');
}
var $list = $('#mylist');
var directionSort = {
asc: function (a, b) {
return parseInt(a.id) < parseInt(b.id) ? -1 : 1;
},
desc: function (a, b) {
return parseInt(a.id) > parseInt(b.id) ? -1 : 1;
}
}
var $items = $list.children();
$list.empty().append($items.sort(directionSort[reverseroute]));
appendHref(reverseroute);
}
};
// Close the db when the transaction is done
transaction1.oncomplete = function() {
db1.close();
};
};
}

jQuery change opacity of non-matching items

I have the following jquery which has been created with the help of a SO member in a previous question...
var filters = [];
function filterList () {
var classes = '.' + filters.join('.');
$('.test').removeClass('main');
if (classes.length > 1) {
$(classes).addClass('main');
}
}
function removeFilter(ele) {
var len = filters.length,
idx;
for (var i = 0; i < len; i++) {
if (filters[i] === ele) {
idx = i;
break;
}
}
filters.splice(idx, 1);
}
function addFilter(ele) {
if (ele) {
filters.push(ele);
}
}
var selectIt = (function () {
var lastSelect;
return (function (ele) {
if (lastSelect) {
removeFilter(lastSelect);
}
addFilter(ele);
lastSelect = ele;
});
}());
$('.selector').on('change', function (e) {
var val = $(this).val();
selectIt(val);
filterList();
});
$('.mybuttons a').on('click', function (e) {
e.preventDefault();
var el = $(this),
col = el.data('col');
if (el.hasClass('active')) {
removeFilter(col);
} else {
addFilter(col);
}
el.toggleClass('active');
filterList();
});
http://jsfiddle.net/fprL03e5/
I am now trying to modify the code so that when an option is selected, all of the non-matching terms have reduced opacity.
When the page is initially loaded all items should have full opacity until one of the items is selected.
I have tried adding an extra class but can't work out how to have it removed when items are de-selected.
Is this what you're looking to do?
http://jsfiddle.net/fprL03e5/3/
function filterList () {
var classes = '.' + filters.join('.');
$('.test').removeClass('main');
$('.test').css('opacity', '.5');
if (classes.length > 1) {
$(classes).addClass('main').css('opacity', '1');
} else {
$('.test').css('opacity', '1');
}
}

Set and Clear Interval turns into multiple Interval

I am trying to develope a slider, which change every 5 seconds if the user doens´t hit the back- or forward-button.
But if he (the user) does, the interval fires multiple times... why?
I save the Interval in a variable and clear this variable so i don´t know why this dont work... but see yourself:
jQuery.fn.extend({
wrGallery: function() {
return this.each(function() {
// config
var wrClassActive = 'galerie_active';
var wrTime = 5000;
// wrAutomaticDirection gibt an, in welche Richtung
// die Gallerie bei automatischem Wechsel wechseln soll (True = vorwärts/rechts)
var wrAutomaticDirection = true;
var wr = jQuery(this);
var wrGalleryContents = wr.find('.galerie_content');
var wrGalleryContentsFirst = wr.find('.galerie_content:first-child');
var wrBtnBack = wr.find('#galerie_backward');
var wrBtnFor = wr.find('#galerie_forward');
var wrTimer = 0;
var wrI = 0;
var wrOldActiveID = 0;
var wrInit = function() {
wrGalleryContents.each(function() {
wrI++;
jQuery(this).attr('id', wrI);
jQuery(this).css({
display: 'none',
opacity: 0
})
})
wrGalleryContentsFirst.css({
display: 'block',
opacity: 1
})
wrGalleryContentsFirst.addClass('galerie_active')
wrStartTimer();
}
var wrStartTimer = function() {
wrTimer = setInterval(function() {
wrChange(wrAutomaticDirection);
}, wrTime)
}
var wrStoppTimer = function() {
clearInterval(wrTimer);
wrTimer = 0;
}
var wrBackground = function(wrDirection) {
wrOldActiveID = wr.find('.' + wrClassActive).attr('id');
wr.find('.' + wrClassActive).removeClass(wrClassActive);
if (wrDirection) {
wrOldActiveID++;
if (wrOldActiveID <= wrI) {
wr.find('#' + wrOldActiveID).addClass(wrClassActive);
} else {
wr.find('#1').addClass(wrClassActive);
}
} else {
wrOldActiveID--;
if (wrOldActiveID <= wrI) {
wr.find('#' + wrOldActiveID).addClass(wrClassActive);
} else {
wr.find('#3').addClass(wrClassActive);
}
}
}
var wrAnimate = function(wrDirection) {
wrGalleryContents.stop().animate({
opacity: 0
}, 500);
wr.find('.' + wrClassActive).css({
display: 'block'
})
wr.find('.' + wrClassActive).stop().animate({
opacity: 1
}, 500);
}
var wrChange = function(wrDirection) {
wrBackground(wrDirection);
wrAnimate(wrDirection);
}
wr.on('mouseenter', function() {
wrStoppTimer();
});
wr.on('mouseleave', function() {
wrStartTimer();
});
wrBtnBack.on('click', function() {
wrStoppTimer();
wrStartTimer();
wrChange(false);
});
wrBtnFor.on('click', function() {
wrStoppTimer();
wrStartTimer();
wrChange(true);
});
wrInit();
});
}
});
Thanks for reading ;-)
Add a wrStoppTimer() call at the beginning of wrStartTimer:
var wrStartTimer = function() {
wrStoppTimer();
wrTimer = setInterval(function() {
wrChange(wrAutomaticDirection);
}, wrTime)
};
Also in the two click functions you have:
wrStoppTimer();
wrStartTimer();
you can remove that wrStoppTimer() call since wrStartTimer() will call it for you now.
One other thing: if you define functions the way you're doing with var name = function() { ... } you should put a semicolon after the closing } as in the updated code above.

Categories

Resources