Connecting user input to a DOM's value - javascript

How can I connect a button which remains constant with a DOM's value in order to capture a user's selection?
I'm creating a taste questionnaire which asks users to select the style they prefer from amongst a series of pairs, and the specific pairings shown will change based upon the items previously selected. I'd like the 'Select' buttons under each set to remain constant so that the entire page doesn't need to be refreshed for each image.
HTML
<table>
<tr><td id="question" colspan=5 > Question 1</td></tr>
<tr><td >
<img src="files/z1.png" name="taste" value="trendy[1]" />
</td> <td >
<img src="files/z2.png" name="taste1" value="classic[1]"/>
</td> </tr>
<tr><td >
<img alt"Select" src="files/Select.jpg" onclick="javascript:manipulateDOM()">
</td><td >
<img alt"Select" src="files/Select.jpg" onclick="javascript:manipulateDOM1()">
</td></tr></table>
Javascript to determine which image is shown based on user input
var NumberOfImages = 7 - 1; //-1 because array members starts from 0
var trendy = new Array(NumberOfImages);
trendy[0] = "files/z1.png";
trendy[1] = "files/z1.png";
trendy[2] = "files/z14.png";
trendy[3] = "files/z4.png";
trendy[4] = "files/z5.png";
trendy[5] = "files/z6.png";
trendy[6] = "files/z9.png";
var imgNumber = 1; //array key of current image
var NumberOfImages = 7 - 1; //-1 because array members starts from 0
var classic = new Array(NumberOfImages);
classic[0] = "files/z2.png";
classic[1] = "files/z2.png";
classic[2] = "files/z12.png";
classic[3] = "files/z3.png";
classic[4] = "files/z3.png";
classic[5] = "files/z7.png";
classic[6] = "files/z8.png";
var classicNumber = 1; //array key of current image
var text = 6 - 1; //-1 because array members starts from 0
var text = new Array;
text[0] = "Question 1"
text[1] = "Question 2"
text[2] = "Question 3"
text[3] = "Question 4"
text[4] = "Question 5"
text[5] = "Question 6"
text[6] = "Question 7"
var textNumber = 1; //array key of current image
function manipulateDOM() {
changeObjects();
NextImage();
}
function changeObjects() {
document.getElementById("question").innerHTML = text[textNumber];
}
function NextImage() {
if (imgNumber < NumberOfImages) //Stop moving forward when we are out of images
{
trendy[0] = trendy[1]; trendy[1] = trendy[2]; trendy[2] = trendy[3]; trendy[2] = trendy[3]; trendy[3] = trendy[4]; trendy[4] = trendy[5]; trendy[5] = trendy[6];
document.images["taste"].src = trendy[imgNumber];
classic[0] = classic[1]; classic[1] = classic[2]; classic[2] = classic[3]; classic[3] = classic[4]; classic[4] = classic[5]; classic[5] = classic[6];
document.images["taste1"].src = classic[imgNumber];
text[0] = text[1]; text[1] = text[2]; text[2] = text[3]; text[3] = text[4]; text[4] = text[5]; text[5] = text[6];
document.getElementById["question"].innerHTML = text[textNumber];
}
}
function manipulateDOM1() {
changeObjects();
NextImage1();
}
function NextImage1() {
if (imgNumber < NumberOfImages) //Stop moving forward when we are out of images
{
trendy[0] = trendy[1]; trendy[1] = trendy[2]; trendy[2] = trendy[3]; trendy[2] = trendy[3]; trendy[3] = trendy[4]; trendy[4] = trendy[5]; trendy[5] = trendy[6];
document.images["taste"].src = trendy[imgNumber];
classic[0] = classic[1]; classic[1] = classic[2]; classic[2] = classic[3]; classic[3] = classic[4]; classic[4] = classic[5]; classic[5] = classic[6];
document.images["taste1"].src = classic[imgNumber];
text[0] = text[1]; text[1] = text[2]; text[2] = text[3]; text[3] = text[4]; text[4] = text[5]; text[5] = text[6];
document.getElementById["question"].innerHTML = text[textNumber];
}
}

Related

If condition on event listeners

I would like to use the addEventListener as a condition
so that if the condition is true by the clicking of the
image, the code executes, but it doesn't seem to work.
HTML
<div class = "content">
<img src = "dog.png" alt = "" id = "firstImage" >
<img src = "coatOfArm.png" alt = "" id = "second
Image" >
<p id = "score" >0</p>
</div>
JavaScript
var firstImage =
document.getElementById("firstImage");
var secondImage =
document.getElementById("secondImage");
var score= document.getElementById("score");
var totalScore_1 = 0;
var totalScore_2 = 0;
firstImage.addEventListeners("click",function() {
totalScore_1++;
score.innerHTML = totalScore_1;
})
secondImage.addEventListeners("click", function() {
totalScore_2++;
score.innerHTML = totalScore_2;
})
function increScore() {
if(first Image clicked == true){
firstImage. append(score) ;
} else{
secondImage. append(score) ;
}
} ;
increScore() ;

How to retrieve session storage values and pass it to radio buttons and checkboxes?

As the question is asking, can you get the values from the session storage or local storage to radio buttons on html and the same thing for the checkboxes?
My code:
var customername = {"firstname" : getCookie("firstname"), "lastname" : getCookie("lastname")};
var curcustomer1 = {"firstname" : getCookie("firstname"), "lastname" : getCookie("lastname")};
var lastvist = {"date" : dateall} // only display the date and time
var myJSON = JSON.stringify(customername);
var myJSON1 = JSON.stringify(lastvist); // has the date when the user last has visited
var myJSON2 = JSON.stringify(curcustomer1);
var myJSON3full = JSON.stringify(custinfo);
sessionStorage.setItem("custinfo", myJSON3full);
var objectfull = sessionStorage.getItem("custinfo");
objfull = JSON.parse(objectfull);
var object = sessionStorage.getItem("customername");
obj = JSON.parse(object);
if(object != myJSON) {
sessionStorage.setItem("customername", myJSON);
var object = sessionStorage.getItem("customername");
obj = JSON.parse(object);
var curcustomer = customername;
var myJSONcopy = JSON.stringify(curcustomer);
var object2 = sessionStorage.setItem("curcustomer", myJSONcopy);
var msg5 = "Welcome ";
document.getElementById("customer").innerHTML = msg5 + " " + "New Customer";
document.getElementById("date1").innerHTML = "";
var radiobtn = document.getElementsByName("type");
if(radiobtn.value != 8) {
document.elem.type.value="8";
}
var radiobtn1 = document.getElementsByName("special");
if(radiobtn1.value != 0) {
document.elem.special.value="0";
}
for (var i = 0; i < extras.length; i++) {
if (extras[i].checked) {
extras[i].checked = false;
}
}
}
if(object == myJSONcopy) {
radiobtn = document.getElementsByClassName("type").innerHTML = sessionStorage.getItem("type");
radiobtn1 = document.getElementsByClassName("special").innerHTML = sessionStorage.getItem("special");
checboxes = document.getElementsByClassName("extras").innerHTML = sessionStorage.getItem("extras");
}
<td>
<input type="radio" name="type" value="8" checked>Small $8.00
<br>
<input type="radio" name="type" value="10">Medium $10.00
<br>
<input type="radio" name="type" value="15">Large $15.00
<br>
<input type="radio" name="type" value="18">Extra Large $18.00
<br>
<br>
</td>
if you are trying to add the item to multiple buttons that share the same className then you will have to do something like this:
var list = document.getElementsByClassName('type');
var i;
for (i = 0; n < list.length; ++i) {
list[i].value= sessionStorage.getItem('events')
};
But if it's just one button then I will suggest you use getElementById
like this
document.getElementById('Id').value = sessionStorage("events");

Trying to add a link to open a 'steam://run/' link to a random word array

So i'm messing about creating a random word picker to pick a steam game from my library, I want to add a 'Launch' link to each random word. Heres the code;
<html>
<head>
<link rel="stylesheet" type="text/css" href="steam_gen_style.css">
<title>Untitled</title>
<SCRIPT LANGUAGE="JavaScript">
<!--
// Use the following variable to specify
// the number of random words
var NumberOfWords = 28
var words = new BuildArray(NumberOfWords)
// Use the following variables to
// define your random words:
words[1] = "ARK: Survival Evolved/346110"
words[2] = "Portal 2/620"
words[3] = "Left 4 Dead 2/550"
words[4] = "CS:GO/730"
words[5] = "And Yet It Moves/18700"
words[6] = "Bridge Constructer/250460"
words[7] = "Bridge Constructer Medieval/319850"
words[8] = "Half-Life 2/220"
words[9] = "GTA V/271590"
words[10] = "Antichamber/219890"
words[11] = "World of Goo/22000"
words[12] = "Super meat Boy/40800"
words[13] = "Hotline Miami/219150"
words[14] = "Metro: Last Light/287390"
words[15] = "GTA IV/12210"
words[16] = "Oddworld: New'n'Tasty/314660"
words[17] = "TUG"
words[18] = "Trials Evo"
words[19] = "Super Hotline Miami"
words[20] = "Outlast"
words[21] = "Besiege"
words[22] = "Next Car Game"
words[23] = "Rust"
words[24] = "Garry's Mod"
words[25] = "Planetary Annihilation"
words[26] = "Skyrim"
words[27] = "Minecraft"
words[28] = "The Forest"
function BuildArray(size){
this.length = size
for (var i = 1; i <= size; i++){
this[i] = null}
return this
}
function PickRandomWord(frm) {
var rnd = Math.ceil(Math.random() * NumberOfWords);
var index = words[rnd].indexOf("/");
frm.WordBox.value = words[rnd].substring(0, index);
var link = document.getElementById("gameLink");
var str = words[rnd].substring(index + 1, words[rnd].length);
link.innerHTML = "<a href='steam://run/" + str + "'>Click</a>";
}
// Display the word inside the text box
frm.WordBox.value = words[rnd]
}
//-->
</SCRIPT>
<body>
<div id="top"></div>
<header id="header">
<h1> Today you will play </h1>
<FORM NAME="WordForm" id="box">
<INPUT
TYPE=TEXT SIZE=30 NAME="WordBox" id="output"><BR>
<INPUT TYPE=BUTTON id="button" onClick="PickRandomWord(document.WordForm)"
VALUE="Click Here to Get a Random Word">
</FORM>
<p>Link to game: </p>
<p id="gameLink"></p>
</header>
</body>
</html>
I've tried a few things but stuck, by the way, I've never done anything with java I only know a little bit of HTMl, I'm just messing around to learn things!
Well if you want a link to be generated based on the game selected you can add below 2 lines at the end of PickRandomWord(),
var link = document.getElementById("gameLink");
link.innerHTML = ""+words[rnd]+"";
Now add 2 more HTML lines after you form,
<p>Link to game: </p>
<p id="gameLink"></p>
UPDATE: You need to have the numbers like 346110, 620 to be stored somewhere so that you can access them depending on the game you select. As you asked for an example, here is what I have come up with.
Here is a demo
Suppose you append the numbers along with the name of the game as,
words[1] = "ARK: Survival Evolved/346110";
words[2] = "Portal 2/620";
Now change your PickRandomWord() function as,
function PickRandomWord(frm) {
var rnd = Math.ceil(Math.random() * NumberOfWords);
var index = words[rnd].indexOf("/");
frm.WordBox.value = words[rnd].substring(0, index);
var link = document.getElementById("gameLink");
var str = words[rnd].substring(index + 1, words[rnd].length);
link.innerHTML = "<a href='steam://run/" + str + "'>Click</a>";
}
UPDATE2: You are having problems with your parenthesis and it is not advisable to write JavaScript statements without semi-colon(;). Copy and paste the below code as it is,
<script>
var NumberOfWords = 28
var words = new BuildArray(NumberOfWords)
words[1] = "ARK: Survival Evolved/346110"
words[2] = "Portal 2/620"
words[3] = "Left 4 Dead 2/621"
words[4] = "CS:GO/622"
words[5] = "And Yet It Moves/622"
words[6] = "Bridge Constructer/6203"
words[7] = "Bridge Constructer Medieval/6520"
words[8] = "Half-Life 2/6290"
words[9] = "GTA V/6020"
words[10] = "Antichamber/6250"
words[11] = "World of Goo/6820"
words[12] = "Super meat Boy/6290"
words[13] = "Hotline Miami/61020"
words[14] = "Metro: Last Light/62110"
words[15] = "GTA IV/67620"
words[16] = "Oddworld: New'n'Tasty/62870"
words[17] = "TUG/687820"
words[18] = "Trials Evo/6120"
words[19] = "Super Hotline Miami/60"
words[20] = "Outlast/690"
words[21] = "Besiege/62900"
words[22] = "Next Car Game/62023"
words[23] = "Rust/620879"
words[24] = "Garry's Mod/626750"
words[25] = "Planetary Annihilation/6260"
words[26] = "Skyrim/6276870"
words[27] = "Minecraft/656520"
words[28] = "The Forest/5620"
function BuildArray(size) {
this.length = size
for (var i = 1; i <= size; i++) {
this[i] = null
}
return this
}
function PickRandomWord(frm) {
var rnd = Math.ceil(Math.random() * NumberOfWords);
var index = words[rnd].indexOf("/");
frm.WordBox.value = words[rnd].substring(0, index);
var link = document.getElementById("gameLink");
var str = words[rnd].substring(index + 1, words[rnd].length);
link.innerHTML = "<a href='steam://run/" + str + "'>Click</a>";
}
</SCRIPT>
<body>
<div id="top"></div>
<header id="header">
<h1> Today you will play the shit out of </h1>
<FORM NAME="WordForm" id="box">
<INPUT TYPE=TEXT SIZE=30 NAME="WordBox" id="output">
<BR>
<INPUT TYPE=BUTTON id="button" onClick="PickRandomWord(document.WordForm)" VALUE="Click Here to Get a Random Word">
</form>
<p>Link to game:</p>
<p id="gameLink"></p>
</header>
</body>

Drop down box text disappears after completing a function, how can I get it to display what option was chosen?

The functions below work fine, the only thing I need help with is that when I pick an option from a drop down menu, it runs the function, but it erases all of the options in the drop down box. How can I get it NOT to do that and continue displaying my original options in the same drop down box?
<script type="text/javascript">
function gbid(s) {
return document.getElementById(s);
}
function myCount() {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("somefilepathhere.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var agent,count
agent=document.getElementById("tAgent").value;
if (agent=="Agent1")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(1,1).Value;
}
else if (agent=="Agent2")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(2,1).Value;
}
document.getElementById("disphere").innerHTML = count;
excel.Quit();
excel.Application.Quit();
}
function saveToExcel() {
var myApp = new ActiveXObject("Excel.Application");
myApp.visible = false;
var xlCellTypeLastCell = 11;
var x = document.forms["f1"]["tAgent"].value;
if (x == null || x == "") {
alert("You must select an 'Entered By' option!");
return false;
}
else
var myWorkbook = myApp.Workbooks.Open(filePath);
var myWorksheet = myWorkbook.Worksheets(1);
myWorksheet.Activate;
objRange = myWorksheet.UsedRange;
objRange.SpecialCells(xlCellTypeLastCell).Activate;
newRow = myApp.ActiveCell.Row + 1;
alert('A new log was created on row '+newRow);
strNewCell = "A" + newRow;
myApp.Range(strNewCell).Activate;
myWorksheet.Cells(newRow,1).value = f1.tMemberid.value;
myWorksheet.Cells(newRow,2).value = f1.tDate.value;
myWorksheet.Cells(newRow,3).value = f1.tRep.value;
myWorksheet.Cells(newRow,4).value = f1.tIssuerep.value;
myWorksheet.Cells(newRow,5).value = f1.tLOB.value;
myWorksheet.Cells(newRow,6).value = f1.tContactnum.value;
myWorksheet.Cells(newRow,7).value = f1.tMembername.value;
myWorksheet.Cells(newRow,8).value = f1.tIssid.value;
myWorksheet.Cells(newRow,9).value = f1.tTypeofissue.value;
myWorksheet.Cells(newRow,10).value = f1.tDiscofissue.value;
myWorksheet.Cells(newRow,11).value = f1.tTimesent.value;
myWorksheet.Cells(newRow,12).value = f1.tSendto.value;
myWorksheet.Cells(newRow,13).value = f1.tAgent.value;
myWorkbook.Close(true);
myApp.Workbooks.Close;
myApp.Close;
alert('Process Complete!');
}
</script>
<table >
<tr>
<td class="tb_bor" Align="center" ><h1>ACA Issues Tracker</h1><br />
<b>Entered By: </b>
<select name="tAgent" id="tAgent" style="80% !important;" onchange="myCount()">
<option value="" ></option>
<option value="Agent1" >Agent 1</option>
<option value="Agent2" >Agent 2</option>
</select>
<br />You have completed: <p id="disphere"></p>
<hr>
</td>
</tr>
</table>
With the below line you overwrite the inner text of your select field:
count = gbid( 'tAgent' ).innerText = excel_sheet.Cells( 1,1 ).Value;
^
|
Allthough I'm not clear on what you desire to achieve with the code because I don't understand your usecase, I think you might have mistaken the second equals sign with a string concatenation or something?
This might be what you tried to achieve:
count = gbid( 'tAgent' ).innerText + ' ' + excel_sheet.Cells( 1,1 ).Value;
This is a corrected version of your function:
function myCount() {
var excel = new ActiveXObject( 'Excel.Application' ),
excel_file = excel.Workbooks.Open( 'somefilepathhere.xlsx' ),
excel_sheet = excel.Worksheets( 'Sheet1' ),
agent = document.getElementById( 'tAgent' ).value,
count;
if ( agent === 'Agent1' ) {
count = excel_sheet.Cells( 1,1 ).Value;
} else if ( agent === 'Agent2' ) {
count = excel_sheet.Cells( 2,1 ).Value;
}
document.getElementById( 'disphere' ).innerHTML = count;
excel.Quit();
excel.Application.Quit();
}

Matching radio button selection with nested Array content in Javascript

UPDATE 6-25-2014
Any insight would be appreciated!
UPDATE 6-21-2014
I tried to make the radio variables, global so the 'if block' in the 'answerFwd' function could be compared to the correctAnswer Array, but that didn't work!
UPDATE 6-16-2014
ADDED JS FIDDLE
I am building a quiz and creating an array of radio buttons dynamically, and would like to match the selected button with the correct answer I have established in the question array.
html
<div id="responses">
<input type="radio" name="choices" class="radioButtons" value="0" id="choice0">
<div id="c0" class="choiceText">The Observers</div>
<input type="radio" name="choices" class="radioButtons" value="1" id="choice1">
<div id="c1" class="choiceText">The Watchers </div>
<input type="radio" name="choices" class="radioButtons" value="2" id="choice2">
<div id="c2" class="choiceText">The Sentinels</div>
<input type="radio" name="choices" class="radioButtons" value="3" id="choice3">
<div id="c3" class="choiceText">The Oa</div>
</div>
questions:
var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0 }, {
"question": "What is the name of Darth Vader's flag ship?",
"choices": ["The Avenger", "Devastator ", "Conquest", "The Executor"],
"correctAnswer": 3 },{},{} //other questions];
var item = allQuestions[0];
var currentQuestion = 0;
var playersScore = 0;
//function which creates the buttons
function createRadioButtonFromArray(array) {
var len = array.length;
var responses = document.getElementById("responses");
responses.innerHTML = '';
for (var i = 0; i < len; i++) {
radio = document.createElement("input"); //Updated 6-21-2014 removed 'var'
radio.type = "radio";
radio.name = "choices";
radio.className = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
ar radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.className = "choiceText";
radioText.innerHTML = array[i];
responses.appendChild(radio);
responses.appendChild(radioText);
}
}
function answerFwd() {
var answerOutput = " ";
var itemAnswers = allQuestions;
var playerTally = 0; //Updated 6-9-2014
var playerFeedback = " "; //Updated 6-9-2014
var playerMessage = document.getElementById("playerMessage"); //Updated 6-9-2014
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
createRadioButtonFromArray(itemAnswers[currentQuestion].choices);
* Updated 6-9-2014 I am stumped; This doesn't work but I was encouraged I got a score tally on the page! Am I comparing the elements correctly? Updated 6-21-2014 This reversed the gain, where I had the tally render on the screen*
if (itemAnswers.correctAnswer === responses.id) { //Updated 6-21-2014
playerTally += 1;
playerFeedback += "<h5>" + playerTally + "</h5> <br/>";
playerMessage.innerHTML = playerFeedback;
}
}
At first I tried to debug this but had trouble finding where the error was coming from.
One thing I noticed was currentAnswer variable was only being set once. (when it was declared)
Another thing that would make this cleaner is storing each response to each question as a property of the questions object.
For example: {"question": "What is the registry of the Starship Reliant?","choices": ["NX-01", "NCC-1864", "NCC-1701", "NCC-2000"],"correctAnswer": 1,"selectedAnswer": 0}
This is a good example of why you may want to use object oriented programming. You can keep the global namespace clean, while also having tighter control over your variables.
I put together this Quiz Code using some object oriented principles:
JavaScript
var Quiz = function(questions) {
this.questions = questions;
this.$template = {
"header": document.querySelector(".question"),
"options": document.querySelector(".question-choices")
};
this.init();
}
Quiz.prototype = {
"init": function() {
this.question = 0;
this.generateQuestion();
this.bindEvents();
},
//gets called when this.question == this.questions.length, calculates a score percentage and alerts it
"score": function() {
var correctCount = 0;
this.questions.forEach(function(question){
if ( (question.selectedAnswer || -1) === question.correctAnswer ) correctCount += 1
})
alert("Score: " + ((correctCount / this.questions.length) * 100) + "%")
},
//Gets called during initialization, and also after a nav button is pressed, loads the question and shows the choices
"generateQuestion": function() {
var question = this.questions[this.question];
this.$template.header.innerHTML = question.question;
this.$template.options.innerHTML = "";
question.choices.forEach(this.createRadio.bind(this));
},
//Binds the previous, and next event handlers, to navigate through the questions
"bindEvents": function() {
var _this = this,
$nextBtn = document.querySelector(".question-navigation--next"),
$prevBtn = document.querySelector(".question-navigation--prev");
$nextBtn.addEventListener("click", function(e) {
//Go to the next question
_this.question++;
if ( _this.question == _this.questions.length ) {
_this.score();
} else {
_this.generateQuestion();
}
});
$prevBtn.addEventListener("click", function(e) {
_this.question--;
if ( _this.question <= 0 ) _this.question = 0
_this.generateQuestion();
});
},
//Create each individual radio button, is callback in a forEach loop
"createRadio": function(choice, index) {
var question = this.questions[this.question];
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "options";
radio.id = "option-"+index;
if ( question.selectedAnswer === index ) {
radio.checked = true;
}
radio.addEventListener("click", function(e) {
question.selectedAnswer = index;
})
var radioText = document.createElement("label");
radioText.setAttribute("for", "option-"+index)
radioText.innerHTML = choice;
radioText.insertBefore(radio, radioText.firstChild);
this.$template.options.appendChild(radioText);
}
}
var q = new Quiz(allQuestions)

Categories

Resources