Button onclick more than once, different text in javascript - javascript

So i made this button, and i made the description text change from
{description}
to "No..." upon clicking. This is what i made:
function changeText(txt){
document.getElementById('name').innerHTML = txt;
}
<p>
<b id='name'>{description}</b>.
</p>
<input type='image'
onclick='changeText("No...")'
src='http://i.imgur.com/4y6bzH9.png'
style="margin-left: 540px; margin-bottom: 20px; position: absolute; outline: none;"/>
If you want, you can view what i did on /http://yosougay.tumblr.com/
I tried to make the description text change another time upon clicking another one time on the same button, so i tried adding another onClick, to make the description text change to "Another text" the next time you click the button.
function changeText(txt){
document.getElementById('name').innerHTML = txt;
}
<p>
<b id='name'>{description}</b>.
</p>
<input type='image'
onclick='changeText("No...")';
onclick='changeText("Another text")';src='http://i.imgur.com/4y6bzH9.png'
style="margin-left: 540px; margin-bottom: 20px; position: absolute; outline: none;" />
I tested it, and it didn't work. Please, is it possible to make a JavaScript button that changes the text to different texts every time it is clicked?
So far, I've only been able two make the text change once.

Try something like this: http://jsfiddle.net/54pp2/2/
<input id="click" type="button" value="click" />
<label id="test">Test</label>
$(document).ready(function () {
var textArray = [];
textArray[0] = 'test 1';
textArray[1] = 'test 2';
textArray[2] = 'test 3';
textArray[3] = 'test 4';
var idx = 0;
$('input#click').on('click', function(){
idx++;
var newidx = idx % textArray.length;
$('label#test').text(textArray[newidx]);
});
});

Sure you can.
You can only bind one click listener that way. Duplicating the attribute onclick will only override the first one, not provide two click listeners.
What you want to do is to handle the "different text every time" in you single onclick listener.
<script>
var txts = ["first", "second", "third"]
var counter = 0;
function changeText() {
document.getElementById('name').innerHTML = txts[counter%3];
counter++;
}
</script>
<p>
<b id='name'>{description}</b>.
</p>
<input type='image'
onclick='changeText()'
src='http://i.imgur.com/4y6bzH9.png'
style="margin-left: 540px;
margin-bottom: 20px;
position: absolute;
outline: none;"/>

I think this what you want
<script>
<!--
$(document).ready(function(){
var textarray ={"No...","Another Text"};
var count = 0;
$('input[type="image"]').click(function(){
$('#name').text(textarray[count]);
count = count==0?1:0;
});
});
// -->
</script>
<p> <b id='name'>{description}</b>. </p>
<input type='image' onclick='changeText("No...")' src='http://i.imgur.com/4y6bzH9.png'
style="margin-left:540px; margin-bottom:20px; position:absolute; outline:none;"/>
<br /><br />

You could keep track of how many times the button has been clicked from inside javascript.
<script>
var clicked = 0;
function changeText(){
if (clicked == 0) {
document.getElementById('name').innerHTML = "No...";
}
else if (clicked == 1) {
document.getElementById('name').innerHTML = "Another text";
}
clicked++;
}
</script>
Notice how I removed the argument from changeText() as well.

Fiddle
My suggestion is to change the onclick to onclick='changeText()'.
Store the texts in an array, and use a count property on the element. This will also move to the first text and repeat, on the third click.
var texts = [
'No',
'Another text'
];
function changeText(){
var elem = document.getElementById('name');
if(typeof elem.count == 'undefined'){
elem.count = 0;
} else {
elem.count++;
}
if(elem.count == texts.length){
elem.count = 0;
}
elem.innerHTML = texts[elem.count];
}

Related

How to include a input in a label in a querySelector() in javascript?

I am trying to construct a personality quiz for my school project. Everything was working fine until I decided that I want the inputs for the radio buttons to be just pictures. The problem is that I am not sure how to save the selected choice and its value, in order to calculate the result.
This is my HTML code:
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<input type="radio" name="colour" class="a" value="-1" />
<label for="p">
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
This is my CSS:
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
And this is my Javascript:
function submitSimpleQuiz() {
"use strict";
var colour = praseInt(document.querySelector('input[name = "colour"]:checked').value);
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
} else {
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
});
This is just one question and answer but essentially all the answers should add up to an outcome which will display a personality description. I don't know why the button for submitting doesn't work anymore.
I would greatly appreciate the help.
I am only new to coding, but I tried including the label into the javascript and also changing the layout of the HTML so that the input is included in the label tag.
As I am sure you won't stop with only 1 question, here is a working snippet in which you can add more questions easily:
function submitSimpleQuiz() {
"use strict";
var total = 0;
var answer = ""; // Added, just because… (see below)
// Easy selection, now! That counts only "selected" inputs!
var inputs = document.querySelectorAll("#simplequiz .selected input");
for (var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if (total < 0) {
answer = "Goth";
} else {
answer = "Minimalistic";
}
// Moved outside of the if to only have these instructions one time
document.getElementById("simplequiz").style.display = "none";
document.getElementById("answer").innerHTML = answer;
}
// Your other code, I haven't touched it. Promise.
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<!-- Modified order -->
<label for="p">
<input type="radio" name="colour" class="a" value="-1" />
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
<!-- Added another one below -->
<label for="p">
<input type="radio" name="colour" class="a" value="1" />
<img src="images/2.jpg" alt="Minimal colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
<!-- Added "answer" -->
<div id="answer"></div>
Anyway, I've got a few remarks, here:
⋅ Your function submitSimpleQuiz is in JavaScript only, whereas your other code is in jQuery. You should choose what you want to use!
⋅ I moved the inputs in your labels to make it easier to select them.
⋅ Why are you using inputs if you're hiding them, and can't/don't check them?!…
Hope it helps.
You need to remove line :
$('#simplequiz input:radio').addClass('input_hidden');
Or you need to modify the line:
var colour = parseInt(document.querySelector('input[name = "colour"]:checked').value);
Because if you uncheck radiobutton you can't get the value. And You have to use parseInt not praseInt. it's an error.
First off all you need to import Jquery for using Jquery function $.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Second it is parseInt not praseInt.
Third:
use this piece of code instead of yours:
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
Fourth:
for your script to work correctly your javasScript should be -
<script type="text/javascript">
function submitSimpleQuiz(){
"use strict";
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
if (document.querySelector("div#simplequiz input[name = 'colour']").checked) {
colour = 0;
}
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
}
else
{
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>

Hide text with the same button it opened it

how can I hide the text opened while clicking on a button by clicking on the same button ? In other words, the same button should show or hide a text when you click on it.
Here's my code that shows a text :
<h3>
<button class="button" onclick="myFunction()" ><img src="infoicon.png" height="30"></button>
<p id="infos"></p>
<script>
function myFunction() {
document.getElementById("infos").innerHTML = "blablabla";
}
</script>
</h3>
Define a variable to save the button state
var clicked = 0;
function myFunction() {
if(clicked == 0 ) {
document.getElementById("infos").innerHTML = "blablabla";
clicked = 1;
} else {
document.getElementById("infos").innerHTML = "";
clicked = 0;
}
}
<h3>
<button class="button" onclick="myFunction()" ><img src="infoicon.png" height="30"></button>
<p id="infos"></p>
</h3>
Try this out, it worked for me:
function showHide() {
var demo = document.getElementById('demo');
if (demo.innerHTML === "") {
demo.innerHTML = "bla";
} else {
demo.innerHTML = "";
}
}
<p id="demo"></p>
<button onclick="showHide()">Show Hide</button>
Quite simple, using jQuery—
$( "#button" ).click(function() {
$('#text-to-toggle').toggle(200);
});

Broken Javascript Code

I'm trying to create a website where three things happen, but I am stuck.
(1) When the button “ADD” button is clicked it will create a new paragraph
and add it to the output. The contents of the paragraph should come from the text area that is below the [ADD] button.
(2) If the “delete” button is pressed I need to delete the first paragraph in the div.
(3) If the user tries to delete when there are no paragraphs, create an “alert" that says:"No Paragraphs to delete".
I got my JS to put each paragraph into the div, but I'm not really sure how to delete it... Any help would be much appreciated.
window.onload = function() {
var button = document.getElementById("add");
button.onclick = insertItem;
}
function insertItem() {
var added = document.getElementById("output");
var textToAdd = document.getElementById("input");
if (textToAdd.value != "") {
var newp = document.createElement("p");
newp.innerHTML = textToAdd.value;
added.appendChild(newp);
}
}
var deletebutton = document.getElementsByTagName("delete");
deletebutton.onclick = deleteItem;
function deleteItem() {
var output = document.getElementById("output");
var pars = output.getElementsByTagName("p");
if (pars.length > 0) {
output.removeChild(pars[0]);
}
}
#output {
border: blue 5px solid;
padding: 10px;
margin-bottom: 10px;
margin-top: 10px;
width: 50%;
}
#output p {
padding: 10px;
border: black 1px dashed;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script>
<script src="task3.js"></script>
</head>
<body>
<h2> TASK 3 - Creating, Appending and Deleting Nodes in the DOM Tree </h2>
<p> Type in text below, click add to add as paragraph. <button id="add"> Add </button> </p>
<textarea id="input" rows="10" cols="60">
</textarea><br>
<button id="delete">Delete Last Paragraph</button>
<br><br>
<h2> Added Paragraphs </h2>
<div id="output">
</div>
</body>
</html>
You're fetching the delete button wrong. You're using getElementsByTagName instead of by id.
When deleting, you will probably delete the first <p> you have in your markup that doesnt belong to your output. To fix this you could simply fetch all children of your output div and remove the first one:
function deleteItem() {
let output = document.getElementById('output')
if (output.hasChildNodes()) {
let outputs = output.childNodes
outputs[0].remove()
}
}

Disable button until a number is reached

So I have a code so when I press a button a number goes up.
This is the html:
<button type="button" class="btn btn-default" onclick="javascript:btnClick()">+1</button>
This is the JavaScript:
function btnClick(){
timesClicked += 1;
document.getElementById('timesClicked').innerHTML = timesClicked;
return true
}
So I have a button that has +1 so when I press it the number goes up
I need a button that is disabled until that number gets to 5 for example then becomes clickable, is that possible? I'm still learning Javascript,
All help is appreciated.
If the button is disabled, a user cannot interact with it.
Try the following
window.onload=function() {
var count =0;
document.getElementById("btn").addEventListener("click", function() {
count++;
if(count === 5) {
this.innerHTML = "5 clicks reached!";
}
});
};
<button id="btn">Click</button>
You could try something like this:
document.getElementById("button").disabled = true;
timesClicked = 0;
function btnClick(){
timesClicked += 1;
document.getElementById('timesClicked').innerHTML = timesClicked;
if(timesClicked > 5){
document.getElementById("button").disabled = false;
}
}
<button type="button" id="button" class="btn btn-default" onclick="btnClick()">+1</button>
[].forEach.call(document.querySelectorAll("[data-click-vote]"), function(btn) {
btn.addEventListener("click", vote);
});
function vote() {
this.innerHTML = this.value=Math.min(++this.value, 5);
}
<button value="0" name="movie1" data-click-vote>+1</button> The Revenant<br>
<button value="0" name="movie2" data-click-vote>+1</button> Dracula<br>
<button value="0" name="movie3" data-click-vote>+1</button> The Usual Suspect<br>
Multiple buttons
Updates simultaneously value and innerHTML
You can submit the values using a <form>
You can achieve your requirement with JS and CSS as in the below solution.
You haven't tagged it with CSS but you might want to look at this as well.
Button is simply a disabled span. Clicks are registered and when the count requirement is satisfied, it springs to life and handles your clicks with the actual handler code. (You can add a handler instead of printing a click count)
window.onload = function() {
var count = 1;
document.getElementById("btn").addEventListener("click", function() {
count++;
this.innerHTML = "+" + count;
if (count >= 5) {
this.className = "btnenabled";
this.innerHTML = "Print Click Count!";
if(count > 5) {
document.getElementById("counter").innerHTML= "Click Count is " + count;
}
}
});
};
.btnenabled {
width:200px;
background-color: blue;
padding: 3px;
border-radius: 3px;
color: white;
font-weight: bold;
display:block;
text-align:center;
}
.btnenabled:hover {
background-color:purple;
}
.btndisabled {
width:200px;
padding: 3px;
border-radius: 3px;
display:block;
text-align:center;
background-color: grey;
color: #F0F0F0;
font-weight: 100;
}
<span id="btn" class="btndisabled"> +1 </span>
<span id="counter"></span>

get text from input and print it in a div in real time html

i'm trying to get the text from an input in my html code and print the value of this input in a div and i want to do this in a real time so
i tried with this javascript function
<input id="fname" onkeyup="getVal()" type="text" name="filter_name" value="Nom" onclick="this.value = '';" onkeydown="this.style.color = '#000000' " style="width:180px;" >
<div id="icard" class="drag" style="left: 0px; top: 0px; width:10%; height:10%;"> item</div>
this is js function :
function getVal()
{
var x=document.getElementById("fname");
x.value=x.value.toUpperCase();
document.getElementById("icard").update("New text");
document.getElementById("icard")=x;
var s =document.getElementById("icard");
s.value=x.value;
}
value attribute is not associated with div. So you have to use innerHTML for div
function getVal() {
var x = document.getElementById("fname");
document.getElementById("icard").innerHTML = x.value.toUpperCase();
}
Check this JSFiddle

Categories