What is going wrong here? - javascript

i made this little script to learn javascript. but i keep getting unexpected token switch..
but hoe do is set switch the corect way??
html:
<p id="new">test<p>
<input id="button" type="submit" name="button" value="enter" />
js:
var switch = true;
if (switch == false){
document.getElementById('button').onclick = function() {
document.getElementById("new").innerHTML = "Mijn Naam!";
var switch = true;
};
} else {
document.getElementById('button').onclick = function() {
document.getElementById("new").innerHTML = "shiva";
var switch = false;
};
}

how about:
<p id="new">test<p>
<input id="button" type="submit" name="button" value="enter" />
var clicked = false;
document.getElementById('button').onclick = function() {
document.getElementById("new").innerHTML = clicked ? "shiva" : "Mijn Naam!";
clicked = !clicked;
};

switch is a reserved word. You should use some variable name else.
By the way, your code is possible to be compressed as follows:
var switchOn = true;
document.getElementById('button').onclick = function() {
document.getElementById("new").innerHTML =
switchOn ? "shiva" :"Mijn Naam!";
switchOn = !switchOn;
}

Related

How can I change paragraph content on button click with if statement?

Trying to display different messages inside the p element for when someone clicks on one of the three buttons. But it only displays the first message (reply) for all the buttons.
Can't see what I have done wrong...
HTML
<div class="options">
<div id="good" class="btn"></div>
<div id="idk" class="btn"></div>
<div id="bad" class="btn"></div>
</div>
JavaScript
let good = document.getElementById("good");
let idk = document.getElementById("idk");
let bad = document.getElementById("bad");
let main = document.querySelector(".main");
let reply;
document.getElementById("good"), document.getElementById("idk"), document.getElementById("bad")].forEach(option => {
option.addEventListener("click", () => {
if (good.clicked = true) {
main.style.display = "block";
reply = "Hey";
} else if (idk.clicked = true) {
main.style.display = "block";
reply = "Well yeah";
} else if (bad.clicked = true) {
main.style.display = "block";
reply = "123";
}
document.getElementById("reply").innerHTML = reply;
});
});
const good = document.getElementById("good");
const idk = document.getElementById("idk");
const bad = document.getElementById("bad");
const main = document.querySelector(".main");
const reply = document.getElementById("reply");
const messageTypes = {
good: 'Hey',
idk: 'Well yeah',
bad: '123 BAD'
};
[good, idk, bad].forEach(option => {
option.addEventListener("click", (e) => {
reply.innerHTML = messageTypes[e.target.id];
});
});
<div class="options">
<button id="good" class="btn">good</button>
<button id="idk" class="btn">idk</button>
<button id="bad" class="btn">bad</button>
</div>
<div class="main"><div>
<div id="reply"></div>
Use const for everything, create a separate message dictionary for every message and just map it against the id. You don't need to use jQuery.
If your real use case is as simple as your example, I would consider maybe using different event listeners with different logic inside them. But if you want to use the same event listener, then you can use event.target.id to know which button was clicked:
[document.getElementById("good"), document.getElementById("idk"), document.getElementById("bad")].forEach(option => {
option.addEventListener("click", (event) => {
switch (event.target.id) {
case "good":
reply = "Hey";
break;
case "idk":
reply = "Well yeah";
break;
case "bad":
reply = "123";
break;
}
main.style.display = "block";
document.getElementById("reply").innerHTML = reply;
});
});
Here you can see it working (note that I removed main.style.display = "block"; in the following example since I don't know what main is in your original code):
[document.getElementById("good"), document.getElementById("idk"), document.getElementById("bad")].forEach(option => {
option.addEventListener("click", (event) => {
switch (event.target.id) {
case "good":
reply = "Hey";
break;
case "idk":
reply = "Well yeah";
break;
case "bad":
reply = "123";
break;
}
document.getElementById("reply").innerHTML = reply;
});
});
<div class="options">
<div id="good" class="btn">good</div>
<div id="idk" class="btn">idk</div>
<div id="bad" class="btn">bad</div>
</div>
<div id="reply"/>
It could be something like that:
let good = document.getElementById("good");
let idk = document.getElementById("idk");
let bad = document.getElementById("bad");
let main = document.querySelector(".main");
let reply;
[good, idk, bad].forEach(option => {
option.addEventListener("click", (e) => {
if (e.target == good) {
main.style.display = "block";
reply = "Hey";
} else if (e.target == idk) {
main.style.display = "block";
reply = "Well yeah";
} else if (e.target == bad) {
main.style.display = "block";
reply = "123";
}
document.getElementById("reply").innerHTML = reply;
});
});
<div class="options">
<div id="good" class="btn">good</div>
<div id="idk" class="btn">idk</div>
<div id="bad" class="btn">bad</div>
</div>
<div class="main"><div>
<div id="reply"></div>
I'd be tempted to use explicit event handlers for each of the buttons rather than a generic handler that then tests all three conditions.
You can reduce the code duplication by using a function to handle the display update of the main element and the setting of reply.
Something like the following shows this in action:
let good = document.getElementById("good");
let idk = document.getElementById("idk");
let bad = document.getElementById("bad");
let main = document.querySelector(".main");
good.addEventListener("click", function(e) {
showMain("Good");
});
idk.addEventListener("click", function(e) {
showMain("Well yeah");
});
bad.addEventListener("click", function(e) {
showMain("123");
});
function showMain(replyText) {
main.style.display = "block";
document.getElementById("reply").innerHTML = replyText;
}
.main {
background-color: red;
display: none;
height: 100px;
width: 100px;
}
<button id="good">Good</button>
<button id="idk">Idk</button>
<button id="bad">Bad</button>
<div class="main"></div>
<div id="reply"></div>
You can instead, do something like this for what you want
In Pure VanillaJS
[document.getElementById("good"), document.getElementById("idk"), document.getElementById("bad")].forEach(option => {
option.addEventListener("click", (event) => {
if (event.target.id == "good") {
main.style.display = "block";
reply = "Hey";
} else if (event.target.id == "idk") {
main.style.display = "block";
reply = "Well yeah";
} else if (event.target.id == "bad") {
main.style.display = "block";
reply = "123";
}
document.getElementById("reply").innerHTML = reply;
});
});
= is used for assignments however == is used to check equality of two strings in javascript
[] ...addEventListener("click", (e) => {
if (good.id == e.target.id) {
main.style.display = "block";
reply = "Hey";
}
// and so on
document.getElementById("reply").innerHTML = reply;
});
var btn1=document.getElementById('btn1')
var btn2=document.getElementById('btn2')
var btn3=document.getElementById('btn3')
// jquery way
$('.btn').on("click",function(e){
$("#msg").html(e.target.id+" clicked");
})
// javascript way
var classname = document.getElementsByClassName("btn");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener("click", function(e){
document.getElementById('msg').innerHTML =e.target.id+' clicked';
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<input type="button" id="btn1" class="btn" value="button 1">
<input type="button" id="btn2" class="btn" value="button 2">
<input type="button" id="btn3" class="btn" value="button 3">
<p id="msg"></p>

Javascript if doesn't work

I'm new to javascript and I was making a simple program to reply
but the if statement doesn't work.
Here's my code :
var myInput = document.getElementById('myInput');
var myBtn = document.getElementById('btn');
var value = document.getElementById('myInput').value;
var answer = document.getElementById('answer');
var question = "Hi";
function message() {
if ( value == question) {
answer.innerHTML = "Hi, how can i help you?";
} else {
answer.innerHTML = "Hi ...";
}
}
and here's the html part:
<input id="myInput" type="text">
<button id="myBtn" type="button" onclick="message()">Send!</button>
<p id="answer"></p>
The problem is that you're fetching the value before you have a chance to fill it in.
Instead, fetch it inside the message function.
var myInput = document.getElementById('myInput');
var myBtn = document.getElementById('btn');
var answer = document.getElementById('answer');
var question = "Hi";
function message() {
var value = document.getElementById('myInput').value;
if (value == question) {
answer.innerHTML = "Hi, how can i help you?";
} else {
answer.innerHTML = "Hi ...";
}
}
<input id="myInput" type="text">
<button id="myBtn" type="button" onclick="message()">Send!</button>
<p id="answer"></p>
Place your var value = document.getElementById('myInput').value; inside the button click function
DEMO
var myInput = document.getElementById('myInput');
var myBtn = document.getElementById('btn');
var answer = document.getElementById('answer');
var question = "Hi";
function message() {
var value = document.getElementById('myInput').value;
console.log(value);
console.log(question);
if (value === question) {
answer.innerHTML = "Hi, how can i help you?";
} else {
answer.innerHTML = "Hi ...";
}
}
<input id="myInput" type="text">
<button id="myBtn" type="button" onclick="message()">Send!</button>
<p id="answer"></p>

Count on click button1 and recount if on click button2

I have two buttons and a counter, I have to reset counter every time I change the button. I don't know how to reset the counter.
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
clickCount();
count=0;
}
button2.onclick = function(){
clickCount();
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
Pass a parameter to your clickCount function with the button name, and check if it has changed.
var count = 0;
var lastButtonClicked = "";
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(buttonName){
if (buttonName === lastButtonClicked)
{
count++;
}
else
{
count = 1;
lastButtonClicked = buttonName;
}
display.innerHTML = count;
}
button1.onclick = function(){
clickCount("1");
}
button2.onclick = function(){
clickCount("2");
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
Just add the extra parameter that determines which button the counter is from.
var isFirstButton = true;
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
if (!isFirstButton){
count = 0;
}
isFirstButton = true;
clickCount();
}
button2.onclick = function(){
if (isFirstButton){
count = 0;
}
isFirstButton = false;
clickCount();
}
I updated your original code, added a active button variable which is chosen from the event target, this way, it doesn't matter how many buttons you want to count, they will all be unique, and you don't need a variable for each one.
This is similar to [stephen.vakil] post, however with this code, you do not need to name the buttons, just use the DOM and event target to define the uniqueness.
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
var activeTarget; // which target are we counting
function clickCount(e){
var e = e || window.event; // IE or other browser event
var target = e.target || e.srcElement; // target from different browsers
if(target != activeTarget) { // Is this the current target?
count = 0; // No, reset counter
activeTarget = target; // and make it the active target
}
count++; // No matter which target, incr counter
display.innerHTML = count; // and display result
}
button1.onclick = function(e) { // don't forget the event arg
clickCount(e); // and pass it to the count function
}
button2.onclick = function(e) { // same as above
clickCount(e);
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
The reference for the source event target onclick calling object

How to change button text on click using JavaScript?

Only started JS a couple of days ago, and I'm already having some troubles getting a toggle to work. I want the button to toggle between on and off when clicked.
function click() {
var change = document.getElementById("toggle");
if (change.innerHTML == "on"); {
change.innerHTML = "off";
} else {
change.innerHTML = "on";
}
}
<button type="button" id="toggle" onClick="click()">on</button>
Is this how I should go about it?
try this
<!DOCTYPE html>
<html>
<body>
<button id="toggle" onclick="myFunction()">on</button>
<script>
function myFunction() {
var change = document.getElementById("toggle");
if (change.innerHTML == "on")
{
change.innerHTML = "off";
}
else {
change.innerHTML = "on";
}
}
</script>
</body>
</html>
define your function to be unique as always
and not make use of the javascript function/reserve words
just a recommendation/suggestion
Your having mistake in the if statement,there is no semicolon after if statement
write the code as like below
<button name="toggle" id="toggle" onclick="myFunction()">on</button>
<script>
function myFunction() {
var change = document.getElementById("toggle");
if (change.innerHTML == "on")
{
change.innerHTML = "off";
}
else {
change.innerHTML = "on";
}
}
</script>
You can do this:
<button type = "button" id= "toggle" onClick = "click()">on</button>
function click()
{
var change = document.getElementById("toggle");
if (change.value == "on")
{
change.value = "off";
}
else
{
change.value = "on";
}
}
or by doing this:
function click()
{
if (this.value=="on")
{
this.value = "off";
}
else
{
this.value = "on";
}
}
It will work for you
function myFunction()
{
var change = document.getElementById("toggle");
if (change.value=="off") change.value = "on";
else change.value = "off";
}
for button
<input type="button" value="on" id="toggle" onclick="myFunction()">

Check,reset buttons active after all inputs were completed

how can i make check and reset buttons active after 6 inputs were completed? I have tryed:
if($('.input') == ""){
checkBtn.disabled = true;
resetBtn.disabled = true;
}
else{
checkBtn.disabled = false;
resetBtn.disabled = false;
}
EDIT 2 with fiddle : http://jsfiddle.net/usPMd/88/
Edit : Your Jsfiddle return error 404... So I developed a basic example (it is not perfect).
Jsfiddle
Javascript solution :
<body>
<form>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input id="send" type="submit" disabled/>
<input id="reset" type="reset" disabled/>
</form>
<script type="text/javascript">
var checkBtn = document.getElementById("send");
var resetBtn = document.getElementById("reset");
var inputTag, lengthInputTag, nbCompleted;
function forEach( a, fn ) {
return [].forEach.call(a, fn);
};
function checkInput(){
inputTag = document.getElementsByTagName("input");
lengthInputTag = inputTag.length;
nbCompleted = 0;
console.log(inputTag);
forEach(inputTag, function(el) {
if(el.value != ""){
nbCompleted++;
}
});
if(nbCompleted < 6){
checkBtn.disabled = true;
resetBtn.disabled = true;
}else{
checkBtn.disabled = false;
resetBtn.disabled = false;
}
};
</script>
</body>
if($('.input').length == 6){
checkBtn.disabled = false;
resetBtn.disabled = false;
}else{
checkBtn.disabled = true;
resetBtn.disabled = true;
}
So, use length then:
if($('.input').length == 7){ //after 6 is 7th input
checkBtn.disabled = true;
resetBtn.disabled = true;
}
And also there might be a typo .input should be input but not 100% sure because this might also be class.
Ok, Here you go:
Workign demo: JSFiddle
HTML (partial):
<button id="validateButton" class="validateButton" type="button" disabled="disabled">Check</button>
<button id="resetButton" class="resetButton" type="button" disabled="disabled">Reset</button>
JS:
$(document).on('change blur', '.input', function(){
var count = 0;
$('.input').each(function(){
var elem_v = $.trim ( $(this).val() );
if (elem_v != "") {
count++;
}
})
$('button').prop('disabled', true);
if (count===6){
$('button').prop('disabled', false);
}
});

Categories

Resources