Im really new to coding, and i wanted to know if it was possible to randomly generate entries submitted by a user.
For example.
If the user was to enter 5 words,
Would they then be stored in a way that you would have a button to just click 'next' and randomly move through them.
Ive checked all around but cant seem to find anything,
Please help!!
Thanks
Your question is very abstract but the answer below details the following:
A user is able to save an infinite number of words.
A button is then able to randomly take one of these words and display it on the screen.
preview
https://jsfiddle.net/gwcq2qc9/1/
html
<input id="word"><button id="save">save</button>
<br><br>
<button id="show">show</button><br>
Random: <span id="output">...</span>
javascript
var words = [];
var input = document.getElementById('word');
var saveButton = document.getElementById('save');
var showWordButton = document.getElementById('show');
var output = document.getElementById('output');
saveButton.addEventListener('click', function () {
words.push(input.value);
input.value = '';
}, false);
showWordButton.addEventListener('click', function () {
output.innerHTML = getRandomWord();
})
function getRandomWord () {
return words[Math.floor(Math.random()*words.length)]
}
Related
Use case is to create Add/show/select/delete text messages on a page. I have used array to store the messages on each click till here it works fine but when I try to create Divs and show the messages in grid, I am having duplication on each click. I can see that my function is reading the array fine and creating the div's on the first click but it does not clear the previously created div on second iteration. Not sure how to approach this. Please advise.
here is the snippet.
<script>
//<!-- Fetch data from Textarea when user Click Save and create or push in an array -->
let ArrNotes = [];
function SaveNote() {
let edittext = document.getElementById("editor").value;
ArrNotes.push(edittext);
document.getElementById("SavedNote").innerHTML = ArrNotes;
let container = document.getElementById("GridNotes");
container.className= "GridNotes";
ArrNotes.forEach(createGrid);
function createGrid(item,index)
{
text = undefined;
var tag = document.createElement("div");
tag.className= "grid";
var text = document.createTextNode(index + ": " + item);
//tag.appendChild(text);
container.appendChild(text);
}
}
basically I want to provide the user two options, Yes or No. For example, if he clicks the Yes button, then this information is saved and I can show what he chose at the end of the questionnaire.
I'm trying this way, but it's not working. At the end, nothing appears on the screen...
answer2-A = Yes Button
answer2-B = No Button
----------------------------//------------------------//-------------------------
document.getElementById('answer2-A').addEventListener("click", defineYes);
document.getElementById('answer2-B').addEventListener("click", defineNo);
};
function defineYes(){
document.getElementById('answer2-A').value = 'Yes';
document.getElementById('info').innerHTML = document.getElementById('answer2-A');
};
function defineNo(){
document.getElementById('answer2-B').value = 'No';
document.getElementById('info').innerHTML = document.getElementById('answer2-B');
Few things to address - without seeing the HTML I assume the value property isn't set on the buttons. Additionally you can/should get references to the buttons and re-use them instead of querying over and over. You can use the target of the event to access which button you clicked.
const yesBtn = document.getElementById('answer2-A')
const noBtn = document.getElementById('answer2-B')
const info = document.getElementById('info');
yesBtn.addEventListener("click", trackClick);
noBtn.addEventListener("click", trackClick);
function trackClick(e) {
info.innerHTML = e.target.value;
}
<button id="answer2-A" value="Yes">Yes</button>
<button id="answer2-B" value="No">No</button>
<div id="info"></div>
I have this idea where if you press a button, it'll display a text, but not only one text, but multiple, just not at once. If you press the button again, it'll display another text after it. So far, I'm only limited to only one text being displayed. I'm not really sure how to go from what I'm trying to achieve. I had an idea about using arrays but arrays and buttons didn't seem to work all that great, at least for me. I might have done something wrong for it to not work. Anyways, the idea was that the button would call from the array each time you'd click it so it'd display a different text.
So if you press the button once, it would output: "Hello"
And if you press it again, it would output: "How are you?"
and so on and so forth.
How would I do this in terms of making something like this happen?
Disclaimer: I don't want the text to be replaced with a new text. I want it solely outputted afterwards.
<button id = "age-button" button onClick = "ageButton()">AGE!</button>
<script>
function ageButton() {
var text = "You are born.";
document.getElementById("age1").innerHTML = text;
}
</script>
This code above only displays one text. How would I let it display another text after I press the button again?
// Define array of string that you would like to show on each click
const labels = [
"String 1",
"String 2",
"String 3"
// ... so on (add as many as you like)
];
// lets start from zero index
let currentIndex = 0;
// get the button HTMLElement
const nextBtn = document.querySelector("#next-btn");
const contentsEl = document.querySelector("#contents");
// attach onClick event handler / listner
nextBtn.addEventListener("click", function(event) {
// get the label string to show
const label = labels[currentIndex];
const p = document.createElement("p");
p.textContent = label;
contentsEl.append(p);
// increment the index
currentIndex++;
// set a trap
if (currentIndex === labels.length) {
//(bonus) disable the button when you reach the end
this.disabled = true;
}
});
<button id="next-btn">Show Next</button>
<div id="contents"></div>
Here is an example how you can do that.
let texts = ["You are born", "Hi there", "I'm ready"];
function ageButton() {
let line = texts.shift(); //use shift to get the first element in array
if (line) {
//use += operator to append to previous content
document.getElementById("age1").innerHTML += "<p>" + line + "</p>";
}
}
<button id="age-button" onclick="ageButton()">AGE!</button>
<div id="age1"></div>
Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone
I am trying to add the values from a text-box (which keeps changing) and a drop-down list (respondents click an answer). For some reason, I am not able to capture the value from the text-box. I am not sure where I am going wrong! Can someone please help, thank you.
Qualtrics.SurveyEngine.addOnload(function()
{
var InputA = $("QR~QID88");
var dropB = $("QR~QID85");
var InputTotalC = $("QR~"+this.questionId);
InputTotalC.readOnly= true;
Event.observe(dropB,'change',function(e){
var dropIdB= dropB.value;
dropB.select("option").each(function(s){
if(s.value==dropIdB)
{
dropIdB=parseInt(s.text);
}
});
var InputA1 = InputA.value;
if(dropIdB>=0) InputTotalC.value=(InputA1+dropIdB)-1;
else InputTotalC.value="0";
});
});