I am working on a JQuery application where I am trying to change the text of a previous element using $(element).prev().text("Mytext");. But when I scroll up / scroll down the page, the changes I have made are disappeared.
titles = $('.checkGroup:checked').parent().map(function () {
return $(this).text();
}).get(); // Generate Array of Titles
for (i = 0; i < titles.length; i++) {
$('span[level ="' + i + '"]').prev().text(titles[i]);
}
this is my code snippet. please help me to fix this
To fix this add the following JS.
Note that this is a quick fix. There must be some callback functions you can use to have the same end effect. The Slick.Grid plugin is rendering the HTML on scroll. Hence the issue.
Events for SlickGrid.
Edit 1:
grid.onScroll.subscribe(function(e,args){
$('.checkGroup:checked').parent().each(function (i, val) {
$('span[level ="' + i + '"]').each(function(){
$(this).prev().text($(val).text());
});
});
})
Normally the following might have worked. But the SlickGrid had many mysteries of its own. Its not a scroll event.
$(document).on('scroll', '.slick-viewport',function(){
$('.checkGroup:checked').parent().each(function (i, val) {
$('span[level ="' + i + '"]').each(function(){
$(this).prev().text($(val).text());
});
});
})
Related
I wrote some code that generates a bunch of html-elements based on a Json-Object. I add it to the page by JQuerys .append() and .after().
It does work perfectly often, but sometimes the outer loop is only executed once and stops at $( '#'+inputname ).entityselector().
function addlinks(qid, prop) {
html="<fieldset id=\"quickpresets\">" +
"<legend>Quick Presets (" + prop.name + ")</legend></fieldset>";
$('.wikibase-statementgrouplistview').first().after( html );
for( var p = 0; p < prop.defaults.length; p++ ) {
pid=prop.defaults[p].pid;
pname=prop.defaults[p].name;
pvalues=prop.defaults[p].values;
inputname="input"+pname;
pclass="addstatement";
if($('#P'+pid).find(".wikibase-snakview-value a").length !== 0) {
pclass += " disabled";
}
str="<p class='"+pclass+"'>Add "+pname+":";
for( var i = 0; i < pvalues.length; i++) {
toqid=pvalues[i].qid;
toname=pvalues[i].name;
str += " <a href='javascript:void(0);' onclick=\""+
"additemstatement("+qid+","+pid+",'"+pname+"',"+ toqid +",'" + toname+ "')\">" + toname+ "</a>"+
" ∙";
}
str += "<span class=\"quickpresetsinput\"><input id='"+inputname+"'/> ";
str += "<a href=\'javascript:void(0);\' onclick=\""+
"onselectitem("+qid+","+pid+",'"+pname+"','"+ inputname +"')\">✔</a>";
str += "</span></p>";
$('#quickpresets').append( str );
input = $( '#'+inputname ).entityselector( {
url: 'https://www.wikidata.org/w/api.php',
language: mw.config.get('wgUserLanguage')
} );
}
}
How do I fix this issue? And what other things are there that I should do to improve this ugly code?
Updates:
I get the following error in the console:
TypeError: $(...).entityselector is not a function [Weitere
Informationen]
The full code can be found here.
I have to use ES5.
The data is always the same ("hard coded") JSON.
See below for the better readable version of Roamer-1888 – which still causes the same bug.
It's not apparent in the code why .entityselector() should throw on some occasions. The most likely reason is that you are trying to invoke the plugin before it is loaded.
In an attempt to fix the issue, you might try initialising all the inputs in one hit instead of individually in the loop.
Also, the code would be made more readable by attaching a fairly simple fragment to the DOM, then immediately adding links and attaching event handlers with jQuery.
Here it is the way I would write it (with a bunch of tidying up) :
function addlinks(qid, prop) {
// compose and intert fieldset.
var $fieldset = $("<fieldset><legend>Quick Presets (" + prop.name + ")</legend></fieldset>")
.insertAfter($('.wikibase-statementgrouplistview').first());
// loop through prop.defaults
prop.defaults.forEach(function(dflt) {
// compose and append a basic fragment ...
var $fragment = $("<p class='addstatement'>Add " + dflt.pname + ":<span class=\"links\"></span>"
+ "<span class=\"quickpresetsinput\"><input /> ✔</span></p>")
.appendTo($fieldset);
// ... then allow jQuery to augment the appended fragment :
// i) conditionally addClass('disabled')
if($('#P' + dflt.pid).find(".wikibase-snakview-value a").length !== 0) {
$fragment.addClass('disabled');
}
// ii) loop through dflt.values and add links.
dflt.values.forEach(function(val) {
$("<span> ∙</span>")
.appendTo($fragment.find('span.links'))
.find('a')
.text(val.name)
.on('click', function(e) {
e.preventDefault();
additemstatement(qid, dflt.pid, dflt.pname, val.qid, val.name);
});
});
// iii) attach click handlers to the quickpresets inputs
$fragment.find('.quickpresetsinput').find('a').on('click', function(e) {
e.preventDefault();
var selection = $(this).prev('input').data('entityselector').selectedEntity();
additemstatement(qid, dflt.pid, dflt.pname, selection.id.substring(1), selection.label);
});
});
// invoke .entityselector() on all the quickpresets inputs in one hit
$('.quickpresetsinput input').entityselector({
'url': 'https://www.wikidata.org/w/api.php',
'language': mw.config.get('wgUserLanguage')
});
}
untested except for syntax
That's certainly tidier though without a proper understanding of the original issue, .entityselector() may still throw.
I have a d3 area chart with a tooltip that displays the same text in two different divs. The first div, .tooltip.headline.record, displays the selected value in bold. Another div class, .record-label, displays the all of the values at a given point on the x-axis — for both the selected and non-selected paths. Here's a Plunker of the problem.
To illustrate, it currently looks like this:
I've been trying to achieve a result like this:
... or like this:
I've tried the following methods of hiding or removing the duplicative .record-label div, without success — and without error messages to assist in further diagnosis.
function getRecordContent(obj, pos) {
if ( $(".tooltip-headline-record").text() == $(".record-label").text() ) {
$(".record-label").hide();
//$(".record-label").remove();
//console.log("same");
}
return '<li><div class="record-label">' + obj.state + " " + obj.record.toLowerCase() + " " + numFormat(obj.values[pos].y) + '</div></li>'
}
Here, again, is a Plunker that demonstrates the problem I'm trying to solve (see, specifically, the code beginning at line 480:
http://plnkr.co/edit/NfMeTpXzXGTxgNFKPFJe?p=preview
Is this what you're looking for?
Plunkr
Relevant code changes:
The whole dataset was being passed to the getRecordContent function. So I changed that: when hovered over "admissions", pass "transfers" and "codependents". (line: 435)
var filtered_dataset = dataset.filter(function(row){return row.record !== d.record; });
for (var i = 0; i < filtered_dataset.length; i++) {
content += getRecordContent(filtered_dataset[i], idx);
}
Seems like you need to specify the state name as well along with the record. (line 480)
return '<li><span class="record-label">' + obj.state + ' ' + obj.record.toLowerCase() + '</span><span class="record-value">' + numFormat(obj.values[pos].y) + '</span></li>'
Edit:
Changes made for the tooltip to adapt to the main chart as well:
var filtered_dataset = dataset.filter(function(row){return row.record !== d.record && row.state === d.state; });
Changed z-index for the tooltip in main.css (try removing it and hovering close to the jquery slider)
z-index: 2;
Hope this helps. :)
I have a textbox that comma separated/delimited values are entered into which I have to make sure has unique entries. Solved that using Paul Irish's Duck Punching example #2 and tying it to onblur for that textbox.
The values entered into the textbox get broken out into a table. As the table can get very lengthy, I found Mottie's Tablesorter to work brilliantly.
The problem is, the the Duck Punching code is breaking the Tablesorter. The style for the Tablesorter is passed through just fine, but the table doesn't actually sort. BUT, when I comment out the Duck Punching code, Tablesorter miraculosly works.
My coding skills are not such that I can figure out why the two are conflicting. Any assistance would be much appreciated.
I haven't modified the Tablesorter code or added any special sorting elements to it...just following the very basic example right now. Here's the Duck Punching code which I've only modified to include the var for the textbox I need to have unique entries.
function ValidateTextBox1()
{
(function($){
var arr = document.getElementById("TextBox1").value.split(',');
var _old = $.unique;
$.unique = function(arr){
// do the default behavior only if we got an array of elements
if (!!arr[0].nodeType){
return _old.apply(this,arguments);
} else {
// reduce the array to contain no dupes via grep/inArray
return $.grep(arr,function(v,k){
return $.inArray(v,arr) === k;
});
}
};
})(jQuery);
}
The function above is in a separate js file which is called via onblur for TextBox1.
Then, I have a button which runs the following:
function GenerateTable()
{
var Entry1 = document.getElementById("TextBox1").value
var Entry2 = document.getElementById("TextBox2").value
var content = "<table id=myTable class=tablesorter ><thead><tr><th>Entry 1 Values</th><th>Entry 2 Value</th></tr></thead><tbody>"
var lines = Entry1.split(","),
i;
for (i = 0; i < lines.length; i++)
content += "<tr><td>" + (Entry1.split(",")[i]) + "</td><td>" + Entry2 + "</td></tr>";
content += "</tbody></table>"
$("#here_table").append(content);
$(function(){
$("#myTable").tablesorter({
theme: 'default'
});
});
}
The function will generate/append the table in a specific DIV.
If I leave in the validation code for TextBox1, the table will generate but isn't sortable (though it does manage to still pull the theme).
If I remove the validation code, the table will generate and is sortable.
The validateText box function above will not work as expected. In this case, "duck-punching" is not even necessary.
Here is how I would fix the script (demo):
HTML
<textarea id="textbox1">6,1,7,5,3,4,3,2,4</textarea><br>
<textarea id="textbox2">column 2</textarea><br>
<button>Build Table</button>
<div id="here_table"></div>
Script (requires jQuery 1.7+)
(function($) {
// bind to button
$(function () {
$('button').on('click', function () {
// disable button to prevent multiple updates
$(this).prop('disabled', true);
generateTable();
});
});
function unique(arr) {
return $.grep(arr, function (v, k) {
return $.inArray(v, arr) === k;
});
}
function generateTable() {
var i,
$wrap = $('#here_table'),
// get text box value, remove unwanted
// spaces/tabs/carriage returns & create an array
val = $('#textbox1').val().split(/\s*,\s*/),
// get unique values for Entry1
entry1 = unique( val ),
entry2 = $('#textbox2').val(),
content = "";
// build tbody rows
for (i = 0; i < entry1.length; i++) {
content += "<tr><td>" + (entry1[i] || '?') + "</td><td>" + entry2 + "</td></tr>";
}
// update or create table
if ($wrap.find('table').length) {
// table exists, just update the data
$wrap.find('tbody').remove();
$wrap.find('table')
.append(content)
.trigger('update');
} else {
// table doesn't exist, build it from scratch
$wrap
.html('<table id=myTable class=tablesorter><thead><tr>' +
'<th>Entry 1 Values</th>' +
'<th>Entry 2 Value</th>' +
'</tr></thead><tbody>' + content + '</tbody></table>')
.find('table')
.tablesorter({
theme: 'blue'
});
}
// enable the button to allow updating the table
$('button').prop('disabled', false);
}
})(jQuery);
I tried to add a few comments to make more clear what each step is doing. Please feel free to ask for any clarification.
I had asked a question about How to open option list of HTML select tag on onfocus(). At that time it solved my problem but I missed one problem that every time on opening a html select option onfocus next select option went disappear.
I not able to find whats going wrong with this code.
here is link for that problematic question jsFiddle.
Yes, that's what the lines
var x = "select[tabindex='" + (parseInt($(this).attr('tabindex'),10) + 1) + "']";
$(x).fadeTo(50,0);
do. They hide the next select, because otherwise it would show on top of the expanded one.
This isn't a good solution at all though. Instead i'd use z-index to prevent that from happening:
$('select').focus(function(){
$(this).attr("size",$(this).attr("expandto")).css('z-index',2);
});
$('select').blur(function(){
$(this).attr("size",1).css('z-index','1');
});
$('select').change(function(){
$(this).attr("size",1).css('z-index','1');
});
It would be even better to use a class instead of inline style. But i used that just as a demonstration.
http://jsfiddle.net/PpTeF/1/
Just comment out the fadeTo function. check this http://jsfiddle.net/PpTeF/2/
$(document).ready(function(){
$('select').focus(function(){
$(this).attr("size",$(this).attr("expandto"));
var x = "select[tabindex='" + (parseInt($(this).attr('tabindex'),10) + 1) + "']";
//$(x).fadeTo(50,0);
});
$('select').blur(function(){
$(this).attr("size",1);
var x = "select[tabindex='" + (parseInt($(this).attr('tabindex'),10) + 1) + "']";
//$(x).fadeTo('fast',1.0);
});
$('select').change(function(){
$(this).attr("size",1);
var x = "select[tabindex='" + (parseInt($(this).attr('tabindex'),10) + 1) + "']";
//$(x).fadeTo('fast',1.0);
});
});
Cheers!!
I have two dropdowns, the second dropdown shall change when something is changed in the first dropdown, this is working fine in Firefox, but not in IE. (IE9). Then in the second dropdown, I'm looping through the items, and hiding some of them.
var intermin = '${intermin}';
var intermin2=intermin.substring(1,3);
$('#startSemester').change(function() {
var start=$('#startSemester').val();
var end=$('#endSemester').val();
var start1=start.substring(0,1);
var start2=start.substring(1,3);
var start3="";
var end3="";
if (start1=="H"){
start3="2";
}
else
start3="1";
var start4=start2+start3;
$('#endSemester option').removeAttr("disabled");
var endSemesters= $('#endSemester');
$.each($('option', endSemesters), function(index, value) {
var end= ($(this).val());
var end2=end.substring(1,3);
var end1=end.substring(0,1);
if (end1=="H"){
end3="2";
}
else
end3="1";
var end4=end2+end3;
$('#endSemester ' + 'option' + '[value =' + end + ']').show();
if (end4 < start4 || end2 > intermin2) {
$('#endSemester ' + 'option' + '[value =' + end + ']').hide();
}
});
});
Is there some way of having this working in IE.
The problem with IE is the hiding option part. IE doesn't support much CSS on option elements.
Especially display: none which is what .hide() does.
Therefor I believe it's best for you to disable the option.
var changeOption = $('#endSemester ' + 'option' + '[value=' + end + ']');
changeOption.prop("disabled", false);
if (parseInt(end4) < parseInt(start4) || parseInt(end2) > parseInt(intermin2)) {
changeOption.prop("disabled", true);
}
You can test this in various browsers: http://jsfiddle.net/tive/wU6XL/
Or if you're persistent enough find a plugin that:
hides the select control and uses a replacement ul li structure
wraps <option /> with a span (demo1 demo2)
PS: you might want to change the option values accordingly since I have no view on your HTML.
Hey Please refer This code
<asp:DropDownList ID="ddlWeeklyWeightIn" runat="server" ClientIDMode="Predictable">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:DropDownList>
Js Code Is
$('#ddlWeeklyWeightIn').on("change", function () {
alert($(this).val());
});
Please refer Link See Demo
Hope it helps you.