I have this code that sends the values a user have typed in... the information and numbers are sent as an array and pushed into another array, I then display the text in a dynamically created list element and number in a span element...
var button = $('#add');
button.click(function()
{
var filmnamn = $('#name');
var filmnamnet = filmnamn.val();
var betyg = $('#star');
var betyget = betyg.val();
betyget = Number(betyget);
if(filmnamnet == 0)
{
$('#name').css('background-color', 'red');
}
if(betyget == 0)
{
$('#star').css('background-color', 'red');
}
if(betyget == 0 || filmnamnet == 0)
{
alert("Vänligen fyll i fälten korrekt");
}
else
{
var array = new Array();
array.unshift(betyget);
array.unshift(filmnamnet);
film_array.unshift(array);
betyg_array.unshift(array);
updateFilmList();
}
});
var film_list = $("#filmlista");
var film_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var filmen = film_array[0][0];
var grade = film_array[0][1];
var element = '<li class="lista">' + filmen + '<span class="betyg">'+ grade +'</span></li>';
film_list.append(element);
changeNumber();
}
And at last I have the function that i want to change the number in the span element to the amount of stars that the number shows... this works fine but only for the first created list and span element, when I try to add more listelements the number wont show up as stars, can someone tell me why this happens and point me in the direction to fix the problem?
function changeNumber(){
var elements= document.getElementsByClassName("betyg");
for (var i=0; i<elements.length; i++) {
var element = elements[i];
var length = parseInt(element.innerHTML);
var x=Array(length+1).join("*");
element.innerHTML=x;
}
}
Related
Scenario :
Working on an e-commerce website.
I have put together a function which :
updates the total number of
items in the basket icon, and
also adjusts it when the user increases
or decreases the qty amount for an item in the actual basket page.
I am using local storage to fetch and update the information.
This particular basket page opens up in a new window. The basket icon is shown in pretty much all other pages of the website.
Problem :
Even if the user has another page open in the background, I want that page to also refresh to reflect the new qty amount displayed in the basket icon, the second they adjusts the qty amount from the basket page.
When the user closes the basket page and wants to continue
shopping, the original page - prior to opening the basket page - has
the updated number of items in the basket icon.
There are three ways a user can adjust the number of items in the basket. Each product has an increase / decrease button, and also an input field where the user can enter a number manually and the basket qty icon will reflect the new change.
Following function will change the qty of the item when user clicks either increase or decrease symbol
document.body.addEventListener("click", function(e) {
var reg = /\w{7}\d+/g;
if (e.target.classList[0] === "increaseQty") {
var getItem = getLocalStorageData("basketData");
getItem.basketQty++;
document.getElementById("item-count").innerHTML = getItem.basketQty;
e.target.previousSibling.value++;
var currentProduct = e.target.previousSibling.id;
currentProduct = currentProduct.match(reg);
currentProduct = currentProduct.toString();
getItem[currentProduct]++;
updateLocalStorage(getItem);
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][currentProduct]) {
var currentPrice = e.target.previousSibling.value * productCats[i][currentProduct].price;
var currentLi = e.target.parentNode;
currentLi.parentNode.lastChild.innerHTML = "£" + currentPrice;
getTotalCost();
}
}
} else if (e.target.classList[0] === "decreaseQty") {
if (e.target.nextSibling.value > 0)
var getItem = getLocalStorageData("basketData");
getItem.basketQty--;
document.getElementById("item-count").innerHTML = getItem.basketQty;
e.target.nextSibling.value--;
var currentProduct = e.target.nextSibling.id;
currentProduct = currentProduct.match(reg);
currentProduct = currentProduct.toString();
getItem[currentProduct]--;
updateLocalStorage(getItem);
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][currentProduct]) {
var currentPrice = e.target.nextSibling.value * productCats[i][currentProduct].price;
var currentLi = e.target.parentNode;
currentLi.parentNode.lastChild.innerHTML = "£" + currentPrice;
getTotalCost();
}
}
} else {
return;
}
})
$("#basket-content").on("change", 'input[name="nameQty"]', function() {
var getItem = getLocalStorageData("basketData");
var regNum = /\d+/;
var currentQty = this.id;
var currentVal = this.value;
var reg = /\w{7}\d+/g;
var product = currentQty.match(reg);
product = product.toString();
if (!regNum.test(currentVal) || currentVal < 0) {
alert("Please enter a valid number");
document.getElementById(currentQty).value = getItem[product];
return;
} else if (currentVal > getItem[product]) {
var addQty = currentVal - getItem[product];
getItem.basketQty += addQty;
document.getElementById("item-count").innerHTML = getItem.basketQty;
getItem[product] = currentVal;
} else if (currentVal < getItem[product]) {
var minusQty = getItem[product] - currentVal;
getItem.basketQty -= minusQty;
document.getElementById("item-count").innerHTML = getItem.basketQty;
getItem[product] = currentVal;
}
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][product]) {
var currentPrice = currentVal * productCats[i][product].price;
document.getElementById(currentQty).parentNode.nextSibling.innerText = "£" + currentPrice.toFixed(2);
getTotalCost();
}
}
updateLocalStorage(getItem);
});
I am creating a Judging Form for a research competition and I am trying to use Google Forms to do so. What I am attempting to do is have a drop down list the Research Poster Numbers and have then have the user selected choice from the drop down fill text field for the poster title. I will be pulling the both the Poster Number and Title from an existing spreadsheet.
var caseScoreForm = FormApp.openById('FormTitle');
var scoreSheet = SpreadsheetApp.openById('SpreadSheetName');
var lastRow = scoreSheet.getLastRow();
function fillposterNumbersDropDown(posterNumberRange) {
var posterNumber = caseScoreForm.addListItem();
var posterNumberValue = "";
var posterNumberLog = "";
var posterNumberArr = [];
var posterNumberRange = scoreSheet.getRange('Score Sheet!A2:' + lastRow).getValues();
// loads the posterNumber array
for (var i = 0; i < posterNumberRange.length; i++) {
posterNumberValue = posterNumberRange[i][0];
Logger.log(posterNumberValue);
posterNumberLog = posterNumber.createChoice(posterNumberValue);
posterNumberArr.push(posterNumberLog);
}
posterNumber.setTitle('Poster Number:').setChoices(posterNumberArr).setRequired(true);
}
function setPosterTitleTextResponce(posterTitleRange) {
var posterTitleRange = scoreSheet.getRange('Score Sheet!B2:' + lastRow).getValues();
var posterTitle = caseScoreForm.addTextItem();
var posterTitleValue = "";
var posterTitleLog = "";
var posterTitleArr = [];
var posterNumberIndex = null;
var posterNumberChoices = FormApp.getActiveForm().getItems(FormApp.ItemType.LIST)[1].asListItem().getChoices();
var userChoice = getUserChoice();
//get the users choice index from the posterNumber dropdown
if (userChoice != null) {
for (var i = 0; i < posterNumberChoices.length; i++) {
if (userChoice == posterNumberChoices[i]) { // need getUserChoice();
posterNumberIndex = i;
break;
}
}
}
//loads the posterTitle array
for (var i = 0; i < posterTitleRange.length; i++) {
posterTitleValue = posterTitleRange[i][0];
posterTitleLog = Logger.log(posterTitleValue);
posterTitleArr.push(posterTitleLog);
}
//print out the posterTitle using the posteNumbers index
posterTitle.setTitle('Poster Title:').setRequired(true); // need way to wright to textfield
}
I think all I have left to do is just get the users choice for the active form and print it to the poster Title text field. I know there is the Get pre-filled URL link in Google forms, but we are projecting about 200 entrees for this competition.
If any one has any help/tip/suggestions or have any alternatives, please let me know.
In JS i need to add span as wrapper on the entire document text words.using below code i can able to add wrapper
function walk(root)
{
if (root.nodeType == 3) // text node
{
doReplace(root);
return;
}
var children = root.childNodes;
for (var i = 0;i<children.length ;i++)
{
walk(children[i]);
}
}
function doReplace(text)
{
var start = counter;
counter = counter+text.nodeValue.length;
var div = document.createElement("div");
var string = text.nodeValue;
var len = string.trim();
if(len.length == 0){
return;
}
var nespan = string.replace(/\b(\w+)\b/g,function myFunction(match, contents, offset, s){
var end = start + contents.length;
var id = start+"_"+end;
start = end;
return "<span class='isparent' id='"+id+"'>"+contents+"</span>";
});
div.innerHTML = nespan;
var parent = text.parentNode;
var children = div.childNodes;
for (var i = children.length - 1 ; i >= 0 ; i--)
{
parent.insertBefore(children[i], text.nextSibling);
}
parent.removeChild(text);
}
using above code ill get below result
input :
Stackoverflow is good
out put:
<span>Stackoverflow</span> <span>is</span> <span>good</span>
expecting result:
<span>Stackoverflow </span><span>is </span><span>good</span>
Add optional space character to your regex after the word but before the second word boundary: \b(\w+\s*)\b
Hi i am trying to display list on mouse over if length is >0 then i am displaying count.On mouse over list i want to display list.But in my case list is always displaying when length is >o.How to display list only on mouse over?
what exactly i am trying is
if (feature.attributes.hasOwnProperty("ExceptionType")) {
var exceptionType = 'x,y';
if (exceptionType)
{ var activeExceptions = exceptionType.split(','); }
else
{ var activeExceptions = []; }
var item, items = [];
for (var i = 0; i < activeExceptions.length; i++) {
item = {};
item.activeexception = activeExceptions[i];
items.push(item);
}
var main = $("<ul>");
var str = "<ul>";
for (var i = 0; i < items.length; i++) {
str += "<li>" + items[i].activeexception + "</li>";
}
$('[rel="tooltip"]').tooltip();
main.html(str);
if (activeExceptions.length == 0) {
feature.attributes.Hoverlist = ".showme{display: none}";
feature.attributes.ShowExceptionType = "display:none";
}
else
feature.attributes.Hoverlist = ".showhim:hover .showme{ display : block;}";
feature.attributes.ShowExceptionType = "display:block";
feature.attributes.HoverContent = str;
feature.attributes.ExceptionCount = activeExceptions.length;
}
"description": "<div class='showhim' style='{ShowExceptionType}' ng-mouseover='alert('hi');'>{ExceptionCount}<div class='showme' style='{Hoverlist}'>{HoverContent}</div></div>",
The problem is i need to put my tooltip on top when popup loads.
$('[rel="tooltip"]').tooltip();
NOTE:
The following solution comes from THIS TOPIC, please see that first.
I have 11 inputs:
<input type="text" class="[something]-input inputs">
(Where [something] is a name, different for every input)
$(document).on("change", ".inputs", function(){
var thisclass = $(this).attr('class').split("-")[0];
if($(this).val() == ''){
//
}
highlightInputNumbers(thisclass, 0);
});
The highlightInputNumbers function goes this way:
function highlightInputNumbers(classe, stepcount, empty){
var all= $("td[class*="+classe+"]");
var index = all.length-1;
var concat_steps = $(all[index]).html().split('.')
//var due_serie = $(all[index]).html().split('.')
var due_serie = $('.'+classe+'-input').val().split('.')
for (var i = index; i >= (index-stepcount)+2; i--) {
due_serie = due_serie.concat($(all[i-1]).html().split('.'));
};
//Rimuovo i doppioni
var serieCompleta = [];
$.each(due_serie, function(i, el){
if($.inArray(el, serieCompleta) === -1) serieCompleta.push(el);
});
//Ottengo dati
for(var s = 0; s < index-(stepcount-1); s++){
var bar = $(all[s]);
var barnum = bar.html().split('.');
bar.html('');
var found = 0;
for(i = 0; i<= barnum.length-1; i++){
for(n = 0; n<= serieCompleta.length-1; n++){
if(i != 4){ var punto = '.' }else{ var punto = ''}
/* Problem here:*/
if(barnum[i] == serieCompleta[n]){
bar.append('<span class="highlight">'+barnum[i]+'</span><span class="fade">'+punto+'</span>');
found = barnum[i];
}
}
if(barnum[i] != found){
bar.append('<span class="fade">'+barnum[i]+punto+'</span>');
}
}
}
}
Where I commented /*Problem here*/ is where I highlight the numbers in the column (that I have inserted), but if I remove the numbers in the input they stay highlighted... If I change them it keeps the old ones..
As you can see here: https://dl.dropboxusercontent.com/u/2276958/Cols_and_rows.mov
Small addition in your code.
Let me try to explain what was happening in your code.
At first try:
your code gets the input values (eg. 89.30.20)
Loop through all available values in the table
Split each value by '.'
Then loop through these spitted values to check for match and highlight
Replace the matched number to highlighted span (i.e 20 to 20 and unmatched number to faded span.
This all works for first time. But at the second try, your code breaks from step 3. As in step 3 code tries to split values by '.' but the values were replaced with Span values in your first try. So now to rectify this issue I added small check and 2-3 lines of extra code to extract actual values from Span values.
That extra code is:
// Check if values bar already contains Span tags (means already processed in first try
var hasSpans = bar.find('span').length>0;
if(hasSpans)
{
//If yes then extract the actual values from these span tags without '.' (This will work for all tries after FIRST)
barnum=bar.find('span').map(
function() {
if($(this).html() != '.')
return $(this).html().replace('.','');
}).get();
}
// else normal case, split the values by '.' (This will for very FIRST try)
else barnum = bar.html().split('.');
$(document).on("change", ".inputs", function(){
var thisclass = $(this).attr('class').split("-")[0];
if($(this).val() == ''){
//
}
highlightInputNumbers(thisclass, 0);
});
function highlightInputNumbers(classe, stepcount, empty){
var all= $("td[class*="+classe+"]");
var index = all.length-1;
var concat_steps = $(all[index]).html().split('.')
//var due_serie = $(all[index]).html().split('.')
var due_serie = $('.'+classe+'-input').val().split('.')
for (var i = index; i >= (index-stepcount)+2; i--) {
due_serie = due_serie.concat($(all[i-1]).html().split('.'));
};
//Rimuovo i doppioni
var serieCompleta = [];
$.each(due_serie, function(i, el){
if($.inArray(el, serieCompleta) === -1) serieCompleta.push(el);
});
//Ottengo dati
for(var s = 0; s < index-(stepcount-1); s++){
var bar = $(all[s]);
var barnum;
var hasSpans = bar.find('span').length>0;
if(hasSpans)
{
barnum=bar.find('span').map(
function() {
if($(this).html() != '.')
return $(this).html().replace('.','');
}).get();
}
else barnum = bar.html().split('.');
bar.html('');
var found = 0;
for(i = 0; i<= barnum.length-1; i++){
for(n = 0; n<= serieCompleta.length-1; n++){
if(i != 4){ var punto = '.' }else{ var punto = ''}
/* Problem here:*/
if(barnum[i] == serieCompleta[n]){
bar.append('<span class="highlight">'+barnum[i]+'</span><span class="fade">'+punto+'</span>');
found = barnum[i];
}
}
if(barnum[i] != found){
bar.append('<span class="fade">'+barnum[i]+punto+'</span>');
}
}
}
}
span.highlight{
color:green;
font-weight:bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>02/05/2015</td><td class="bari1">89.10.86.30.65</td></tr>
<tr><td>30/04/2015</td><td class="bari2">96.11.73.36.13</td></tr>
<tr><td>02/05/2015</td><td class="bari3">78.34.50.72.11</td></tr>
<tr><td>30/04/2015</td><td class="bari4">34.78.69.60.22</td></tr>
<tr><td>02/05/2015</td><td class="bari5">12.29.30.69.33</td></tr>
<tr><td>30/04/2015</td><td class="bari6">59.10.20.96.44</td></tr>
<tr><td colspan="2"><input type="text" class="bari-input inputs"></td></tr>
</table>
<table>
<tr><td>02/05/2015</td><td class="vari1">89.10.86.30.65</td></tr>
<tr><td>30/04/2015</td><td class="vari2">96.11.73.36.13</td></tr>
<tr><td>02/05/2015</td><td class="vari3">78.34.50.72.11</td></tr>
<tr><td>30/04/2015</td><td class="vari4">34.78.69.60.22</td></tr>
<tr><td>02/05/2015</td><td class="vari5">12.29.30.69.33</td></tr>
<tr><td>30/04/2015</td><td class="vari6">59.10.20.96.44</td></tr>
<tr><td colspan="2"><input type="text" class="vari-input inputs"></td></tr>
</table>