Problems with Get / Set value to text - javascript

I'm trying to when I press button (Get Value) to set the size of checkboxes to text. I make the variable (numAll) global, and convert toString, but still not working. any idea to solve the solution?
Demo
Jquery:
$(function () {
// Click function to add a card
var $div = $('<div />').addClass('sortable-div');
$('<label>Title</label><br/>').appendTo($div);
$('<input/>', {
"type": "text",
"class": "ctb"
}).appendTo($div);
$('<input/>', {
"type": "text",
"class": "date"
}).appendTo($div);
$('<input/>', {
"type": "text",
"class": "Cbox"
}).appendTo($div);
var cnt = 0,
$currentTarget;
$('#AddCardBtn').click(function () {
var $newDiv = $div.clone(true);
cnt++;
$newDiv.prop("id", "div" + cnt);
$newDiv.data('checkboxes', []);
$('#userAddedCard').append($newDiv);
// alert($('#userAddedCard').find("div.sortable-div").length);
});
$("#Getbtn").on("click", function () {
var val = $("#customTextBox").val();
$currentTarget.find(".ctb").val(val);
$currentTarget.find(".date").val($("#datepicker").val());
var Cboxval = numAll;
var st = console.toString(Cboxval);
$currentTarget.find(".Cbox").val(st);
$currentTarget.data('checkboxes', $('#modalDialog').data('checkboxes')); /* Copy checkbox data to card */
//$('#modalDialog').dialog("close");
});
var numAll;
function updateProgress() {
var numAll = $('input[type="checkbox"]').length;
var numChecked = $('input[type="checkbox"]:checked').length;
if (numAll > 0) {
var perc = (numChecked / numAll) * 100;
$("#progressbar").progressbar("value", perc)
.children('.ui-progressbar-value')
.html(perc.toPrecision(3) + '%')
.css("display", "block");
}
}

You should use .toString() method on a Number Object:
var st = Cboxval.toString();
Otherwise I can't find where are you defining the numAll variable, so I had to replace
var Cboxval = numAll;
with:
var Cboxval = numAll === undefined ? 0 : numAll;
in order to be able to perform mys tests.
Here you have an updated version of your JS fiddle.

Related

how to append a new hyperlink with a new id each time in a loop?

It's my second day on this project :\
I'm trying to create is : creating a new <a> element with a new href and id attributes in for loop so that I can get each output of the API as a link.
This is my JS Code
var one;
var two;
var hoba;
$(document).ready(function() {
$("#inp").keyup(function() {
hoba = $(this).val();
});
$("#but").on("click", function() {
var app = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles=Main+Page&rvprop=content&origin=*&srsearch=" + hoba;
$.getJSON(app, function(data) {
for (i = 0; i < data.query.search.length; i++) {
console.log(app);
one = $("<a></a>").text(data.query.search[i].title);
//var _href = $("a").attr("href");
$("a").attr("href", 'https://www.wikipedia.org/wiki/' + data.query.search[i].title);
$("a").attr("id", data.query.search[i].title);
two = document.createElement("p");
two.innerHTML = data.query.search[i].snippet;
$("body").append(one, two);
}
});
});
});
Use same object to set attributes
one = $("<a></a>");
one.text(data.query.search[i].title);
one.attr("href", 'https://www.wikipedia.org/wiki/' + data.query.search[i].title);
one.attr("id", data.query.search[i].title);
Use jQuery( html, attributes ) to create HTML element.
var anchor = $("<a></a>", {
"text": data.query.search[i].title,
"href": 'https://www.wikipedia.org/wiki/' + data.query.search[i].title,
"id": data.query.search[i].title
});
$("body").append(anchor);
$(document).ready(function() {
$("#inp").keyup(function() {
hoba = $(this).val();
});
$("#but").on("click", function() {
var app = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles=Main+Page&rvprop=content&origin=*&srsearch=" + hoba;
$.getJSON(app, function(data) {
for (i = 0; i < data.query.search.length; i++) {
var anchor = $("<a></a>", {
"text": data.query.search[i].title,
"href": 'https://www.wikipedia.org/wiki/' + data.query.search[i].title,
"id": data.query.search[i].title
});
var p = $("<p></p>", {
"html": data.query.search[i].snippet
});
$("body").append(anchor);
$("body").append(p);
}
});
});
});
You should to do minor changes in your code as below.
Change code are in between
// Changes Code Start and // Changes Code End
var one;
var two;
var hoba;
$(document).ready(function(){
$("#inp").keyup(function(){
hoba = $(this).val();
});
$("#but").on("click",function(){
var app = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles=Main+Page&rvprop=content&origin=*&srsearch="+hoba;
// Changes Code Start
$.getJSON(app,function(data){
for(i=0; i<data.query.search.length; i++){
console.log(app);
var dataAppend;
var title = data.query.search[i].title;
var href = 'https://www.wikipedia.org/wiki/' + data.query.search[i].title;
var id = data.query.search[i].title;
dataAppend = "<a href='"+href+"' id='"+id+"'>"+title+"</a>";
dataAppend += "<p>"+data.query.search[i].snippet+"</p>";
// \"
$("body").append(dataAppend);
}
});
// Changes Code End
});
});

How to customize autocomplete function of the CodeMirror

I want to customize an autocomplete function to Codemirror.
So I have build this code:
CodeMirror.commands.autocomplete = function (cm) {
var arrayTabNONDefault = new Array();
var stringaCampi = null;
var arrayTabellaCampo = null;
var textVal = cm.getValue();
textVal = textVal.toUpperCase();
var res = textVal.match("SELECT(.*)FROM");
if (res != null) {
stringaCampi = res[1];
arrayTabellaCampo = stringaCampi.split(",");
var nomeTab = null;
for (var i = 0; i < arrayTabellaCampo.length; i++) {
nomeTab = (arrayTabellaCampo[i].split(".")[0]).trim();
if (hintTables[nomeTab] == null)
hintTables[nomeTab] = new Array();
} //FINE FOR
} //FINE IF
CodeMirror.showHint(cm, CodeMirror.hint.sql, {
tables: hintTables
});
cm.on("beforeChange", function (cm, change) {
var before = cm.getRange({ line: 0, ch: 0 }, change.from);
var text = cm.getRange(change.from, change.to);
var after = cm.getRange(change.to, { line: cm.lineCount() + 1, ch: 0 });
if (before.indexOf("FROM") !== -1)
// alert("Ho scritto FROM");
console.log("before change", before, text, after);
});
cm.on("change", function (cm, change) {
var from = change.from;
var text = change.text.join("\n");
var removed = change.removed.join("\n");
var to = cm.posFromIndex(cm.indexFromPos(from) + text.length);
var before = cm.getRange({ line: 0, ch: 0 }, from);
var after = cm.getRange(to, { line: cm.lineCount() + 1, ch: 0 });
if (before.indexOf("FROM") !== -1)
console.log("after change", before, removed, text, after);
});
} //FINE ESTENSIONE
This is the content of hintTables
var hintTables = { "#T_TF_FilesList": ["FilesListHeaderID", "NumRecord", "FileTypeID", "FileID", "FilesListHeaderID", "NumRecord"],
"#T_TF_SelectedItems": ["EventHeaderID", "ItemType", "ItemID1", "ItemID2", "EventHeaderID", "ItemType", "ItemID1", "ItemID2"],
"#T_TFT_CacheSearchCriteriaHeaders": ["ID", "SyncDate", "FileTypeID", "CriteriaExpressionString", "CriteriaExpressionHash", "PageRecordsNumber", "PageNumber", "NumFiles"]
};
So I want that the system should propose a list of this table after I write FROM, or the system should to propose a list of stored procedures after I write EXECUTE.
It is possible to do this?
Are you trying to customize the SQL hint addon? If so, you should make changes inside sql-hint.js (under codemirror/addon/hint).
Basically what you should do is:
1.In your app.js (whatever js file for your main logic) call editor.showHint({hint: CodeMirror.hint.sql) on "change" event;
2.Inside sql-hint.js, return {list: hintTables, from: somePos, to: somePos} when the user types FROM or EXECUTE which can be detected by regular expression or inspecting the tokens at the line. I made up some code for your reference:
var cursor = editor.getCursor();
var tokenAtCursor = editor.getTokenAt(cursor);
if (tokenAtCursor.type == "FROM-and-EXECUTE")
return {list: hintTables,
from: CodeMirror.Pos(cur.line, tokenAtCursor.start),
to: CodeMirror.Pos(cur.line, tokenAtCursor.end)};
If I misunderstand your question and this answer is not helpful, please tell me and I will delete it.

prettyPhoto change title on hover over thumbnail

I use prettyPhoto version: 3.1.6 to display simple lightbox with thumbnail.
Normally title attribute appear inside the lightbox for the active/selected image.
My client ask for this change
http://i.stack.imgur.com/7932x.jpg
How I can accomplish this?
Here is a part of my code
<a rel="prettyPhoto[pp_gal]"href="1.jpg" title="Staring at the sun"><img src="2.jpg"></a>
try this jquery function. You may have to style it a little.
(function($)
{
$.fn.avia_activate_lightbox = function(variables)
{
var defaults =
{
autolinkElements: 'a[rel^="prettyPhoto"], a[rel^="lightbox"], a[href$=jpg], a[href$=png], a[href$=gif], a[href$=jpeg], a[href$=".mov"] , a[href$=".swf"], a[href$=".flv"] , a[href*="vimeo.com"] , a[href*="youtube.com"]'
};
var options = $.extend(defaults, variables);
var imagedefaults =
{
autolinkImages: 'img[title!=""]'
};
return this.each(function()
{
var elements = $(options.autolinkElements, this),
lastParent = "",
counter = 0;
var images = $(imagedefaults.autolinkImages, this),
imgcounter = 0;
var alltitlesalt = new Array();
var alltitles = new Array();
images.each(function()
{
if($(this).attr('alt') != undefined && $(this).attr('alt') !="")
{
alltitlesalt.push($(this).attr('alt'));
}
else
{
alltitlesalt.push("");
};
alltitles.push($(this).attr('title'));
});
elements.each(function()
{
var el = $(this),
parentPost = el.parents('.post-entry:eq(0)'),
group = 'auto_group';
if(parentPost.get(0) != lastParent)
{
lastParent = parentPost.get(0);
counter ++;
}
if((el.attr('rel') == undefined || el.attr('rel') == '') && !el.hasClass('noLightbox'))
{
el.attr('rel','lightbox');
el.attr('title',alltitles[imgcounter]);
el.attr('alt',alltitlesalt[imgcounter]);
imgcounter ++;
}
});
if($.fn.prettyPhoto)
elements.prettyPhoto({ "theme": 'premium_photo', 'slideshow': 5000 }); /* facebook /light_rounded / dark_rounded / light_square / dark_square */
});
};
})(jQuery);
Reference

getJSON returning undefined

I'm trying to make an automatic news feed on a project website, where all the posts are put into a JSON file and then formatted on the news page accordingly. I've finally figured out how to get the json parser to show SOMETHING but that something is just a bunch of "undefined" bits all over the page. What am I doing wrong?
The jquery/html snippet
<script>
$.getJSON("js/news.json", function (data) {
$.each(data.posts, function (val) {
var title = val.title;
var date = val.date;
var content = val.content;
$("#newscontainer").append('<div><h1>' + title + '</h1><h2>' + date + '</h2><p>' + content + '</p></div>');
});
});
</script>
<div id='newscontainer'>
</div>
The JSON snippet
{
"posts": [
{
"title": "title1",
"date": "8302014",
"content": "LotsoftextLotsoftext"
},
{
"title": "title2",
"date": "8312014",
"content": "CopiousquantitiesoftextCopiousquantitiesoftext"
},
{
"title": "title3",
"date": "8322014",
"content": "onlyalittletext"
}
]
}
val in your code is the index, you should use the second argument of the callback.
$.each(data.posts, function (index, val) {
You can also use the this keyword.
Try this one :
var post_title = val.title;
var post_date = val.date;
var post_content = val.content;
var divTag = document.createElement("div");
newscontainer.appendChild(divTag);
var h1Tag = document.createElement("h1");
h1Tag.innerHTML = post_title;
newscontainer.appendChild(h1);
var h2Tag = document.createElement("h2");
h2Tag.innerHTML = post_date;
newscontainer.appendChild(h2);
var pTag = document.createElement("p");
pTag.innerHTML = post_content;
newscontainer.appendChild(p);
You can use the each() function on your list:
$(data.posts).each(function() {
var $this = this;
$("#newscontainer").append('<div><h1>' + $this.title + '</h1><h2>' + $this.date + '</h2><p>' + $this.content + '</p></div>');
});

Selecting element and replacing text inside each()

I have a list which looks like the following:
<ul id="offers">
<li class="unique-id-here">
<span class="country">US</span>
<span class="clicks">192</span>
<span class="ctr">9%</span>
</li>
</ul>
And i am trying to update the .clicks with new values every 5 seconds.
So my though was, select each li -> get the unique-id-here -> save the id to a variable -> to a $.get request to request the clicks for that given id -> replace the current clicks with the new ones.
Problem is that i cannot seem to select the .clicks properly... this is what my jQuery code looks like:
var refreshId = setInterval(function() {
$("#offers li").each(function(){
var a = $(this).attr('class');
if(a) {
$.get("ajax.php", { opt: "stats", oid: a }, function(r) {
var j = eval('(' + r + ')');
$(this).find('.clicks').text('<strong>'+j.message.clicks+'%</strong>');
});
}
});
}, 5000);
Any ideas on how i can replace the .clicks value of each li field properly?
Help is much appreciated :)
Try:
var refreshId = setInterval(function() {
$("#offers li").each(function(){
var $li = $(this),
a = $li.attr('class');
if(a) {
$.get("ajax.php", { opt: "stats", oid: a }, function(r) {
var j = eval('(' + r + ')');
$li.find('.clicks').html('<strong>'+j.message.clicks+'%</strong>');
});
}
});
}, 5000);
You are using $(this) inside the $.get, which would refer to another object. Also, why are you using eval? Why not return a JSON object to the request?
In addition, you are using text(), however the string you pass to the parameter contains HTML (<strong>). Thus, I switched text() with html().
You could do:
var refreshId = setInterval(function() {
$("#offers li").each(function(){
var clicks = $(this).find('.clicks');
var a = $(this).attr('class');
if(a) {
$.get("ajax.php", { opt: "stats", oid: a }, function(r) {
var j = eval('(' + r + ')');
clicks.text('<strong>'+j.message.clicks+'%</strong>');
});
}
});
}, 5000);
i think that your problem is that $(this) inside the success function of tha AJAX call has not the scope you think. another thing you could do is:
var refreshId = setInterval(function() {
$("#offers li").each(function(){
var $that = $(this);
var a = $(this).attr('class');
if(a) {
$.get("ajax.php", { opt: "stats", oid: a }, function(r) {
var j = eval('(' + r + ')');
$that.find('.clicks').text('<strong>'+j.message.clicks+'%</strong>');
});
}
});
}, 5000);

Categories