Helper functions in jsviews - javascript

I am going through the following examples in JsViews site for buttons http://www.jsviews.com/#link-button. When I modify the code to take an input and display the same in the alertbox on clicking the button, the helper function gets executed onload. Also, instead of on click of the button, the function gets executed when the input value changes. I am guessing since the model value is changed in the view, the function gets called with the updated model value but why is it not working on click of the button. I am quite new to jsviews and not able to understand what is happening. Can anyone tell me what is wrong with my approach. Below is the updated code.
<div id="topLinked">
<input type="text" data-link="test"/>
<button data-link="{on ~doSomething(test)}">Do something</button>
<input type="button" data-link="{on ~doSomething(test)}" value="Do something" />
</div>
var person = {};
var helpers = {
doSomething: function(val) {
alert(val);
}
}
$.link(true, "#topLinked", person, helpers); // Data-link top-level content

You made a mistake this: data-link="{on ~doSomething(test)}".
Arguments are passed through the one or more spaces like this: data-link="{on ~doSomething test test2 ...}".
I changed the example like this:
html
<div id="result"></div>
<script id="tmpl" type="text/x-jsrender">
<input type="text" data-link="test" value="Do something" />
{^{on ~doSomething test}}Do something{{/on}}
<button data-link="{on ~doSomething test}">Do something</button>
<input type="button" data-link="{on ~doSomething test}" value="Do something" />
</script>
js
var person = {
test : "start value"
};
var helpers = {
doSomething : function (val) {
alert(val);
return false;
}
}
var tmpl = $.templates("#tmpl");
tmpl.link("#result", person, helpers);
example on jsfiddle

Related

knockout.js click binding not calling viewmodel function

I want a function declared on my viewmodel to trigger when clicking a button. However the functions are not called when the button is clicked.
I have tried renaming the methods, callling them with parameters, but nothing triggers them. I know that knockout.js i loaded on the page since the showSmsPanel observable is working as expected.
MyJavascript.js
function AdminTilmeldingerViewModel() {
var self = this;
self.showSmsPanel = ko.observable(false); // hidden initially
self.cancelSend = function () {
console.log('cancelSend');
this.showSmsPanel(false);
}
self.sendSms = function () {
console.log('sendSms');
};
}
var vm = new AdminTilmeldingerViewModel();
ko.applyBindings(vm);
MyHtml.aspx
<div id="smsPanel" data-bind = "visible: showSmsPanel" class="row">
<input type=button class="btn btn-primary" data-bind="click: sendSms" id="btnSendSms" value="Send sms">
<input type=button class="btn btn-default" data-bind="click: cancelSend" value="Annuller">
</div>
I would expect the function to be called on clicking the buttons, but I dont see output logged to the console.

Submit button to call function

My submit button is not doing anything when I click on it. I believe my event listener is correctly established. Any ideas on why it wont do anything?
JS FILE
document.getElementById("submitbutton").addEventListener("click", saveNames());
function saveNames() {
var player1name = document.getElementById("player1").value;
var player2name = document.getElementById("player2").value;
var player3name = document.getElementById("player3").value;
var player4name = document.getElementById("player4").value;
var player5name = document.getElementById("player5").value;
savePlayer(player1name);
savePlayer(player2name);
savePlayer(player3name);
savePlayer(player4name);
savePlayer(player5name);
gameScreen(2);
}
HTML FILE:
<input type="text"name="p1"><br>
<input type="text"name="p2"><br>
<input type="text"name="p3"><br>
<input type="text"name="p4"><br>
<input type="text"name="p5"><br>
<input id="submitbutton"type="submit" value="Submit">;
You're not binding to the function, you're binding to the result of the function. Just pass the function itself, don't invoke it. (Get rid of the parentheses):
document.getElementById("submitbutton").addEventListener("click", saveNames);
Why?
Because when that one line of code above executes, if you have the errant parentheses then the first thing it does is execute the saveNames function in order to get the result to pass to the addEventListener function. And that result is undefined because saveNames doesn't return anything.
Presumably also that first invocation of the saveNames function doesn't visibly do anything (though it does execute) because the inputs have no values in them yet at that time.
Consider as a contrived example:
doSomething( doSomethingElse() )
This would execute doSomethingElse() and then pass its returned result to doSomething(). The same is true when adding event listeners, you're just calling a function like any other function.
add the listener like this -
document.getElementById("submitbutton").addEventListener("click", saveNames);
note , I have removed () at end.
Use Id instead of name. you are reading these elements with id then you need to specify that.
Give a spaces before name or type.
//Remove the parenthese after "saveNames" - leaving them will call saveNames when it is encountered
document.getElementById("submitbutton").addEventListener("click", saveNames);
function saveNames() {
//Use an array as it's neater
var players = [
document.getElementById("player1").value,
document.getElementById("player2").value,
document.getElementById("player3").value,
document.getElementById("player4").value,
document.getElementById("player5").value
]
//loop and save
players.forEach(function(name) {
if (name) {
savePlayer(name);
}
});
//gameScreen(2);
}
function savePlayer(name) {
console.log(`${name} saved.`);
}
<input id="player1" type="text" name="p1"><br>
<input id="player2" type="text" name="p2"><br>
<input id="player3" type="text" name="p3"><br>
<input id="player4" type="text" name="p4"><br>
<input id="player5" type="text" name="p5"><br>
<input id="submitbutton" type="button" value="Submit">

alerting the value of an input type number

Here is the code that I am having problems with. Below it I'll add an explanation:
$(function() {
var $input = $("#input");
var input = $input.val();
var $go = $("#go");
$go.click(function() {
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
The code above is a dummie example to represent my actual question, no more background is needed.
So I have one input type="number" id="input" in which you input a number, and a button type="button" id="go".
In my jQuery, I first declare $input which holds the element #input, then input which holds the value of the element #input, and finally $go which holds the element #go.
Below that I have a function, that says that when I click on #go, I should be able to alert(input).
Now, this code does not do that. In my head this makes perfect sense, but apparently it doesn't work.
That is because you are declaring input outside the click function, which means the value (simply an empty string) is set at runtime and will not be updated. You should define input within your click event handler:
$(function() {
var $input = $("#input");
var $go = $("#go");
$go.click(function() {
var input = $input.val();
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
First of all, StackOverflow seems to block alerts origination from the code snippet, it will be much easier to output them to the console instead so you can keep track of things.
Your code can be simplified way down without the need for many variables.
But your main problem was the fact that the input value was not getting reset when the click event happened but was getting picked up on page load, meaning it would be stuck at ''.
$(function() {
$("#go").click(function() {
var input = $("#input").val();
console.log(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>

JS function not displaying anything

I have made a function and captured the value of a textbox. On a button click, it should alert the value.
The code is:
function substitute (argument) {
var myVal=document.getElementById('myTextBox').value();
alert(myVal);
if (myVal.length==0) {
alert('Empty Textbox');
};
}
It is then executed using this:
<input type="button" name="Button" value="Click Me" onclick="substitute();">
But nothing happens. Please tell me where am I doing it wrong.
You have a few errors:
.value() is not a function: use .value
You don't need that semicolon at the end of the if statement
Your text box might not have the id that you're referring to: make sure that you have id="myTextBox" in the opening tag
While it won't cause any errors, your function definition lists a parameter, but you do not pass one when you call it.
Always check your browser console for errors if nothing is happening. Always.
function substitute () { // Parameter "argument" is not necessary
var myVal=document.getElementById('myTextBox').value; //.value, not .value()
alert(myVal);
if (myVal.length==0) {
alert('Empty Textbox');
}; // You don't need this semicolon
} // You were missing this curly brace
Demo
value is not a function, it's a property, therefore:
var myVal=document.getElementById('myTextBox').value;
As you're brand new to JS, I'll give you a piece of advice: If you want to manipulate the DOM, use jQuery.
In Your code, you are not passing any parameter to function subsititute(), But # function definition you wrote substitute(argument). Thats a big issue, and also you put there is a semi-column after if condition inside the function. No need of it
Try This..
<input type="text" id="myText" value="Hello" />
<input type="button" name="Button" value="Click Me" onclick="substitute();" />
In script part,
function subsitute()
{
var myVal=$('#myText').val();
alert(myVal);
if (myVal=='')
{
alert('Empty Textbox');
}
}
http://jsbin.com/tewudopi/1/edit
Add an ID to the button. When referencing the button, it is not ".value()", it is simply ".value".
As a side note, you should use === instead of == to compare.
function substitute() {
var myVal=document.getElementById('myTextBox');
alert(myVal.value);
if (myVal.value.length===0) {
alert('Empty Textbox');
}
}
Maybe something like the following.
<script type="text/javascript">
function substitute() {
var myVal=document.getElementById('myTextBox').value;
if (myVal.length>0) {
alert(myVal);
}
if (myVal.length==0) {
alert('Empty Textbox');
}
}
</script>
<input type="button" name="Button" value="Click Me" onclick="substitute();">
<textarea name="myTextBox" id="myTextBox"></textarea>
Fiddle demo

Model update is not propagated dynamically

I want to sum up 2 values and display the result in the 3rd input:
HTML
<div ng-app="myApp">
<div ng-controller="MainCtrl as mainCtrl">
Main {{mainCtrl.foo}} <br/>
<input type="text" ng-model="mainCtrl.foo"/>
<input type="text" ng-model="mainCtrl.foo2"/>
<input type="text" ng-model="mainCtrl.foo3"/>
<br/>
</div>
</div>
JS
var myApp = angular.module('myApp', []);
var my = {};
my.MainCtrl = function() {
this.foo = '1';
this.foo2 = '2'
this.foo3 = this.sumUp();
}
my.MainCtrl.prototype.sumUp = function() {
return this.foo + this.foo2;
}
// register all controllers
myApp.controller('MainCtrl', my.MainCtrl);
My problem is that the 3rd input is set only when the document is loaded but it is not dynamically changing while typing values in first two inputs.
Fiddle:
http://jsfiddle.net/K64wb/
Use parameter ng-change for input-fields 1 and 2.
Solution for U ;) ng-change="mainCtrl.foo3=mainCtrl.sumUp()"
Example:
<div ng-controller="MainCtrl as mainCtrl">
Main {{mainCtrl.foo}} <br/>
<input type="text" ng-change="mainCtrl.foo3=mainCtrl.sumUp()" ng-model="mainCtrl.foo"/>
<input type="text" ng-change="mainCtrl.foo3=mainCtrl.sumUp()" ng-model="mainCtrl.foo2"/>
<input type="text" ng-model="mainCtrl.foo3"/>
<br/>
</div>
When your view loads, it only fires the controller function once. So it assigns foo and foo2, and then computes foo3, and then it's done. this.sumUp is never called again.
You can add ng-change="mainCtrl.foo3=mainCtrl.sumUp()" to the input boxes like Mularski suggests. This causes the sumUp function to run and be assigned to foo3 every time the input value changes. I think that looks kind of messy, though. And if you decided to add more input boxes to add up, you have to remember to put ng-change on all of them.
Another way to do it is to assign the sumUp function itself to foo3 like this
this.foo3 = this.sumUp;
instead of assigning the result of sumUp like you are doing (this.foo3 = this.sumUp();). Then in your view, assign foo3() to the ng-value of the textbox:
<input type="text" ng-value="mainCtrl.foo3()"/>
(you can't assign it to ng-model because the function isn't writeable).
Now you're telling the textbox to always show the result of that function, and it will fire whenever any of its dependencies change (i.e. foo and foo2).
Here's a Fiddle.

Categories

Resources