Passing element ID as a function parameter - javascript

I am trying to pass element ID as one of the function's parameters:
sap.ui.getCore().byId("idView1").getController().addField("selectedFieldsContainer", oItem);
The definition of the addField function is as follows:
addField: function(sId, oItem){
var oSelectedFieldsContainer = sap.ui.getCore().byId(sId);
oSelectedFieldsContainer.addItem(oItem);
}
When I run the code, I get error:
Uncaught TypeError: Cannot read property 'addItem' of undefined
But if I try to explicitly define the id:
sap.ui.getCore().byId("idView1").getController().addField(oItem);
while the function's definition is:
addField: function(oItem){
var oSelectedFieldsContainer = sap.ui.getCore().byId("selectedFieldsContainer");
oSelectedFieldsContainer.addItem(oItem);
}
the code works.
I don't understand why the first example doesn't work.
What am I missing?
Thank you.
UPDATE
HERE is JSBIN. I want to update control's type. I try to pass this control's id as a parameter, but sap.ui.getCore().byId() can't find it (see console message).

You should know that calling
sap.ui.getCore().byId("control")
does not return a String. From the variable name sId I can guess that you were expecting to receive a String. Instead it returns the control with the given id. Then because of this your changeType() function does not work. Either you pass a reference to the found control to your changeType() function or you pass the string sap.ui.getCore().byId(sId). The jsbin passes the found control instead of the id. Passing the id string would be easy as well...
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
<title>Example</title>
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.m,sap.ui.layout"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-bindingSyntax="complex"
data-sap-ui-compatVersion="edge"
data-sap-ui-preload="sync"></script>
<script type="text/javascript">
function changeType(oControl, sType){
oControl.setType(sType);
}
var oButton = new sap.m.Button({
text: "Update Control Type",
press: function(){
var oControl = sap.ui.getCore().byId("control");
var sType = "Password";
changeType(oControl, sType);
}
});
var oItem = new sap.m.Input("control");
new sap.m.HBox({
items: [oButton, oItem]
}).placeAt("content");
</script>
</head>
<body id="content" class="sapUiBody">
</body>
</html>

Sorry, everyone.
The problem was hiding elsewhere.
Please see the answer to this question.

Here is the working edit Fixed.
The issue is you are passing the object reference in sId field whereas getCore() expects a string. sId.sId get the id of the control you are passing and this appears to work.

Related

Passing a variable in JavaScript to open.window

I have variable which is i think global ,,so all my child functions must be able to get that variable,But i am getting a reference error,Variable not declared
Here is below code.Please help if i am doing any wrong thing.Thanku
<!DOCTYPE html>
<html>
<head>
<script>
var Test1Object = 'Testing'; // This is my variable
</script>
<script src = 'ch.js'>
</script>
</head>
<body>
<button onclick="openwindow()">Create window</button>
</body>
</html>
My Ch.js
(function(){
alert(Test1Object) // Here i am getting this object
this.openwindow = function() {
w =window.open("untitled.html",'TheNewpop','height=315,width=625');
w.document.write(
"<body>"+
"<\/body>" +
"<script src = \"windowpo.js\"><\/script>" // THis is where i reference my windowpo.js
)
w.document.close();
w.focus();
}
})()
My windowpo.js
(function(){
alert(Test1Object) // Here there is not Test1Object (Reference error)
})();
My issue is that in my windowp.js how can i get my Test1Object Variable...
Easy doing by just acessing your refrence inside the window by using window.opener like in this runnable demo plnkr. Inside your window application you can access it via window.opener.Test1Object where window.opener holds a reference of the JavaScript instance where it was opened. In that way you can access all the stuff you configured in your main application:
Source: window.opener MDN reference
View
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="utf-8" />
<title>Custom Plunker</title>
<script type="text/javascript">
var Test1Object = 'Testing';
</script>
<script src="main.js"></script>
</head>
<body>
<a onclick="openwindow()">Open Window</a>
</body>
</html>
main.js
this.openwindow = function() {
w = window.open(location.href+"untitled.html",'TheNewpop','height=315,width=625');
w.document.close();
w.focus();
}
unitiled.html
Some Test
<script src="windowpo.js"></script>
windowpo.js
alert(window.opener.Test1Object);
As most other answers don't seem to even read the question properly, I'll add my 2 cents as an answer, too:
The main problem in your code, is that you have to JS execution contexts here: One for the original page (the HTML code you show) and one for the popup you open in Ch.js. In general both do not share any data, variables or whatever.
You have, however, a window object reference in your variable w after calling window.open(). You use this already to inject HTML code to the popup.
If you now want to have JS variables available in the popup JS context, you can either inject additional <script> tags into the popups HTML code and set the variables there (bad choice, imho) or use postMessage() to send data across. I give some sample code for the postMessage() variant below:
Ch.js
this.openwindow = function() {
w = window.open("untitled.html",'TheNewpop','height=315,width=625');
w.document.write(
"<body>"+
"<\/body>" +
"<script src = \"windowpo.js\"><\/script>" // THis is where i reference my windowpo.js
);
w.document.close();
w.focus();
// wait for pupup to be ready
window.addEventListener( 'message', function( e ){
// send the variable
if( e.data == 'inited' ) {
w.postMessage( Test1Object, '*' );
}
})
}
windowpo.js
// wait for messages from opener
window.addEventListener( 'message', function( e ) {
alert( e.data );
});
// tell the opener we are waiting
window.opener.postMessage( 'inited', '*' );
For some more information see the respective MDN article on Window.postMessage().
You need to declare the variable before you include in any file. Simply create a script tag above the included files define it there.
<script type='text/javascript' >
var Test1Object = 'Testing';
</script>
<script type='text/javascript' src='js/Ch.js'></script>
<script type='text/javascript' src='js/windowpo.js'></script>
this way you should be able to use withing all files

Displaying data from an array of objects inside document

Been trying to take specific data from an array of objects that for many reasons I cannot host on a server. The data is in stored as a variable in the document. This is what i've been trying so far to no success:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m#ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o#technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}]
var simpson = users.find("last_name" + "Simpson")
document.getElementById("return").innerHTML = function myfunction() {
simpson;
}
</script>
</head>
<body>
<div id="return"></div>
</body>
For now I've just been trying to extract some/any data from the 'users' array, but going forward i would like to have the user search for a word and the entire 'line'/'lines' of data related to the word/words in 'users' display as results. What methods should i use to achieve this?
You have some mistakes in your code. First of all, find function accept as argument a callback function.
var simpson = users.find(a=>a.last_name=="Simpson");
If you pass function to innerHTML, you must to invoke it, like this:
document.getElementById("return").innerHTML = (function myFunction(){
return JSON.stringify(simpson);
})();
and function must return a value in order to set the HTML content (inner HTML) of result element.
var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m#ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o#technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}]
var simpson = users.find(callback);
function callback(item){
return item.last_name=="Simpson";
}
document.getElementById("return").innerHTML = (function myFunction(){
return JSON.stringify(simpson);
})();
<body>
<div id="return"></div>
</body>
1. You need to pass the callback function in find method. The find method searches for an element in an array and returns the element if it is found. Otherwise undefined is returned. The Search Criteria is defined by a callback function. Something like
var simpson = users.find(currentValue => currentValue.last_name === "Simpson");
2. You might not require your innerHTML to be a function, instead it would be more appropriate that it points to meaningfull information like UserName Found.
document.getElementById("return").innerHTML = simpson.username;
Try the following code.
var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m#ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o#technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}]
var simpson = users.find(currentValue => currentValue.last_name === "Simpson");
document.getElementById("return").innerHTML = simpson.username;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
</script>
</head>
<body>
<div id="return"></div>
</body>

js function not changing value

I have the following code. The first time the function is called the iframe changes contents to newPage but the second time the function is called the page doesn't change.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Submit</title>
<script>
var url = 1;
function setURL(url){
var win1 = "http://localhost/Audio/src/submit1.html" ;
var win2 = "http://localhost/Audio/src/newPage.html";
if (url === 1){
document.getElementById('iframe').src=win2;
url=2;
}
else{
document.getElementById('iframe').src=win1;
url=1;
}
}
</script>
</head>
<body>
<iframe src="http://localhost/Audio/src/audio.html" style="width:0;height:0;border:0; border:none;"></iframe>
<iframe id="iframe" style="border:0; " src="http://localhost/Audio/src/submit1.html">
</iframe>
<input type="button" value="click me 71" onclick="setURL(url)">
</body>
</html>
You have two variables called url.
The one defined as a global and the one defined as the function argument.
Your function only changes the one defined as the function argument, which isn't preserved anywhere.
If you want to modify the global one: Don't define the argument in the function definition (and don't bother passing an argument to the function).
since you are passing the same name as parameter (url) you have to explicitly say which one do you want to change or change the parameter name (from url to u for instance)

How do you set a permanent value in jQuery

I want to set a permanent value to a div element with jQuery;
the full js file:
$(function () {
var $a;
var $b;
$('button').click(function () {
$a = $('#a').val();
$b = $('#b').val();
var $big = getBigger($b, $a);
var $small = getSmaller($b, $a);
$('#bigger').text($big);
$('#smaller').text($small);
});
});
//a simple function for getting a bigger element
function getBigger(a, b) {
return a ^ (a ^ b) & -(a < b);
}
//a simple function for getting a smaller element
function getSmaller(a, b) {
return (a < b) ? a : b;
}
the full html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style/style.css">
<title>Compare</title>
</head>
<body>
<form>
Enter a: <input type="number" id="a"><br/>
Enter b: <input type="number" id="b"><br/>
<button> Compare</button>
<div id="bigger"></div>
<div id="smaller"> </div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
The problem is that when I leave the scope the variable gets destroyed
PS. Now I realise that my mistake is that when a <button> is added in a form element, everytime the button is pressed, the data in the form gets reseted
When you run code within a function it creates a scope. Each variable you define using the var statement will be available only in that scope.
To create a variable for usage outside of the current scope, either declare a variable without putting var beforehand or directly write window.varname = value. Have another read on that topic.
Besides that, in your code $('#bigger').text($big); the var $big never even gets defined, so maybe that is the problem.
And setting an elements text works independent from scopes or variables.
Try this
To Access:
$("#a").data('value');
To Set
$("#a").data('value' , 'whatevervalue');
To Access Without JQuery:
document.getElementById("a").dataset.value;
To Set Without JQuery;
document.getElementById("a").dataset.value = "Some Value";
A Div cannot hold the Value attribute unless you use:
document.getElementById("a").setAttribute("value" , "val");
Then to Assign it to Inside your div:
$("#myDivElement").html($("#a").data('value'))

Issue with getElementById

I have written the following code to display an input with Javascript's alert( ... ) function.
My aim is to take a URL as input and open it in a new window. I concatenate it with 'http://' and then execute window.open().
However, I just get 'http://' in the URL name, even after concatenation, and not the complete URL. How can I fix this?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<body onload="onload();">
<input type="text" name="enter" value="" id="url_id">
<input type="button" value="Submit" onclick="func();">
</body>
<script type="text/javascript">
var url;
function onload() {
url = document.getElementById("url_id").value;
}
function func(){
var var1 = "http://";
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
</script>
</head>
</html>
You shouldn't be calling it in onload(), only after the user has entered the url into the input field. Of course its an empty string, because you assign url to the value of #url_id before the user has a chance to enter anything when you place it in onload().
function func(){
var var1 = "http://";
url = document.getElementById("url_id").value;
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
Others have given solutions, and you already have accepted one. But none of them have told you what is wrong with your code.
Fristly, you have a body element inside your head element. This is invalid markup. Please correct it:
<html>
<head>
<!-- this is a script -->
<script type="text/javascript">
// javascript code
</script>
</head>
<body>
<!-- this is an inline script -->
<script type="text/javascript">
// javascript code
</script>
</body>
</html>
Secondly, you need to have an idea about the execution order of JavaScript inside browser windows. Consider this example:
<html>
<body onload="alert('onload')">
<p>Lorem Ipsum</p>
<script type="text/javascript" >
alert('inline');
</script>
</body>
</html>
Which alert do you thing will get executed first? See the JSFiddle.
So as you can see, inline JavaScript will be executed first, and then the browser will call whatever code is in <body onload=.
Also, onload function is called immediately after the page is loaded. And user has not entered anything when the function is executed. That is why you get null for url.
function func()
var url = document.getElementById("url_id").value;
var fullUrl = "http://".concat(url);
alert(fullUrl);
// or window.open(fullUrl);
}
You're not concatenating with a String but with an Object. Specifically an HTMLInputElement object.
If you want the url from the text input, you need to concatenate with url.value.
if its not concatenating, use:
var res = val1+val2.value;

Categories

Resources