The getElementByID isnt showing the value - javascript

PLeaseHelp. it wont show the Value, even for form authentication, to get username & password values,I was trying the same methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=<device-width>,initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="result">Selected movie is </h1>
<select id="movie" onchange="showmovie()">
<option value="Spiderman">Spiderman</option>
<option value="Spiderman2">Spiderman2</option>
<option value="Spiderman3">Spiderman3</option>
</select>
</body>
</html>
<script>
var movie = document.getElementById("movie").value
function showmovie(){
alert("Changed")
document.getElementById("result").innerHTML="Movie chosen is"+movie
}
</script>

Try with this function showmovie
<script>
function showmovie() {
//Selected option
var selectedMovie = document.getElementById("movie").value;
document.getElementById("result").innerHTML = "Movie chosen is " + selectedMovie;
}
</script>

The issue here is because of the line var movie = document.getElementById("movie").value being executed just one time at the beginning (you could verify that adding console.log(movie); just after the movie variable declaration)
(movie stores then the value 'Spierdaman') and it never executes again with the calls for showmovie() function, so you could just move the movie declaration line above inside the function so it executes each time the action occurs and then having the good values.
Other details : To have a compliant code i suggest moving the script bloc to part just before and dont forget to add semicolons ';' at the end of each line ! + Better approach would be to use an eventListener as suggested by #T.J. Crowder in comments section above

Related

Nested Input Problems

why is "undefined" showing up on top of my text
function myname() {
document.write('Im john doe ');
}
function myage() {
myname();
document.write('Im 47 years old');
}
document.querySelector('.test').innerHTML=myage();
JSBin here's the full code
function myage(){
myname();
document.write('Im 47 years old')
}
document.querySelector('.test').innerHTML=myage()
In this when You are calling myage() it is not returning anything. So innerHtml for the Selected Target gets nothing.
This is the reason why it's showing Undefined.
When the browser processes a HTML-document and comes across a tag, it needs to execute before continuing building the DOM. As you are trying to access document.querySelector('.test') which is not available at that moment, it has given an undefined. Check out the below code where, the script gets executed with out undefined after the dom loads.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="test"></div>
</body>
<script>
function myname(){
document.write('Im john doe ')
}
function myage(){
myname();
document.write('Im 47 years old')
}
document.addEventListener("DOMContentLoaded", () => {
document.querySelector('.test').innerHTML=myage()
});
</script>
</html>

Why won't my modified current location request code (JS/jQuery) work? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm trying to figure out why the first code works whereas the second doesn't. I'm a tad green on jQuery and Javascript as a whole, but was under the impression that this "$('#location').html(...)" part populated the element with 'location' id. That way if I created a variable to which the results of the request are assigned, it'd do the same job if I had "$('#location').html(variable)". What gives?
Here are the two codes:
First Code(This works)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Current Position</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body >
<div>Location: <span id="location"></span></div>
<script>
$.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?')
.done (function(location) {
$('#location').html(location.city + ", " + location.state + " (" + location.country_name + ")");
});
</script>
</body>
</html>
Second Code(This one doesn't)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Current Position</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body >
<div>Location: <span id="location"></span></div>
<script>
var currentLocation = $.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?')
.done (function(location) {
location.city + ", " + location.state + " (" + location.country_name + ")";
});
$('#location').html(currentLocation);
</script>
</body>
</html>
$.getJson returns a kind of promise, not the value of the request itself. So assigning it's result to a variable won't give you the wanted results. This is the way most asynchronous stuff works. You won't ever be able to assign the result of an asynchronous call that way because the code hasn't successfully ran yet.
The first code it's the correct way to go. Think about it this way:
// Do some *asynchrounous* request
const promise = $.getJson(...arguments...)
// Create a handler funcion or "callback"
const handler = function(value) { console.log(value) }
// Tell the promise to call this function when it get's resolved
promise.done(handler);
Promises have some serious advantages like composability: multiple handlers can be attached.
$.getJson(...)
.done(doStuffA)
.done(doStuffB)
.catch(handleError)

Js: GetElementByID() doesn't return my element

This has been asked 100x before but after reading a lot of those posts I'm still not sure what I'm doing wrong. The script is only executed when you press the button (so the textbox should exist in the DOM by the time the code is executed), Visual Studio even lets me autocomplete the getElementByID argument to inputField. Yet somehow it doesn't get the element and 'null' is printed on my screen.
My code is:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<!-- input field + button, and an empty value field -->
<input type="text" id="inputField" value="" />
<input type="button" onclick="printType()" />
</body>
<script>
function printType() {
console.log(document.getElementById(inputField).value); //first try to get the value the regular way
console.log(
get_type(
document.getElementById(inputField)
)
); //also try get_type to see if it exists, we're expecting a string
}
//stole this function from a stackoverflow post
function get_type(thing) {
if (thing === null) return "[object Null]"; // special case
return Object.prototype.toString.call(thing);
}
</script>
</html>
You're missing quotes:
document.getElementById(inputField);
Should be:
document.getElementById('inputField');
Based on #Schlaus answer, I created a jsfiddle with correct answer.
function printType() {
console.log(document.getElementById('inputField').value); //first try to get the value the regular way
console.log(
get_type(
document.getElementById('inputField')
)
); //also try get_type to see if it exists, we're expecting a string
}

Clickstream Tracking in Veeva CRM

I am working with Veeva CRM, trying to use Click Stream Tracking. I have the code which I am using and trying to track the Presentation id, Product Key Message, track an Element Description and Answer.
Can anybody help with the code that I am using.
Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>CLM_CERT_HCPName</title>
<!-- Bootstrap -->
<link href="css/style.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<script src="js/veeva-library-3.0.js"></script>
<script>
function start(){
header_getAccountName();
}
function header_getAccountName(){ com.veeva.clm.getDataForCurrentObject("Account","Name",header_displayAccountName)}
function header_displayAccountName(result){
var AccountNameHTML = document.getElementById("hcpName");
AccountNameHTML.innerHTML += result.Account.Name;com.veeva.clm.getDataForCurrentObject("Presentation","Survey_vod__c",header_getSurveyID);
}
function mySaveObject(){
//This is the start of my JSON object
var myCallClickStream = {Call_vod__c, Key_Message_vod__c};
//i am using my JSON obj name with the field API name of the call clickstream object obj.apiName then set the value. obj.apiName= value;]
// Create the record using the com.veeva.clm.createRecord
com.veeva.clm.createRecord("Call_ClickStream_vod_c", myCallClickStream, printSavedResults)}
function printSavedResults(result){
alert(JSON.stingify(result));
}
</script>
</head>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
I have also some sample code to try out but not sure what I am doing wrong.
function mySaveObject(){
var myCallClickStream = {};
myCallClickStream.Text_Entered_vod__c = "i will put some text here";
com.veeva.clm.createRecord("Call_Clickstream_vod__c", myCallClickStream, printSavedResults)
}
function printSavedResults(result) {
alert(JSON.stringify(result));
}
Not sure if you still need help on this or not. But my team uses a simple method in every project to simplify the tracking process. The below was modified to fit some of your naming conventions/needs.
// clmDescription - string submitted as the description to be tracked
// clmAnswer - string submitted as the answer to be tracked`
// callback - call back function which will be used to return the information
function mySaveObject( clmDescription, clmAnswer, clmCallback ) {
var url = window.location.pathname,
filename = url.substring(url.lastIndexOf('/') + 1),
clmTrackingID = filename.replace(".html", "");
var myCallClickStream = {};
myCallClickStream.Track_Element_Id_vod__c = clmTrackingID;
myCallClickStream.Track_Element_Type_vod__c = clmDescription;
myCallClickStream.Selected_Items_vod__c = clmAnswer;
myCallClickStream.Track_Element_Description_vod__c = clmAnswer;
// var myJSONText = JSON.stringify( myCallClickStream );
com.veeva.clm.createRecord( Call_Clickstream_vod__c, myCallClickStream, clmCallback );
}
Simply call the method and pass in your parameters, including your callback method.
Hope this helps!

What can't I get this random quote generator to work?

I've been trying to make a "Random Quote Machine" that randomly selects a quote from an array of 5 quotes and inserts the text into a paragraph on a webpage. The Machine uses HTML and JavaScript(jQuery). I suspect my error is pretty simple given how simple the project is.
Here's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
</body>
</html>
Here's the JavaScript:
var quotes = ["Innocence is thought charming because it offers delightful possibilities for exploitation.",
"Every day begins with an act of courage and hope: getting out of bed.",
"Hatred observes with more care than love does.",
"To understand someone, find out how he spends his money.",
"The educated do not share a common body of information, but a common state of mind."
];
function getQuote() {
return Math.floor(Math.random() * quotes.length);
}
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
Because your scripts are included in the head element, the quoteGen button doesn't exist in the DOM at the time that you try to bind an event handler to it. You need to either include the scripts just before the end of your body tag, or wrap your code in a DOM-ready event handler to ensure that the DOM exists as you expect it to when your code runs.
So, you could either go with this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</body>
</html>
... or, use a DOM-ready handler, such as this:
$(function () {
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
Works just fine?
http://jsfiddle.net/tj3dvz1m/.
make sure to run your code in a
$( document ).ready(function() {
Your code here.
});
The handler is being set before the #quoteGen dom node exists.
You need to move the inclusion of quotes.js to the end of your file, right before the closing of /BODY.
Or register the handler to be installed once the document is ready:
$(document).ready(function(){
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
This code works fine. Credit to owner.
// Random Quotes
var Quotation=new Array()
Quotation[0] = "Time is of the essence! Comb your hair.";
Quotation[1] = "Sanity is a golden apple with no shoelaces.";
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon.";
Quotation[3] = "Honesty blurts where deception sneezes.";
Quotation[4] = "Pastry satisfies where art is unavailable.";
Quotation[5] = "Delete not, lest you, too, be deleted.";
Quotation[6] = "O! Youth! What a pain in the backside.";
Quotation[7] = "Wishes are like goldfish with propellors.";
Quotation[8] = "Love the river's \"beauty\", but live on a hill.";
Quotation[9] = "Invention is the mother of too many useless toys.";
var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation()
{document.write(Quotation[whichQuotation]);}
showQuotation();

Categories

Resources