How to set textbox input to a variable - javascript

I'm currently just getting into JavaScript with HTML. I have been using HTML and CSS for a while now, but I only just recently got into Python, so now I feel I'll be more capable / able to understand JavaScript.
I'm currently working on an idea I've had, a Fortune Cookie Maker. The user inputs text into a textbox input. This is stored in a variable. When the user clicks ok, it gets the text from the textbox, and sets it to that variable. Then, it switches the page, and gets the variable from the script, and sets a paragraph to the text value of that variable.
However, my problem is, the paragraph won't display the text.
Here's my code:
var fortune = null;
function dispTxt() {
var txt = document.getElementById('textbox').value;
var hid = document.getElementById('conftxt');
if (txt.length > 0) {
//hid.style.display = 'block';
document.getElementById("conftxt").style.opacity = 1;
document.getElementById("textbox").style.color = "#ffffff";
} else {
//hid.style.display = 'none';
document.getElementById("conftxt").style.opacity = 0;
//document.getElementById("textbox").style.color = "#000000";
}
document.getElementById("txt").addEventListener("onkeyup", function() {
dispTxt();
})
};
function confirm() {
//Get the text that is inputted by the user.
fortune = document.getElementById("conftxt").value;
window.location = "fortune.html";
window.alert(fortune);
}
function setFortune() {
document.getElementById('fortunetext').value = fortune;
}
And here's a link to the repl itself for reference.
Also, if anyone has any tips for how I should go about making the fortune cookie itself, please, let me know.
I essentially just want it to be so that once you confirm what the fortune says, the fortune cookie appears, and you can click on it, and break it open, and it reveals the fortune.
Thanks!

You say fortune = document.getElementById("conftxt").value;, but #conftxt is the button element.
fortune = document.getElementById("textbox").value; will do
But because the page refreshes/redirects to fortune.html the variable fortune is cleared again.
You have two options:
Use one HTML page, so you don't use redirects
Store the variable in localStorage or sessionStorage
Pass the value into the URL param. Links: Pass variable to URL and Get the passed variable from URl
I recommend 1.

You can't get the value because you are getting the wrong element
function confirm () {
fortune = document.getElementById("conftxt").value;
...
}
Should be
function confirm () {
fortune = document.getElementById("textbox").value;
...
}
Also, you are navigating between different pages, so, you need to pass this value

Related

How to create an onclick function which is called when a restart button is pressed

I am quite new to programming and am in desperate need of help.
I am trying to code a function that will carry out a resetting function upon pressing an already made reset button. I have a rough skeleton code however I am struggling with what to write within my function to allow it to physically clear the message field and any temporary variables made along with it.
Below is my code
onclick="restartButtonClicked()"
function restartButtonClicked() {
document.getElementById("MessageField") = ""
morseCode = [];
colours = [];
output = '';
message = '';
message.innerHTML = '';
}
document.getElementById("restartButton").onclick = restartButtonClicked;
I am sorry for my lack of detail but I am indeed, quite lost.
Thank you for your time.
If messageField is the ID of your html tag, this will reset your field:
document.getElementById("messageField").innerHTML = "";
You can add event handler to your button with both:
<button onclick="restartButtonClicked()" id="restartButton">restart</button>
and
document.getElementById("restartButton").addEventListener("click", restartButtonClicked);

Cognos passing a value to all prompts

So I am using jQuery in my reports and I have a suite of reports that all load thanks to jQuery all at once so the customer feels like the transitions are faster because they don't have to wait between each click. I want to be able to have all reports change based off of a prompt the customer uses. So if they select a specific day, all of the reports in the suite will change to that day. Or if they have a specific area they select, all of the reports go to that area. This will make it so the customer doesn't have to load the parameters in the prompt for each report. I am wonderin if there is a way to do this. I have looked and haven't found anything.
Edit..
So in my report that houses all of the iframes and the value prompt that I have named changeMonth I have this JS
<script>
var report = cognos.Report.getReport("_THIS_");
var radio = report.prompt.getControlByName('monthChange');
var currentRadioValue = radio.getValues()[0]; //Get initial value object
radio.setValidator(validateRadio); //Define function to validate prompt
function validateRadio(values) {
if (values && values.length > 0 && values[0].use != currentRadioValue.use) { //Only do anything if control has value and has changed
currentRadioValue = values[0]; //Assign new value for later comparison
for (var i=0; i<window.frames.length; i++) { //Loop through all iFrames
window.frames[i].changeValue(values[0].use); //Call the changeValue function passing in the radio button value
}
}
return true; //Indicates the prompt is valid
}
</script>
In the reports that I want iframed in I have a value prompt that is a drop down list with this code in an HTML tag.
<script>
function changeValue(str){
var report = cognos.Report.getReport("_THIS_"); //Grab a handle for the report
var control = report.prompt.getControlByName('monthChange'); //Grab a handle for the prompt control
control.addValues([{"use":str,"display":str}]); //Change the prompt to the passed in value
report.sendRequest(cognos.Report.Action.REPROMPT); //Reprompt the page
}
</script>
They were both drop down lists if that matters. I see that you listed them as radio buttons so I will try that here in a moment and let you know if that changed anything. But how I have it setup, is there something else i should be doing?
I was able to get this to work by creating a JavaScript function in each child report which changes a hidden prompt value which the query depends on and then reprompts the page. Here is the portion of the code that needs to be in every child object:
Child Report(s) Code
<script>
function changeValue(str){
var report = cognos.Report.getReport("_THIS_"); //Grab a handle for the report
var control = report.prompt.getControlByName('controlname'); //Grab a handle for the prompt control
control.addValues([{"use":str,"display":str}]); //Change the prompt to the passed in value
report.sendRequest(cognos.Report.Action.REPROMPT); //Reprompt the page
}
</script>
This utilizes the Cognos JavaScript Prompt API added in Cognos version 10.2. The functions getReport, getControlByName, addValues, and sendRequest are all functions provided by Cognos to make working with prompts in JavaScript easier. There's more info here:
Cognos JavaScript Prompt API documentation
In the container report I created a Cognos radio button value prompt. I coded the JavaScript to leverage the built-in onchange validation hook provided by Cognos in the API to run code when the radio button has changed. The code loops through all iFrames and calls the function defined above in each child report passing in the value of the radio button selected.
Container Report Code
<script>
var report = cognos.Report.getReport("_THIS_");
var radio = report.prompt.getControlByName('radio');
var currentRadioValue = radio.getValues()[0]; //Get initial value object
radio.setValidator(validateRadio); //Define function to validate prompt
function validateRadio(values) {
if (values && values.length > 0 && values[0].use != currentRadioValue.use) { //Only do anything if control has value and has changed
currentRadioValue = values[0]; //Assign new value for later comparison
for (var i=0; i<window.frames.length; i++) { //Loop through all iFrames
window.frames[i].changeValue(values[0].use); //Call the changeValue function passing in the radio button value
}
}
return true; //Indicates the prompt is valid
}
</script>
Note that in the above code the strings 'controlname' and 'radio' correspond to the Name property of the prompt controls in question. By default Cognos does not give prompt controls a name. Thus, you have to supply the name after creation. Whatever names you give them the script has to be adjusted accordingly to allow JavaScript to access their Cognos Prompt API objects.
This technique can be modified to take input from any of the variety of prompt controls available in Cognos. Additionally, in theory, the container doesn't even have to be Cognos at all. It could be a standalone Web page with controls that call the JavaScript functions in the iFrames when standard HTML onchange events fire. The only caveat is due to security restrictions browsers do not allow calling of functions within iFrames from containers that have a different domain than the iFrame. This is something to consider when designing a solution.

Why do my functions keep reading input from my input text field?

The input on my html form has a problem. Curently I am taking the input which is a twitter name into an Ajax function that calls tweets via php from the twitter api.
As I have a setInterval function to keep checking for updates, the input is passed again and again into the function to get tweets.
The problem is that the function seems to be reading the input directly from what is in the text input box. So if the user changes the text without pressing enter or hitting the button, the function keeps reading that text as the input. So the input entered initially is not fixed after pressing enter or hitting the button to submit.
Here is the html form taking in the input:
<div id="topdiv">Input Twitter ID: <input type="text" id="userid" onkeydown="if(event.keyCode===13) {document.getElementById('tweet-button').click();}">
<input type="submit" id="tweet-button" onclick="getStatusesX();" value="Get recent tweets">
<p id="tweetbox"></p>
</div>
Here are the functions:
function getStatusesX() {
var userID = document.getElementById("userid").value;
getStatuses(userID);
var intervalstop = setInterval(function() {getStatuses(userID);}, 20000);
clearInterval(intervalstop);}
//Create a cross-browser XMLHttp Request object
function getXMLHttp() {
var xmlhttp;
if (window.ActiveXObject) {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
XMLHttp = new XMLHttpRequest();
} else {
alert("Your browser does not support XMLHTTP!");
}
return XMLHttp;
}
//function that searches for the tweets via php
function getStatuses(userID){
XMLHttp1 = getXMLHttp();
//ajax call to a php file that will extract the tweets
XMLHttp1.open( 'GET', 'TwitterGlimpsePHP.php?userid='userID, true);
// Process the data when the ajax object changes its state
XMLHttp1.onreadystatechange = function() {
if( XMLHttp1.readyState == 4 ) {
if( XMLHttp1.status ==200 ) { //no problem has been detected
document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;
}
}
}
XMLHttp1.send(null);
}
I want the input to be taken as the text after enter is pressed. I have tried assigning it to variables but cannot work out why it keeps reading from the input field. Any help appreciated.
This is not an official answer - just trying to clear up my comments
This is what I mean by declaring outside the function...
var intervalstop;
function getStatusesX() {
clearInterval(intervalstop);
var userID = document.getElementById("userid").value;
getStatuses(userID);
intervalstop = setInterval(function() {getStatuses(userID);}, 20000);
}
that way you initialize the var and inside the function you clear first to ensure it's not compounding. Then you set the var to a new interval to begin again.
You said twitter doesn't like something about this code if the user clicks many times - Makes perfect sense. They will want to throttle the API to prevent someone from making 50,000 requests per minute cause of improper coding. You should check the API specs to make sure you're within a realistic zone and consider caching the results locally if you are pushing boundaries.
The issue is that you are re-reading the value of the textbox every time getStatuses is called.
Try capturing the value of the textbox first, and passing it into your getStatuses function:
So your new getStatusesX is:
function getStatusesX() {
var userID = document.getElementById("userid").value;
getStatuses(userID);
setInterval(function() {
getStatuses(userID);
}, 20000);
}
Update getStatuses to take a userID parameter and delete the line where you're reading the textbox's value inside of getStatuses.
That having been said, it might be an issue if this is possible to begin with - what if the user clicks the button to automatically refresh statuses multiple times? You might want to disable the button/textbox after it's been clicked, or have it clearInterval the old interval first.

How do I use part of a text form input to add and make it go to an url?

The title might not be clear, but I'll explain it here. I'm a total newbie and I have almost no knowlege in JS, so please be clear.
My main code is here:
function goTo()
{
var url = "http://myurl.com/";
var name = document.forms[0].name.value;
window.location = url+name;
return false;
}
The code uses a set url and a form value, then if I press the send button, it jumps to the preset url + the form value.
But what I want, is to get just the last part of the input, so for example, this is my input:
http://lolsite.com/testing/files/HAfg76SDA
And I want the code to get the part of the input after the "/", so the finished product would be "HAfg76SDA". Now I want to snip this product at the end of my preset url, so when I press the submit button, it goes to:
http://myurl.com/HAfg76SDA
I would like to know if is this even possible, and if it is, I would nedd a code i could use straight away. Btw. I tried to use
function goTo()
{
var url = "http://myurl.com/";
var name = document.forms[0].name.value.(lastIndexOf("/")+1);
window.location = url+name;
return false;
}
but it doesn't seem to work.
function goTo()
{
var url = "http://myurl.com/";
var name = document.forms[0].name.value;
window.location = url+name.substr(name.lastIndexOf('/')+1);
return false;
}

Code works when i put javascript alert in between anywhere

I have a function that runs on key tab press, it works fine when i put a javascipt alert in between the code, any kind of alert,if i remove the alert it stops working : my function
//Function to set the tab feture for focus to work properly on fields with autosuggestion(location and name)
function setFocusOnTab(name) {
var focusElement = "";
if(name == "name") {//For main contact field
if ($("#email").is(":visible")) {
$('#email').focus();
}
} else if(name == 'location_name') {//For main contact field
$("#country").focus();
} else {//For extra contact field
var outputDataCurrentVal = name.lastIndexOf('record_');
if(outputDataCurrentVal < 0) {
//ADDTIONAL CONTACT TAB
var outputDataCurrentName = name.lastIndexOf('_name_');
if(outputDataCurrentName >= 0) {
//Replacing the name to get location name.
locName = currentName.replace("_name_","_designation_");
focusElement = locName;
} else {
var outputDataCurrentLoc = name.lastIndexOf('_location_');
if(outputDataCurrentLoc >= 0) {
//Replacing the location name to get country name.
countryName = name.replace("_location_","_country_");
focusElement = countryName;
}
}
} else {
//Extra CONTACT TAB
var outputDataCurrentName = name.lastIndexOf('_name_');
if(outputDataCurrentName >= 0) {
//Replacing the name to get location name.
locName = currentName.replace("_name_","_location_");
focusElement = locName;
} else {
var outputDataCurrentLoc = name.lastIndexOf('_location_');
if(outputDataCurrentLoc >= 0) {
//Replacing the location name to get country name.
countryName = name.replace("_location_","_country_");
focusElement = countryName;
}
}
}
$("#" + focusElement).focus();
return false;
}
}
Sounds like you need something to halt your code, which is what alert() does.
You may need a callback instead.
What might be happening with alert() is that calling it causes the current window to lose focus (as focus moves to the new pop-up dialogue box), and after it's finished it re-focuses the window. This will trigger focus and blur events which might confuse your script, and in Safari the window may not re-focus at all.
It's not clear to me what you are doing here... how are you attaching this code to a tab key event? What event is supposed to be cancelled by the return false;? If you are using keypress, then that simply won't get called for the Tab key in IE, Safari or Chrome. If you are using keydown, then cancelling the event won't prevent the tabbing in Opera. And what about Shift-Tab?
Reproducing/altering browser keyboard behaviour is hard: it's much better not to if there's any other way. For making controls like a drop-down suggester work you are probably much better off just setting the declarative tabIndex on the elements concerned and letting the browser work out how to sort out the tabs from there.
I should write something on this post. I read so many blogs and post but couldn't get the right solution from anywhere else. Even in this post, I looked more detail and tried each of solution.
Finally reading the answer of bobince, I could figured out the solution. In my case, I have set the focus to another textbox ( not required type) and later when I finish my job, I set back focus to original one. So the morel story is we just need to set focus somewhere else from current element which actually done by alert and I have replaced that on by setting the focus on non required element.

Categories

Resources