this is a noob question:
I'm defining a button in HTML like this:
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>
To avoid showing too many buttons I'd like the button to toggle between
value="Select good points"
and
value="Select bad points
So in javascript i'm using
$(".btn-change").on("click", function() {
alert("you pressed the " + nextMark + " button");
switch(nextMark) {
case "bad":
nextMark = "good"
document.getelementsbyclassname("btn-change").value="Select good points";
break;
case 'good':
nextMark = "bad"
$("btn-change").value = "Select bad points";
break;
}
}
The nextMark var changes the colour of marks placed on a leaflet map depending on the value of the button.
The alert shows the case structure is working but the button value isn't changing - what is the correct way of doing this?
jsfiddle right here
To assign a value to the input using JQuery you need to use .val() and not .value
var nextMark = "good";
$(".btn-change").on("click", function() {
switch (nextMark) {
case "bad":
nextMark = "good";
$(".btn-change").val("Select good points");
break;
case 'good':
nextMark = "bad";
$(".btn-change").val("Select bad points");
break;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>
You need to specify index to document.getElementsByClassName("btn-change")[0].value = as 0
var nextMark = "good";
$(function(){
$(".btn-change").on("click", function() {
alert("you pressed the " + nextMark + " button");
switch(nextMark) {
case "bad":
nextMark = "good"
document.getElementsByClassName("btn-change")[0].value = "Select good points";
break;
case 'good':
nextMark = "bad"
document.getElementsByClassName("btn-change")[0].value = "Select bad points";
break;
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>
First, you're missing an ending ); to close of the … .on("click" ….
If you are using jQuery, you need to remember to include that first (at the top in <head>), then you should define the JavaScript sheet later. Common practice is at the end, right before the </body> tag.
<script type="text/javascript" src="js.js"></script>
</body>
Next, for the alert, nextMark is not defined.
You can do that with this. when using jQuery, you should keep to it, so use $(this).
Put this inside the function to define nextMark:
var nextMark = $(this);
Once that is done, you need to get the value of it, unless it will say you pressed the [object Object] button. You do that by adding .val() at the end of the target with jQuery; so nextMark.val() inside the alert.
Now to make it switch, you could use a simple if-else statement to switch between the two with:
if (nextMark.val() == "Select good points") {
nextMark.val("Select bad points");
} else {
nextMark.val("Select good points");
}
If you want to use switch, then at least to make it work you need to give it what case it is. What goes inside the (…) of the switch is the case it will use to check.
If I put switch(x) and define x as var x = 1 or var x = "one, we will use this to decide which case to use:
case 1: or case "one": will be executed.
var x = 1;
var y = "one";
switch(y) {
case 1:
// "y" is not 1.
break;
case "one":
// "y" is "one", so this will be exectuted.
break;
}
Therefore, we need to define when the button is "good" or "bad". You could do this by using the literal value, like:
var myMark = $(this).val();
switch(myMark) {
case "Select bad points":
$(this).val("Select good points");
break;
case 'Select good points':
$(this).val("Select bad points");
break;
}
$(".btn-change").on("click", function() {
var nextMark = $(this);
alert("you pressed the " + nextMark.val() + " button");
/* Optional method: */
// if (nextMark.val() == "Select good points") {
// nextMark.val("Select bad points");
// } else {
// nextMark.val("Select good points");
// }
var myMark = $(this).val(); /* or var myMark = nextMark.val(); */
switch(myMark) {
case "Select bad points":
$(this).val("Select good points");
break;
case 'Select good points':
$(this).val("Select bad points");
break;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- jQuery included in this example to make it work -->
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>
Related
I'm a beginner at JavaScript. I'm sorry if I cannot explain clearly what I need.
I am trying to design a page with some questions. The answers must be typed in a textbox.
I am using a Switch Statement to generate different comments to all acceptable answers.
As for answers that are not accepted, I would like to have more than the default message.
For example, if the user types an unaccepted answer for the first time, a message will show up, like "That is not an acceptable answer". On the user's second unaccepted answer a different message would show up, like "Please try again"... And so on for about five times, and then it would loop back to the first default message.
I just don't know how to make that happen...
This is what I have so far:
function myFunction() {
var text;
var colors = document.getElementById("myInput").value;
switch (colors) {
case "White":
text = "White is a nice color.";
break;
case "Blue":
text = "I also like blue. It reminds me of the ocean.";
break;
case "Red":
text = "Red is also nice.";
break;
default:
text = "That is not an acceptable answer";
}
document.getElementById("comment").innerHTML = text;
}
<p>What is your favorite color from the USA flag?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>
You need to have an array for the number of messages, the user needs to get when they have sent an answer.
var count = 0;
var messages = ["That is not an acceptable answer.", "Please try again!", "Still wrong.", "I don't understand.", "Consider visiting the 'help page' before moving on."];
Based on that count, show the message in the default case.
default:
text = messages[count%messages.length];
count++;
Full Working Snippet
var count = 0;
var messages = ["That is not an acceptable answer.", "Please try again!", "Still wrong.", "I don't understand.", "Consider visiting the 'help page' before moving on."];
function myFunction() {
var text;
var colors = document.getElementById("myInput").value;
switch (colors) {
case "White":
text = "White is a nice color.";
break;
case "Blue":
text = "I also like blue. It reminds me of the ocean.";
break;
case "Red":
text = "Red is also nice.";
break;
default:
text = messages[count%messages.length];
count++;
}
document.getElementById("comment").innerHTML = text;
}
<p>What is your favorite color from the USA flag?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>
var counter = 0;
function myFunction() {
var text;
var colors = document.getElementById("myInput").value;
switch(colors) {
case "White":
text = "White is a nice color.";
break;
case "Blue":
text = "I also like blue. It reminds me of the ocean.";
break;
case "Red":
text = "Red is also nice.";
break;
default:
text = getText(counter++);
}
counter = counter > 5 ? 0 : counter;
document.getElementById("comment").innerHTML = text;
}
function getText(counter) {
switch(counter):
case 1:
return "some text";
case 2:
return "some text";
...
}
I am creating a Meteor app that provides a wizard-like experience, moving from one template to the next with each press of the "Next" button. For the most part, it's working as designed.
On one page, however, where I hide several "columns" of an HtmlTable until the user selects the "Add another Date" button, attempting to "add" (unhide) a column by selecting that button sends me back to "page 1" (the first template). This is the event that causes the page/template to disappear and returns the app to the first template:
Template.postTravelWizard.events({
'click #addDate': function(event){
var nextD8 = Session.get('nextDate');
nextD8 = ++nextD8;
Session.set('nextDate', nextD8);
if (nextD8 == 2) {
$("#date2").removeClass("hide");
$("#airfare2").removeClass("hide");
$("#pcm2").removeClass("hide");
$("#reimbursemlg2").removeClass("hide");
$("#rcei2").removeClass("hide");
$("#ot2").removeClass("hide");
$("#parktolls2").removeClass("hide");
$("#confreg2").removeClass("hide");
$("#lodging2").removeClass("hide");
$("#mealsandI2").removeClass("hide");
$("#foreignanddomestic2").removeClass("hide");
$("#miscandenter2").removeClass("hide");
$("#totals2").removeClass("hide");
}
}
}); // Template.postTravelWizard.events
Why would it do that?
For full disclosure, here is the pertinent HTML and JavaScript, and the pertinent CSS:
HTML:
<div class="container">
{{> postTravelWizard}}
</div>
</body>
<template name="postTravelWizard">
{{> Template.dynamic template=getStepTemplate}}
<input type="submit" value="Next" class="button">
</template>
. . .
<template name="tblExpenseDescription">
<button type="button" name="addDate" id="addDate">Add another Date</button>
<table class="maintable" name="tblExpDesc" id="tblExpDesc" border="1">
<tr>
<td class="centertextnowrap"><strong>Description of Expense</strong></td>
<td class="centertext"><label>Date 1: </label><input type="date" id="date1" name="date1"/></td>
<td class="centertext hide"><label>Date 2: </label><input type="date" id="date2" name="date2"/></td>
. . .
JavaScript (all of it):
if (Meteor.isClient) {
// stepNum starts at 1
Session.setDefault('stepNum', 1);
Session.setDefault('nextDate', 1);
Template.postTravelWizard.helpers({
getStepTemplate: function () {
var step = Session.get('stepNum');
switch (step) {
case 4:
return 'tblExpenseDescription'
break;
case 3:
return 'tblPayments'
break;
case 2:
return 'tblTravelerInfo2';
break;
default:
return 'tblTravelerInfo'
break;
}
}
}); // Template.postTravelWizard.helpers
Template.postTravelWizard.events({
'click [type=submit]': function (e, t) {
e.preventDefault();
//save something...
var step = Session.get('stepNum'),
step = (step) < 4 ? ++step : 1;
Session.set('stepNum', step);
if ($('#visitor').is(':checked')) {
console.log('visitor is checked');
var visaselection = $('select[name="selvisatype"]').val()
console.log('visaselection is ' + visaselection);
// When this is working (the first two return "visaselection is undefined" and the last one returns simply
// "visaselection is "), do something similar for ucemployee (input type=radio) and selectcampus (select element)
}
},
'change .payments' : function(event){
var paymentTot = $('#paymenttotal').val();
paymentTot = parseInt(paymentTot) || 0;
var targetVal = $(event.target).val();
targetVal = parseInt(targetVal);
paymentTot = paymentTot + targetVal;
$('#paymenttotal').val(paymentTot);
},
'click #addDate': function(event){
var nextD8 = Session.get('nextDate');
nextD8 = ++nextD8;
Session.set('nextDate', nextD8);
if (nextD8 == 2) {
$("#date2").removeClass("hide");
$("#airfare2").removeClass("hide");
$("#pcm2").removeClass("hide");
$("#reimbursemlg2").removeClass("hide");
$("#rcei2").removeClass("hide");
$("#ot2").removeClass("hide");
$("#parktolls2").removeClass("hide");
$("#confreg2").removeClass("hide");
$("#lodging2").removeClass("hide");
$("#mealsandI2").removeClass("hide");
$("#foreignanddomestic2").removeClass("hide");
$("#miscandenter2").removeClass("hide");
$("#totals2").removeClass("hide");
}
}
}); // Template.postTravelWizard.events
} // if (Meteor.isClient)
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
CSS:
.hide {
visibility: hidden;
display: none;
}
UPDATE
Stepping through my code when nextD8 == 2, it seems to remove the "hide" class where it should, but after stepping through my code, it goes to here:
return Template._withTemplateInstanceFunc(tmplInstanceFunc, function ()
{
return v.apply(data, args);
});
...and then here:
Template._currentTemplateInstanceFunc = oldTmplInstanceFunc;
(not my code, but rather template.js)
UPDATE
For some reason, if I change the input of type submit to a button, the wrap-around from the last template to the first no longer happens when I select "Add Another Date" on the last template (good!).
However, it still does not make visible the "column". Do I need to call "invalidate" or some such to refresh the page?
Ok so I'm kind of new in HTML/javascript, but I'm working on a project, which is a text-based game, basically, I want to have a function, which takes an array of text, print the first one in a text zone, and wait until the "ok" button in pressed before printing the next string of the array.this function is in the middle of a bunch of other ones.
Here is my code at the moment:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Retro-Fighting</title>
</head>
<body>
<br><br><br>
<input id="hpPlayer" type="text" value="" size="40" readonly>
<input id="hpBoss" type="text" value="" size="40" readonly>
<div id="sound_element"></div>
<script>
var player={
//Bunch of characteristics
};
var boss={
//Bunch of characteristics
};
var playerTurn=function()
{
var action =prompt("Do you want to : ATTACK , use MAGIC , or drink a POTION?").toLowerCase();
switch(action)
{
case 'attack':
var rand=10+(player.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(player.attack+rand-(boss.defense/2));
alert("You hit "+boss.name+" and deal "+damage+" damage points!" );
boss.hp-=damage;
if(boss.hp<0){boss.hp=0;}
showHp()
break;
case 'magic':
var rand=10+(player.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(player.attackM+rand-(boss.defenseM/2));
alert("You use "+player.magicName1+" on "+boss.name+" and deal "+damage+" damage points!" );
boss.hp-=damage;
if(boss.hp<0){boss.hp=0;}
showHp()
break;
case 'potion':
if(player.potion)
{
var heal = player.luck-Math.floor(Math.random()*20+1);
alert("You drink a potion and restore "+heal+" HP");
player.potion--
player.hp+=heal;
if(player.hp>player.hpMax){player.hp=player.hpMax;}
}
else {
alert("You don't have any potions left!")
playerTurn();
}
showHp()
break;
default:
confirm("You can't do that!");
playerTurn();
}
};
var bossTurn=function()
{
if(Math.floor(Math.random()+0.5))
{
var rand=10+(boss.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(boss.attackM+rand-(player.defenseM/2));
alert(boss.name+" use "+boss.magicName+" and deal "+damage+" damage points!" );
player.hp-=damage;
if(player.hp<0){player.hp=0;}
}
else
{
var rand=10+(boss.luck-50)-Math.floor(Math.random() *20 + 1);
var damage= Math.floor(boss.attack+rand-(player.defense/2));
alert(boss.name+" hit you and deal "+damage+" damage points!" );
player.hp-=damage;
if(player.hp<0){player.hp=0;}
}
showHp()
};
var startBattle=function()
{
showHp()
while(player.hp>0&&boss.hp>0)
{
if(player.speed>boss.speed)
{
playerTurn();
if(boss.hp)
{bossTurn();}
}
else
{
bossTurn();
if(player.hp)
playerTurn();
}
}
if(player.hp)
{
alert("You won!")
//play victory sound
soundPlay("victory.mp3")
//Go to loot !
alert("Thank you for playing the demo of Retro-fighting!")
}
else
{
alert("You lost...The woodman is now free to destroy the world...")
soundPlay("gameover.mp3")
}
};
var showHp=function()
{
var outputHpPlayer = document.getElementById('hpPlayer')
var outputHpBoss = document.getElementById('hpBoss')
var stringHpPlayer= " "+ player.fName + ": " +player.hp+"/"+player.hpMax+" HP"
outputHpPlayer.value=stringHpPlayer
var stringHpBoss= " "+ boss.name + ": " +boss.hp+"/"+boss.hpMax+" HP"
outputHpBoss.value=stringHpBoss
}
var soundPlay=function(music)
{
document.getElementById("sound_element").innerHTML=
"<embed src="+music+" hidden=true autostart=true loop=false>";
}
confirm("You wake up...");
alert("You're wearing strange green clothes, and a sword is laying down, next to you...");
alert("You pick up the sword...An inscription on the blade say : Link" );
alert("You notice that you are in a dark corridor, a strange woodman is looking at you");
alert("The woodman is attacking you!");
startBattle();
</script>
</body>
</html>
Basically, I just want to get rid of the pop-up showing with the alert() command, while still waiting for a confirmation before showing more text
Since I'm really a beginner in programmation, tell me if my method isn't the right one ect...
Thank you!
PS: English is not my native language, sorry
Is this how your code is originally?
getBoss(//depending on the position o the player)
If so, then there is an error. The comment is extending all the way to the closing parenthesis.
SO this is my code so far:
JS:
<script type="text/javascript">
function Hide(srcField)
{
var x = srcField.getAttribute('name');
var string = new RegExp("hide_ID",'gi');
switch (x)
{
case "1":
var dataRows= document.getElementsByID("obrazovanje");
alert (dataRows[0].innerHTML);
dataRows[0].className.replace('',string);
break;
case "2":
var dataRows= document.getElementsByID("rad_iskustvo");
dataRows[0].className.replace('',string);
break;
case "3":
var dataRows= document.getElementsByID("strani_jezici");
dataRows[0].className.replace('',string);
break;
case "4":
var dataRows= document.getElementsByID("znanja_vjestine");
dataRows[0].className.replace('',string);
break;
case "5":
var dataRows= document.getElementsByID("osobine_interesi");
dataRows[0].className.replace('',string);
break;
}
}
</script>
CSS:
.hide_ID,
{
display:none
}
HTML:
<a name="1"><h4><span name="1" onmouseover="Hide(this)">OBRAZOVANJE:</span></h4></a>
<div ID="obrazovanje">
<ul>
<li>2001.-2005. elektrotehnicar</li>
<li>2009.-2012. racunarstvo</li>
</ul>
</div>
the idea is that i want to hide the div block when i hover over the title that's in h4, but it doesn't seem to hide it... any ideas?
i started using replace but it still didn't work, before that it was just 'dataRows[0].className = "hide_ID"' but that didn't work either.
EDIT1:
so i changed the JS to:
var x = srcField.getAttribute('name');
switch (x)
{
case "1":
var dataRow= document.getElementByID("obrazovanje");
dataRow.className += "hide_ID";
break;
the rest of the JS is also edited, but i didn't feel the need to paste it all)
but still no result.
also tried to change display:none to display:block but now results.
EDIT2:
the JS now looks like this:
function Hide(id)
{
switch (id)
{
case "obrazovanje":
var dataRow= document.getElementByID("obrazovanje");
if ( dataRow.className.indexOf('hide_ID') == -1 ) dataRow.className += ' hide_ID';
else dataRow.className = 'obrazovanje';
break;
...
and the html is:
<a name="1"><h4 class="menu" onmouseover="Hide('obrazovanje')">OBRAZOVANJE:</h4></a>
<div ID="obrazovanje" class="content">
<ul>
<li>2001.-2005. elektrotehnicar</li>
<li>2009.-2012. racunarstvo</li>
</ul>
</div>
and still it wont budge...
FINAL:
this worked:
JS:
<script type="text/javascript">
function Hide(id)
{
switch (id) {
case 1:
document.getElementById("1").className = "hide_ID";
break;
case 2:
document.getElementById("2").className = "hide_ID";
break;
case 3:
document.getElementById("3").className = "hide_ID";
break;
case 4:
document.getElementById("4").className = "hide_ID";
break;
case 5:
document.getElementById("5").className = "hide_ID";
break;
}
}
function Show(id)
{
switch (id) {
case 1:
document.getElementById("1").className = "1";
break;
case 2:
document.getElementById("2").className = "2";
break;
case 3:
document.getElementById("3").className = "3";
break;
case 4:
document.getElementById("4").className = "4";
break;
case 5:
document.getElementById("5").className = "5";
break;
}
}
</script>
HTML:
<a name="1_a"><h4 class="menu" onmouseover="Hide(1)" onmouseout="Show(1)">OBRAZOVANJE:</h4></a>
<div ID="1" class="content">
<ul>
<li>2001.-2005. elektrotehnicar</li>
<li>2009.-2012. racunarstvo</li>
</ul>
</div>
CSS:
.hide_ID
{
display:none
}
thx guys.
Try this one. and change the switch case statement as per your requirement.
switch (x) {
case "1":
document.getElementById("obrazovanje").className += "hide_ID";
break;
case "2":
document.getElementById("rad_iskustvo").className += "hide_ID";
break;
case "3":
document.getElementById("strani_jezici").className += "hide_ID";
break;
case "4":
document.getElementById("znanja_vjestine").className += "hide_ID";
break;
case "5":
document.getElementById("osobine_interesi").className += "hide_ID";
break;
}
with this style
.hide_ID
{
display:none;
}
As I understand, your goal is to hide the associated div tag when the h4 element is hovered over. One way to do this is to use a combination of javascript, css and naming conventions. Consider...
<script type="text/javascript">
function Hide(id) {
var elt = document.getElementById('obrazovanje');
if ( elt.className.indexOf('hide_ID') == -1 ) {
elt.className += ' hide_ID'; // from your css example
} else {
elt.className = '';
}
}
/* In jQuery as mentioned in other answers it's even easier (and offers some other cool ways too (highly recommended if it fits your purposes) */
function jHide(id) {
$('#' + id ).toggleClass('hide_ID');
}
</script>
<h4 class="menu" onmouseover="Hide('obrazovanje');">obrazovanje</h4>
...
<div id="obrazovanje" class="content">
</div>
instead of replacing className with a reg exp try appending new class to className string.
Also getElementById() returns single html instance. And also id attribute must be unique for the entire document.
var dataRows= document.getElementById("obrazovanje");
dataRows.className += " hide_ID"
if you can use jQuery, just use $("#divname").addClass("hide_ID");
I am new to Dojo and working with someone else's code. Currently, this function looks to see the value of a dropdown box. Based on that value, it adds another form box, on the fly, for a user to fill out. In all the examples I have, I've only seen the function create one added form box. In a particular case, though, I'd like to add a second row with another form box. I thought maybe repeating the line twice would do the trick, but it doesn't. Any thoughts how to do this? Thanks in advance...
Switch Statement:
if (form_row != null)
dojo.destroy(form_row);
//Add the correct new field to the form.
switch (inquiry.selectedIndex) {
case place_order:
html = this.create_form_row(id, "Account Number");
break;
case order_status:
html = this.create_form_row(id, "Order Number");
break;
case telalert_signup:
html = this.create_form_row(id, "Account Number");
break;
case invoice_questions:
html = this.create_form_row(id, "Invoice Number");
break;
case new_option:
html = this.create_form_row(id, "Invoice Number");
(WANT TO CREATE A SECOND ROW HERE!)
break;
default:
}
Function being called:
create_form_row: function(id, label) {
//Container
var a = dojo.create("div", { id: id, className: "question", style: "padding-top:4px;" });
//Label
var b = dojo.create("div", { className: "label", innerHTML: label, style: "margin-top:8px;" }, a);
//Field
var c = dojo.create("div", { className: "field" });
var d = dojo.create("span", { className: "full_number_span span" });
var e = dojo.create("input", { type: "text", className: "textbox acct_num", name: label }, d);
dojo.place(d, c);
dojo.place(c, a);
return a;
}
If you tried
case new_option:
html = this.create_form_row(id, "Invoice Number");
html = this.create_form_row(id, "SOMETHING ELSE");
break;
it wouldn't work because you would just overwrite the html variable and throw away the first one.
You can either change stuff so that html is supposed to be a list of nodes or you can try wrapping your two form nodes inside a single one
var html = dojo.create('div');
dojo.place(this.create_form_row(...), html);
dojo.place(this.create_form_row(...), html);