I have this function:
<script type="text/javascript">
var car = document.getElementById("Carros").value;
window.onload = ChangeValue(car);
function ChangeValue(str)
{
....
}
See that ChangeValue(str) receives a parameter, how may I make it start in the pageLoad?
using javascript ! The parameter I pass is a <select id="" onChange="ChangeValue(this.value)">
window.onload = function () {
var car = document.getElementById("Carros").value;
ChangeValue(car);
}
Related
In the original script, when there is no value in the text bar and I click on the button called Radar 2, the page is automatically refreshed, as I understand it, as it generates an error in the function, the page refreshes because of that.
To prevent this error and this forced update, I tried using try{} catch{}, so if there is an error when trying to parse the first function, open a blank iframe.
But the page keeps updating when I click the Radar 2 button.
I would like to know what I'm doing wrong and what the correct script would look like for my needs.
The original script works as follows:
<form action="" method="post" id="url-setter2">
<button type="submit" name="submit">Radar 2</button>
<input type="text" name="url2" id="url2" style="width: 282px;" />
<iframe id="the-frame2" width="347" height="282" src=""></iframe>
<script type="text/javascript">
(function () {
"use strict";
var url_setter = document.getElementById('url-setter2'), url = document.getElementById('url2'), the_iframe = document.getElementById('the-frame2');
url_setter.onsubmit = function (event) {
let link = document.getElementById("url2").value;
let value2 = link.split("OB_EV")[1];
value2 = value2.split("/")[0];
event.preventDefault();
the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + value2;
};
}());
</script>
My Script Error Test:
<script type="text/javascript">
(function () {
"use strict";
var url_setter = document.getElementById('url-setter2'), url = document.getElementById('url2'), the_iframe = document.getElementById('the-frame2');
url_setter.onsubmit = try {
function (event) {
let link = document.getElementById("url2").value;
let value2 = link.split("OB_EV")[1];
value2 = value2.split("/")[0];
event.preventDefault();
the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + value2;
}
}
catch (e) {
function (event) {
event.preventDefault();
the_iframe.src ="";
}
};
}());
</script>
Using type="submit" will try to send the form data to the server for processing which is why the page refreshes.
Instead try using <button onclick="myFunction()">Radar 2</button> where
myFunction() is a function with your javascript code in it
I have made a small application that increments a counter when a picture of a cat is clicked. When I set the function with default parameters, it works. However, when I pass it a string to substitute in the function, it does not. What is the difference between these two scripts?
The first script, which does not pass a string to the catClick function:
'use strict';
function CatCount (pic_url, cat_name) {
this.pic_url = pic_url;
this.click_count = 0;
this.cat_name = cat_name;
return false;
}
var cat_name;
var pic_url;
var click_count;
function catClick() {
var cat_click_p = document.getElementById("number_clicked");
var number = cat_click_p.innerHTML;
number = parseInt(number) + 1;
cat_click_p.innerHTML = number;
}
var catGrid = document.getElementById('cat_grid');
catGrid.addEventListener('click', catClick, false);
and the second version of the script, which does pass a string to the catClick function:
'use strict';
function CatCount (pic_url, cat_name) {
this.pic_url = pic_url;
this.click_count = 0;
this.cat_name = cat_name;
return false;
}
var cat_name;
var pic_url;
var click_count;
function catClick(element_id_to_be_replaced) {
var cat_click_p = document.getElementById(element_id_to_be_replaced);
var number = cat_click_p.innerHTML;
number = parseInt(number) + 1;
cat_click_p.innerHTML = number;
}
var catGrid = document.getElementById('cat_grid');
catGrid.addEventListener('click', catClick('number_clicked'), false);
The second version of the script just increments the cat counter once.
Additionally, here is the index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src='js/app.js'></script>
<title>Cat App</title>
</head>
<body>
<div>
This app keeps track of how many times you click on a cat!
<div class='cat' id='cat_grid'>
<img src='http://thepetproductguru.com/wp-content/uploads/2012/05/CAT-HEADPHONES.jpeg'>
</div>
<div>
This cat has been clicked
<p id='number_clicked'>0</p>
times.
</div>
</body>
</html>
The problem lies in the following line:
catGrid.addEventListener('click', catClick('number_clicked'), false);
In that line you are executing catClick('number_clicked') and returning the result of that expression as the 2nd parameter to the addEventListener function.
Two possible solutions are:
//1: Using an anonymous function:
catGrid.addEventListener('click', function() {
catClick('number_clicked')
}, false);
//2: Using bind:
catGrid.addEventListener('click', catClick.bind(this,'number_clicked'), false);
I am new to web development.
Today I learn about classes(function) in javascript. I got an error how to call dynamically added method.
My Code :
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function MyMethod(name, fn) {
var str = "MyFunction1.prototype." + name + "= fn;";
eval(str);
}
function MyFunction1() {
MyMethod("start", function () { return "hi"; });
var abc = this.start(); //gives error
}
</script>
</head>
<body>
<form id="form1" runat="server" >
<div>
<input type="button" value="Click" onclick="MyFunction1()"/>
</div>
</form>
Here when I click the input button then not able to call the dynamically added function
How can i call the start() function that i added here.
Please Help me.
Thanks in Advance.
this in MyFunction1 referes to the global object in that case(for browsers it is window) , because you call MyFunction1 as function and you don't create an object by using new MyFunction1().
Another thing to be noted. You should not use eval when it is possible to do it without eval.
You can do the same thing using:
function MyMethod(name, fn) {
MyFunction1.prototype[name] = fn;
}
Using eval prevents you from using optimization tools or tools to validate your code. At least most of these tools don't take eval into account or even give a warning about that you are using it.
Try adding "new" before your onclick call to MyFunction1, creating an instance of it.
It reseolved I did
Hi , It resolved .Thanks for the gret help i did :
function fnOnload() {
MyMethod("start", function () { return "hi"; });
}
function MyMethod(name, fn) {
var str = "MyFunction1.prototype." + name + "= fn;";
eval(str);
}
function MyFunction1() {
}
function MyFunction2()
{
var aa = new MyFunction1();
var answee = aa.start();
}
and in click of button i callled function MyFunction2()
without changing your code you can do as follow , but I say it would be helpful if you read about invocations types and about this variable.
function MyMethod(name, fn) {
MyFunction1.prototype[name]= fn;
return MyFunction1.prototype;
}
function MyFunction1() {
var myPrototype= MyMethod("start", function () { return "hi"; });
var returnValue = myPrototype.start();
console.log(returnValue);
}
I have a SPA using knockout JS for data binding and sammy for routing. I have a deck of cards that I am trying to have a dynamic routing to. My problem is that it doesn't work when I try to set a knockout observable from the routing function in sammy.
My HTML, where I try to bind the name of the deck, looks like this:
<!-- Create Deck -->
<div id="createDeck" class="page" style="display:none;">
<input type="text" class="form-control" placeholder="Untitled Deck..." data-bind="value: $root.deck.name" />
</div>
<script type="text/javascript" src="lib/jquery-1.9.1.js"></script>
<script type="text/javascript" src="lib/knockout-2.3.0.js"></script>
<script type="text/javascript" src="lib/bootstrap.min.js"></script>
<script type="text/javascript" src="lib/sammy.js"></script>
<script type="text/javascript" src="js/Models/Deck.js"></script>
<script type="text/javascript" src="js/Models/Card.js"></script>
<script type="text/javascript" src="js/ViewModels/DeckViewModel.js"></script>
<script type="text/javascript" src="js/ViewModels/CardViewModel.js"></script>
<script type="text/javascript" src="js/routing.js"></script>
The Deck.js and DeckViewModel.js looks like below
function Deck(deckid, name, cards) {
var self = this;
self.id = deckid;
self.name = name;
self.cards = cards;
}
function DeckViewModel(deck, cards) {
var self = this;
self.deck = ko.observable(deck);
self.cards = ko.observableArray(cards);
self.goToCard = function (card) { location.hash = card.deckid + '/' + card.id };
}
// Bind
var element = $('#createDeck')[0];
var deckView = new DeckViewModel(null, null);
ko.applyBindings(deckView, element);
Finally, in my routing I try to create a new Deck, like this:
// Client-side routes
(function ($) {
var app = $.sammy('#content', function () {
this.get('#deck/:id', function (context) {
showPage("createDeck", ": Create Deck");
console.log(this.params.id);
deckView.deck = new Deck(1, "test", null);
console.log(deckView.deck);
});
});
$(function () {
app.run('#/');
});
})(jQuery);
function showPage(pageID, subHeader) {
// Hide all pages
$(".page").hide();
// Show the given page
$("#" + pageID).show();
// change the sub header
$("#subHeader").text(subHeader);
}
As you can see, I'm trying to create a test deck with the name 'test', but the binding <input type="text" class="form-control" placeholder="Untitled Deck..." data-bind="value: $root.deck.name" /> seems to bind the letter 'c'.
I'm at a loss, please help.
I tried to make a jsfiddle to demonstrate my problem
In your code the value assignment is not correct unless you are using Knockout-es5 plugin. here is the correct code
var app = $.sammy('#content', function () {
this.get('#deck/:id', function (context) {
showPage("createDeck", ": Create Deck");
console.log(this.params.id);
deckView.deck(new Deck(1, "test", null));
console.log(deckView.deck());
});
});
The way I've done this before is to define my Sammy() routes within the ViewModel. Shorter example for brevity:
(function($) {
function ViewModel() {
var self = this;
self.deckId = ko.observable(null);
Sammy(function() {
this.get('#/deck/:deckId', function(context) {
self.deckId(this.params.deckId);
});
});
}
$(function() {
ko.applyBindings(new ViewModel());
});
})(jQuery);
That way you can access your observables, etc, via self.
A sample bit of code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<div id="myinfo">info</div>
<input id="clickme" type="button" value="click here to display info"/>
<script type="text/javascript">
function Fighter() {
this.name = "Kenny"; // fighters name
this.hp = 10; // fighters hp
this.getHP = function() {
return this.hp;
}
this.getName = function() {
return this.name;
}
this.initUpdateButton = function(button_id) {
$(button_id).click(function() {
$("#myinfo").html("Name: "+this.getName()+"<br/>HP:"+this.getHP());
// this.getName is undefined
});
}
};
var me = new Fighter();
alert("Name: "+me.getName()+"<br/>HP:"+me.getHP()); // works properly
me.initUpdateButton("#clickme"); // bind it to some ID
</script>
Simply put, given a JavaScript class with JQuery mixed in, I understand that on the callback for JQuery functions (i.e. $.click()), that this is referring to the object that was clicked and Not the Class or root function(). so this.getName() and this.getHP() don't work.
But what is the best way to get around this problem?
I saw some similar posts but they weren't of use to me so sorry if this is a repost and thanks in advance.
this.initUpdateButton = function(button_id) {
var self = this;
$(button_id).click(function() {
$("#myinfo").html("Name: "+self.getName()+"<br/>HP:"+self.getHP());
});
}