I'm new to coffeescript and javascript
I wrote a simple code =>
1 number = 42
2 coffee = ->
3 ans = confirm "Ready?"
4 "your answer is #{ans}"
And I put the generated javascript into html
call the coffee function by clicking the button,
but it didn't show the alert window,and Firebug told me "ReferenceError: coffee is not defined
"
1 <head>
2 <script type=”text/javascript” src=”http://codeorigin.jquery.com/jquery-1.10.2.js"> </script>
3 <script type="text/javascript" >
4 // Generated by CoffeeScript 1.6.3
5 $(document).ready(
6 function(){
7
8 var coffee, fk, number;
9
10 number = 42;
11
12 coffee = function() {
13 var ans;
14 ans = confirm("Ready?");
15 return "your answer is " + ans;
16 };
17 });
18
19 </script>
20 </head>
21 <body>
22 <input type=button name="lala" value="hihi" onclick="coffee();">
23 </body>
You need to export the parts of your script that you want visible to the outside world.
Easiest way would be to do
window.myCoffee = {}
number = 42
myCoffee.coffee = ->
ans = confirm "Ready?"
"your answer is #{ans}"
That is because the script is wrapped into its own private scope.
But since you are already using jQuery, a better solution would be to attach the click handler to the DOM element.
number = 42
$('input').click ->
ans = confirm "Ready?"
"your answer is #{ans}"
Finally, returning a String from onClick seems not so useful. Maybe alert?
You're defining the coffee function as a local variable to another function, so it won't be available in the global scope.
It's not recommended to put the onclick events to elements in HTML anyway, so attaching the event with jQuery should fix the problem:
number = 42
coffee = ->
ans = confirm "Ready?"
"your answer is #{ans}"
$("input[name=lala]").on "click", coffee
Related
I wish to get the "Testing 2" text inside a class called "inner" as shown below.
<div _ngcontent-c6="" class="inner">
<h1 _ngcontent-c6=""> Testing 2
</h1>
</div>
I tried "return element(by.css('.inner')).element(by.css("h1")).getText();" and "return element(by.className('inner')).element(by.css("h1")).getText();" but both codes are not working.
When running the said codes I got the same error saying "Failed: No element found using locator: By(css selector, h1)"
How can I get the value of h1 inside a div with a class name?
Try wait for a while.
var EC = protractor.ExpectedConditions;
var target = element(by.css('div.inner > h1'));
browser.wait(EC.presenceOf(target), 15*1000);
target.getText().then(function(txt){
console.log('H1: ' + txt);
});
I have the following data in a Google Spreadsheet:
ColumnA ColumnB
Departament Quantity
01/01/2016 23
02/01/2016 43
04/01/2016 5
06/01/2016 65
10/01/2016 12
11/01/2016 32
13/01/2016 22
15/02/2016 2
And want to draw a linechart using HTML Templates: This is my code so far now
<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/jsapi"></script>
</head>
<body>
<div id="main"></div>
<script>
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(getSpreadsheetData);
function getSpreadsheetData() {
google.script.run.withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(rows) {
var options = {'title':'Example','width':400,'height':300};
var data = google.visualization.arrayToDataTable(rows, false);
var chart = newgoogle.visualization.LineChart(document.getElementById("main"));
chart.draw(data, options)
}
</script>
</body>
</html>
My script to read the sheet:
function getSpreadsheetData() {
var ssID = "12GvIStMKqmRFNBM-C67NCDeb89-c55K7KQtcuEYmJWQ",
sheet = SpreadsheetApp.openById(ssID).getSheets()[0],
data = sheet.getDataRange().getValues();
return data;
}
However i cant draw the plot, this issue dissapear when i change the data to a numeric (i.e. 42370), but thats not what i want!
Question is: what do i have to add in order to change to the right format in x axis?
You can use the hAxis.format configuration option
var options = {'title':'Example','width':400,'height':300,//-->'format':'MM/dd/yyyy'};
The valid format options can be found here...
And if you need to load with a specific locale, see this...
My code works, but it throws the NaN 'not a number' before updating the field correctly. Im just being nit picky for efficiency as the 2nd field is going to be a hidden administration field as this is to fix a bug where a CRM is subtracting minus one day for some unknown reason when syncing with gravity forms to agilecrm, so I need to push the +1 date instead.
Here's my code. As I said, it works, but I wonder if there's a cleaner pure jQuery method without crossing back and forth between javascript. Although other solutions with javascript could be useful. I know I could possibly put some kind of if not (!datepicker) logic somewhere, but need the syntax and best practice do it.
Reason for asking: The answer in multiple places was to just use:
newdate.setDate(newdate.getDate() + 1);
However this answer was not working until I found the additional concatenating setup to put together the final mm/dd/yyyy format to resolve, also I didn't see a good jQuery on document.ready listening for a blur event solution to update another dated field in any other article so figure this would be worth the time to have discussed.
Also here's a link to the page with the form and the fixdate field that's populated.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#input_6_4").blur(function(){
var tt = $("#input_6_4").val();
//alert(tt);
var date = new Date(tt);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() + 1);
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var y = newdate.getFullYear();
var FixDate = mm + '/' + dd + '/' + y;
// alert(FixDate);
$("#input_6_14").attr('value',FixDate);
});
});
</script>
Megalayer: Complete End to End Managed Website Solutions
Below is the optimized code for your code.
$(document).ready(function(){
$("#input_6_4").blur(function(){
var newdate = new Date(this.value);
newdate.setDate(newdate.getDate() + 1);
$("#input_6_14").val(newdate.toLocaleDateString());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Old Date: <input id="input_6_4" / value="5/20/2015">
<br/>
<br/>
New Date: <input id="input_6_14" />
I have some basic form/input html that works (including validation) if explicitly written as follows:
<form name="forms.create" novalidate>
<div class="si-container">
<div class="si-input-container">
<input class="si-input" name="someNum" placeholder="Enter a number" ng-model="formdata.number" type="number" min="40"/>
</div>
<div class="si-error">
<div ng-show="forms.create.someNum.$error.min">Error! Value must be > 40.</div>
</div>
</div>
</form>
Now what I want to do is create a directive that allows me to write the html below, but result in the html above:
<form name="forms.create" novalidate>
<div special-input name="someNum" placeholder="Enter a number" type="number" ng-model="formdata.number">
<div error-type="min" error-value="40">Error! Value must be > 40.</div>
</div>
</form>
My attempt at the special-input directive (simplified) is as follows:
.directive('specialInput', [function(){
return {
compile: function(elem, attrs){
var input = angular.element('<input class="si-input"/>');
input.attr('placeholder', attrs.placeholder);
input.attr('type', attrs.type);
input.attr('name', attrs.name);
input.attr('ng-model', attrs.ngModel);
var errorCont = angular.element('<div class="si-error"></div>');
var errors = elem.children();
angular.forEach(errors, function(error){
var err = angular.element(error);
var type = err.attr('error-type');
var value = err.attr('error-value');
input.attr(type, value);
var formName = elem.parent().attr('name');
errorCont.append('<div ng-show="' + formName + '.' + attrs.name + '.$error.' + type + '">' + err.html() + '</div>');
});
var cont = angular.element('<div class="si-container"></div>');
cont.append('<div class="si-floating-label">' + attrs.placeholder + '</div>');
cont.append('<div class="si-input-container">' + input[0].outerHTML + '</div>');
cont.append('<div class="si-underline"></div>');
cont.append(errorCont);
elem.replaceWith(cont[0].outerHTML);
}
};
}]);
Now the resultant html using the directive above looks about right. If I put {{formdata.number}} below the form the value changes as expected. The problem is that now the validation never shows.
For example, if I put the value 5 in the input and inspect the form object, I get weird results. $dirty is set to true for form, but not for form.someNum. If I put 55 in the input, $dirty is still set to false for form.someNum, but $modelValue and $viewValue both show 55.
Any ideas or suggestions? Here is a fiddle to help with any testing.
If you put 50 in the input box you should see the value below, but put 5 and the error does not appear
UPDATE
I have managed to get it working by moving the dom changes into the link function instead of the compile function, and adding this:
elem.replaceWith(cont);
$compile(cont)(scope);
I am still puzzled though, as to why this works, while altering the dom in the exact same way in the compile function doesn't work. Is anyone able to explain this?
It's because the original ng-model is still get compiled even the original DOM has already been replaced by the new one in your compile function.
The ng-model directive will register itself to a parent form in its postLink function. Due to the fact that the postLink function will be executed in reverse (child's before parent's), the new ng-model will do the registration first, thus it will be overridden by the one from the original ng-model eventually.
To avoid this problem, you could change the original ng-model to another name such as my-model, then rename it to ng-model later in your compile function.
Example jsfiddle: http://jsfiddle.net/Wr3cJ/1/
Hope this helps.
I am able to do this using an ID prefix as the selector, but I need to be able to do it with classes instead. It's an each function for opening up different modal windows on the same page. I need to avoid using ID names because I have some modal windows that will have multiple links on the same page, and when using IDs, only the first link will work.
So here's the function as it works with IDs:
$('div[id^=ssfamodal-help-]').each(function() {
var sfx = this.id,
mdl = $(this),
lnk = $('.link-' + sfx),
cls = $('.ssfamodal-close'),
con = $('.ssfamodal-content');
lnk.click(function(){
mdl.show();
});
cls.click(function(){
mdl.hide();
});
mdl.click(function() {
mdl.hide();
});
con.click(function() {
return false;
});
});
and I'm trying to change it to classes instead, like:
$('div[class^=ssfamodal-help-]').each(function() {
var sfx = this.attr('class'),
etc.
But I cannot get it to work without using IDs. Is it possible?
EDIT Fixed error with semi-colon at end of Vars, and updated Fiddle with the fix. Still not working though.
Here's a Fiddle
** UPDATE **
To be clearer, I need to be able to refer to the same modal more than once on the same page. E.g.:
MODAL 1
MODAL 2
MODAL 3
MODAL 4
LINK TO MODAL 1
LINK TO MODAL 2
LINK TO MODAL 3
LINK TO MODAL 4
OTHER STUFF
LINK TO MODAL 1
LINK TO MODAL 4
LINK TO MODAL 3
OTHER STUFF
LINK TO MODAL 2
ETC.
When using classes get rid of the ID habit :
className1, className2, className3 ... etc
simply use
className
HTML:
<div class="ssfamodal-help-base ssfamodal-backdrop">
<div id="help-content" class="ssfamodal-content">
<span class="ssfamodal-close">[x]</span>
Howdy
</div>
</div>
<div class="ssfamodal-help-base ssfamodal-backdrop">
<div id="help-content" class="ssfamodal-content">
<span class="ssfamodal-close">[x]</span>
Howdy Ho
</div>
</div>
<span class="link-ssfamodal-help-base">One</span>
<span class="link-ssfamodal-help-base">Two</span>
LIVE DEMO
var $btn = $('.link-ssfamodal-help-base'),
$mod = $('.ssfamodal-help-base'),
$X = $('.ssfamodal-close');
$btn.click(function(i) {
var i = $('[class^="link-"]').index(this); // all .link-** but get the index of this!
// Why that?! cause if you only do:
// var i = $('.link-ssfamodal-help-base').index();
// you'll get // 2
// cause that element, inside a parent is the 3rd element
// but retargeting it's index using $('className').index(this);
// you'll get the correct index for that class name!
$('.ssfamodal-help-base').eq(i).show() // Show the referenced element by .eq()
.siblings('.ssfamodal-help-base').hide(); // hide all other elements (with same class)
});
$X.click(function(){
$(this).closest('.ssfamodal-help-base').hide();
});
From the DOCS:
http://api.jquery.com/eq/
http://api.jquery.com/index/
http://api.jquery.com/closest/
Here I created a quite basic example on how you can create a jQuery plugin of your own to handle modals: http://jsbin.com/ulUPIje/1/edit
feel free to use and abuse.
The problem is that class attributes can consist of many classes, rather than IDs which only have one value. One solution, which isn't exactly clean, but seems to work is the following.
$('div').filter(function () {
var classes = $(this).attr('class').split(/\s+/);
for (var i = 0; i < classes.length; i++)
if (classes[i].indexOf('ssfamodal-help-') == 0)
return true;
return false;
}).each(function() {
// code
});
jsFiddle
Or, equivalently
$('div').filter(function () {
return $(this).attr('class').split(/\s+/).some(function (e) {
return e.indexOf('ssfamodal-help-') == 0;
});
}).each(function() {
// code
});
jsFiddle
If there is one-to-one relationship between the modal helps and the modal links which it appears there is...can simplfy needing to match class values by using indexing.
For this reason you don't need unique class names, rather they just overcomplicate things. Following assumes classes stay unique however
var $helps=$('div[id^=ssfamodal-help-]');
var $help_links=$('div[id^=link-ssfamodal-help-]');
$help_links.click(function(){
var linkIndex= $help_links.index(this);
$helps.hide().eq( linkIndex ).show();
});
/* not sure if this is what's wanted, but appeared original code had it*/
$helps.click(function(){
$(this).hide()
})
/* close buttons using traverse*/
$('.ssfamodal-close').click(function(){
$(this).closest('div[id^=ssfamodal-help-]' ).hide();
});
Also believe that this code is a little more readable than original apporach
DEMO
Can you try this,
$('div[class^=ssfamodal-help-]').each(function() {
var sfx = $(this).attr('class');
console.log(sfx);
/*console log:
ssfamodal-help-base ssfamodal-backdrop
ssfamodal-help-base2 ssfamodal-backdrop
*/
});
Demo: http://jsfiddle.net/xAssR/51/
why don't you write like
$('div.classname').each(function() {
// you can write your desired code here
var sfx = this.attr('class');
var aa= this.attr('id');
});
or
$('.classname').each(function() {
// you can write your desired code here
var sfx = this.attr('class');
var aa= this.attr('id');
});
where classname is the name of the class used for the div in html
Thanks.