I'm using the jquery tokeninput plugin, and I want the json token input data to be dependent upon a value that can be found somewhere in the form.
My code looks like this:
jQuery(function() {
var bparam;
if ($('#tokens')) {
bparam = $('#select_menu').val();
return $('#tokens').tokenInput(("/tokens.json?b=" + bparam)({
theme: 'facebook',
}));
}
});
So the plugin should make a request such as /tokens.json?b=124 if that value from the select_menu div was 124.
Somehow this just doesn't work and I don't know why. I'm still kindof a javascript newbie.
Any help appreciated!
if ($('#tokens')) will return an empty array ([]), so no matter what that will always evaluate to true. I'm guessing you want if ($('#tokens').length). If there is an item in the array it will evaluate to true, if it's empty it evaluates to false.
What's tripping you up is when the variable is being set. bparam is being set on page load. I would bind it to be set when whatever is triggering the event occurs.
Apart from the length > 0 call I had to make (thanks for pointing that out Stuart Nelson and Shusl!), it turned out that the string interpolation in coffeescript somehow wasn't working as I wanted. The same code translated into javascript did actually work.
Coffeescript was being translated into:
jQuery(function() {
var bparam;
if ($('#tokens').length > 0) {
bparam = $('#select_menu').val();
return $('#tokens').tokenInput(("/tokens.json?b=" + bparam)({
theme: 'facebook',
}));
}
});
Now, the working code is, directly written in javascript/jquery ,is:
jQuery(function() {
if ($("#tokens").length > 0) {
var bparam
bparam = $('#select_menu').val();
return $('#tokens').tokenInput("/tokens.json?b=" + bparam, {
theme: 'facebook',
});
}
});
Note these extra parenthesis in
(("/tokens.json?b=" + bparam)
whereas
("/tokens.json?b=" + bparam
is the working solution.
Related
I have a list of variables that I call tags. Each one changes value from true to false depending on the function executed. These 'tags' act as builder pieces for booleans that I'd like to add in other variables. Basically, I'm trying to shorthand the language in order to make complex boolean conditions. Is this code correct for Javascript? The conditions are not passing as I've intended. cleared would read as true while runScreen and runIndicator read as true
Update I shortened the code and made a function to help strengthen the emphasis on the issue. Please see the code below.
Thanks
//builder variables for condition
let testValueA;
let testValueB;
//condition shorthanded inside a variable
const testCondition = !testValueA && testValueB;
// test function for condition
function testCondionValue() {
testValueA=Math.random() > 0.5;
testValueB=Math.random() > 0.5;
console.log("testValueA is", testValueA, "and testValueB is", testValueB);
if (testCondition) {
console.log(" therefore testCondition is true")
}
else {
console.log("therefore testCondition is false")
}
}
This line:
var cleared = (noHover && !runScreen && !runIndicator);
runScreen is true, then !runScreen is false, then cleared is false.
I am programming in Polymer 1.0 and am trying to create an IF function to change the value of a property. My function is the following:
_searchButton: function(selectednamedropdown, selectedtypedropdown){
if (selectednamedropdown=="no_name_selected" && selectedtypedropdown=="no_type_selected"){
this.searchUsagesBtn = true
} else{
this.searchUsagesBtn = false
}
}
In my mind when selectednamedropdown is equal to "no_name_selected" and selectedtypedropdown is equal to "no_type_selected" the function should set searchUsagesBtn to true and when they are not these values, false.
However, the function does not ever seem to be returning true even when these conditions are met. Any ideas why this might be? Thanks for all help
When I run your function like this:
let searchUsagesBtn;
function search(selectednamedropdown, selectedtypedropdown) {
if (
selectednamedropdown === "no_name_selected" &&
selectedtypedropdown === "no_type_selected"
) {
searchUsagesBtn = true;
} else {
searchUsagesBtn = false;
}
}
search("no_name_selected", "no_type_selected");
console.log("button: ", searchUsagesBtn);
I get button: true in console log. So maybe your inputs in this function are not a strings.
The issue was around how JavaScript treats properties within functions. The function was storing the new value and old value of the first property and not any values of the second property. The solution involved making 2 functions to test the strings in each property. Thanks for all assistance
I have an array that contains dates. and for some reason I can't get it to show on my screen I've been debugging for a few days now and I've tracked it down to a single line, but the line has worked before and I can't figure out what the issue might be.
The array looks like this:
var selectItems =
[ "05-26-2017", "06-02-2017", "06-09-2017",
"06-16-2017", "06-23-2017", "06-30-2017", "07-07-2017", "07-14-2017",
"07-21-2017", "07-28-2017"...];
It's passed as an argument from another function, but that's how it's showing in console.log().
I might be going about this the wrong way, maybe even a lot further around then I need to but this is what I've come up with:
1. function setTHead(selectItems) {
2 var formatString;
3. for (var x = 0; x < 12; x++) {
4. formatString = selectItems[x].replace(/[^0-9/-]/g, "").toString();
5. console.log(selectItems);
6. $('#datTab').append("<div id='col" + x + "' class='column'>'" + formatString + "'</div>");
7. }
8. }
the array up top is what's showing from the console.log 5 lines down.
the sixth line is what is seeming to give me issues. Nothing is put on the page at all.
I'm getting a console error saying:
jQuery.Deferred exception: selectItems is undefined setTHead#http://localhost/mySite/script.js:136:9
startUp2#http://localhost/mySite/script.js:146:5
#http://localhost/mySite/table.php:19:9
mightThrow#http://localhost/mySite/lib/jquery.js:3586:52
resolve/</process<#http://localhost/mySite/lib/jquery.js:3654:49
setTimeout handler*resolve/<#http://localhost/mySite/lib/jquery.js:3692:37
fire#http://localhost/mySite/lib/jquery.js:3320:30
fireWith#http://localhost/mySite/lib/jquery.js:3450:29
fire#http://localhost/mySite/lib/jquery.js:3458:21
fire#http://localhost/mySite/lib/jquery.js:3320:30
fireWith#http://localhost/mySite/lib/jquery.js:3450:29
ready#http://localhost/mySite/lib/jquery.js:3923:13
completed#http://localhost/mySite/lib/jquery.js:3933:9
EventListener.handleEvent*#http://localhost/mySite/lib/jquery.js:3949:9
#http://localhost/mySite/lib/jquery.js:39:9
#http://localhost/mySite/lib/jquery.js:17:3
undefined
followed by:
TypeError: selectItems is undefined
and thats pointing to line 6.
if anyone has any advice I would be very much appreciative. Thank you in advance.
EDIT: A little more code:
function startTblView(defSel) {
if (defSel === true) {
setCookie('defSel', true, 7);
} else{
setCookie('defSel', false, 7);
}
saveSelected();
window.open('table.php', '_self');
defSel = getCookie('defSel');
if (defSel) {
selectItems = getDefDates();
}else {
selectItems = reGetSelected();
}
setTHead(selectItems);
}
defSel, is a boolean passed from my last page stating whether I'm doing a default view or a custom view, the custom view is passed from saveSelected();
saveSelected is a function for just saving the selected global value as a cookie so I can pull it out on the next page.
getDefDates pulls the default values for the array
reGetSelected, gets the selected array from the cookie.
I apologize for wonky naming conventions. I'm the only one working on this site and I'm just making sure the names don't overlap.
You can do this :
HTML code
<div id="datTab"></div>
JS code
var selectItems =
[ "05-26-2017", "06-02-2017", "06-09-2017",
"06-16-2017", "06-23-2017", "06-30-2017", "07-07-2017", "07-14-2017",
"07-21-2017", "07-28-2017"];
function setTHead(selectItems) {
var formatString;
$.each( selectItems, function( index, value ){
formatString = value.replace(/[^0-9/-]/g, "").toString();
$('#datTab').append("<div id='col" + index + "' class='column'>'" + value + "'</div>");
});
};
You can use $.each, its better than 'for' with javascript.
The .each() method is designed to make DOM looping constructs concise
and less error-prone. When called it iterates over the DOM elements
that are part of the jQuery object. Each time the callback runs, it is
passed the current loop iteration, beginning from 0. More importantly,
the callback is fired in the context of the current DOM element, so
the keyword this refers to the element.
I did a JsFiddle
Here.
I'm using ExtJs 3.4 and have the following code to create a hidden field:
box.hidden = this.el.insertSibling({
tag: 'input',
type: 'hidden',
value: itemVal,
name: (this.hiddenName || this.name)
}, 'before');
However, when itemVal is a json-string (or a string with quotation characters) it creates an element that looks like:
<input type="hidden" value="[" 635f7ede-7add-415f-8461-548d17027cac.group","bbe2x:101"]"="" name="selector_account_ef8e33ca71e749dca21997f51b404e23" id="ext-gen1766">
The problem is that it cocatenates the html for performance. So I want to, in this case, create the element by setting Ext.DomHelper.useDom to true. Should be an easy fix, right? But the inner code that checks the useDom variable checks against the private object that is passed to Ext.apply function instead of using Ext.DomHelper.useDom. So it doesn't matter if i set Ext.DomHelper.useDom to true inside the function that checks it, it is never true. Se the ExtJs code here:
http://docs.sencha.com/ext-js/3-4/source/DomHelper-more.html
// private
function doInsert(el, o, returnElement, pos, sibling, append){
el = Ext.getDom(el);
var newNode;
if (pub.useDom) {
...
} else {
...
}
return returnElement ? Ext.get(newNode, true) : newNode;
}
I found an old bug report for this that was closed, (http://www.sencha.com/forum/showthread.php?76966-CLOSED-3.0.0-DomHelper-s-useDom-bug) but I don't understand why and HOW I can set useDom to true.
Of course it's simple to fix it by replacing " to " but I want to understand it.
I did this javascript quiz : http://utbm.trunat.fr/CIP/quiz/
It works on normal browser but doesn't even load with Internet Explorer.
It seams that it doesn't recognize the initQuiz() function.
Do you have any idea of how I can fix this ?
Internet Explorer doesn't accept the trailing comma:
question = {'texte': $(this).attr("texte"),
'sound': $(this).attr("sound"),}
Apparently, another error comes from this line:
$('title').html(QUIZ_TITLE[lang]);
Turns out you can't set the title like that in IE. Use document.title = QUIZ_TITLE[lang] instead.
A third error is that you're introducing a new variable, question without the var keyword, which is an error in IE. You're doing it again, later on, in response. Update your loadXML as such:
function loadXML(xml) {
$(xml).find("question").each(function() {
var question = {'texte': $(this).attr("texte"), 'sound': $(this).attr("sound")};
reponses = [];
$(this).find('carre').find('reponse').each(function() {
var reponse = {'texte': $(this).text(), 'sound': $(this).attr("sound"), 'bonne': false};
if($(this).attr('bonne') == "vrai") reponse['bonne'] = true;
reponses.push(reponse);
});
question['reponses'] = reponses;
questions.push(question);
});
startGame(questions);
}
A fourth error is in the way you're verifying that an answer is correct.
if($(this).attr('data-type') == 'true')
You compare the value of the data-type attribute to the string value "true", but when you assign the value, you set it to the boolean value true:
$('#r'+(i+1)+'input').attr('data-type', r.bonne);
To make sure that you're always comparing string values, for instance, you could set the value as such:
$('#r'+(i+1)+'input').attr('data-type', r.bonne.toString());