I'll rephrase my question
I wrote this code and I don't understand why it doesn't work...
I want to create something that one a person come's to the website to order sandwich he write's one of the options I wrote in the website and then it display's the sandwich he chose and the the ingredients in the sandwich (the ingredients are all the arrays)
I'll add my html code as well, and if someone can write an example for the right code it will be much more helpful to me.
Thanks a lot in advance!
JavaScript code:
var avucado = ["eggs ","avucado ","tommato ","mayonnaise ","pickles ","gamba"];
var eggSalad = ["eggs ","dill ","mayonnaise ","pickles"];
var tuna = ["tuna ","coriander ","pickles ","mayonnaise ","gamba"];
var cheeze = ["yellow cheeze ","mayonnaise ","tommato ","cucumber"];
var sausage =["sausage ","mustard ","mayonnaise ","tommato ","pickles"];
var choice1 = ("you chose:");
var choice2 = ("the ingredients of your sandwich are:")
var food = function(foodName)
{
if (document.getElementById("input").value = avucado) {
document.write(choice1 + " " + 'avucado.'+ "<br /><br />" + " " + choice2 +
" " + avucado + ".");
}else if(document.getElementById("input").value = eggSalad) {
document.write(choice1 + " " + 'egg salad.'+ "<br /><br />" + " " + choice2 +
" " + eggSalad + ".");
}else if(document.getElementById("input").value = tuna) {
document.write(choice1 + " " + 'tuna.'+ "<br /><br />" + " " + choice2 +
" " + tuna + ".");
}else if(document.getElementById("input").value = cheeze) {
document.write(choice1 + " " + 'yellow cheeze.'+ "<br /><br />" + " " + choice2 +
" " + cheeze + ".");
}else if(document.getElementById("input").value = sausage) {
document.write(choice1 + " " + 'tuna.'+ "<br /><br />" + " " + choice2 +
" " + tuna + ".");
}
else(document.getElementById("input".value != avucado,eggSalad,tuna,cheeze,sausage){
document.write("Error, please chose one of the sandwich's on the list");
}
};
HTML code:
<html>
<head>
<title>Hello World!</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="script.js"> </script>
</head>
<body dir="rtl">
<h1> wich sandwich would you like to order? </h1>
<form>
<input type="text" id="input" /><br />
<button type="button" id="button" value="submit" onclick="food()">submit</button><br />
</form>
</body>
</html>
Replace all occurrences of:
document.getElementById("input").value =
With:
document.getElementById("input").value ==
The single "equals" sign (=) is an "Assignment" operator.
The double "equals" sign (==) is an "Comparison" operator.
In your if's, you were assigning the foodstuffs' contents to the input's .value, instead of checking for equality.
To check if the value is in the arrays, you should do something like this:
if(avucado.indexOf(document.getElementById("input").value) !== -1){
So, if the value is in the array avucado, then do what's below the if.
Last, this else statement of yours needs some fixing:
else(document.getElementById("input".value != avucado,eggSalad,tuna,cheeze,sausage){
document.write("Error, please chose one of the sandwich's on the list");
}
Replace that with:
else if(avucado.concat(eggSalad,tuna,cheeze,sausage).indexOf(document.getElementById("input").value) == -1){
document.write("Error, please chose one of the sandwich's on the list");
}
Now, instead of document.write("text"), I'd suggest using DOM manipulation:
In your HTML, add an element like this:
<span id="message"></span>
Then, in your JS:
document.getElementById("message").innerHTML = "text";
Related
I'm trying to GET all players from a list, but the whole GetMapping it's constructed around Player DTO. The data I want to loop is a list of "players" stored into a DTO like this:
{
PLAYERS: [
{ player0 {parameters...} },
{ player1 {parameters...} },
...
]
}
Here is my ajax code in JS:
//GET ALL PLAYERS
function getAllPlayers() {
document.getElementById("erase_repeated_results").innerHTML = ""; //to erase info I don't want to store
document.getElementById("fullInfo").innerHTML = "";
document.getElementById("data").innerHTML = "";
document.getElementById("sameRoles").innerHTML = "";
$.ajax({
type: "GET",
url: "http://localhost:8081/dices/players",
contentType: "application/json",
dataType: "json",
success: function (data) {
for (var j = 0; j < data.length; j++) {
document.getElementById("fullInfo").innerHTML += "Complete info of player " + (j+1) + ": " + "<br />" + "<br />" +
"The ID of this player is: " + data[j].id + "<br />" +
"The name of this player is: " + data[j].name + "<br />" +
"The register date of this player is: " + data[j].registerDate + "<br />" +
"The total amount of dice rolls of this player is: " + data[j].totalDiceRolls + "<br />" +
"The total amount of games won of this player is: " + data[j].gamesWon + "<br />" +
"The success rate of this player is: " + data[j].successRate + "<br />";
console.log(data[j]);
}
},
error: function () {
alert("Something went wrong! Maybe you are entering parameters not related to our Database!");
}
});
}
Below I attached a screenshot so you can see how it is working while I debug it, and you'll see in the scope section what I'm talking about.
How can I enter only in the array parameter of the DTO?
In your data structure, it's the PLAYERS property which is an array. data is an object containing a single property called PLAYERS. So looping through that makes no sense. Just loop through the players array instead:
for (var j = 0; j < data.PLAYERS.length; j++) {
document.getElementById("fullInfo").innerHTML += "Complete info of player " + (j+1) + ": " + "<br />" + "<br />" +
"The ID of this player is: " + data.PLAYERS[j].id + "<br />" +
"The name of this player is: " + data.PLAYERS[j].name + "<br />" +
"The register date of this player is: " + data.PLAYERS[j].registerDate + "<br />" +
"The total amount of dice rolls of this player is: " + data.PLAYERS[j].totalDiceRolls + "<br />" +
"The total amount of games won of this player is: " + data.PLAYERS[j].gamesWon + "<br />" +
"The success rate of this player is: " + data.PLAYERS[j].successRate + "<br />";
console.log(data.PLAYERS[j]);
}
I'm creating a communications generator that will standardise SMS communications regarding critical IT incidents for my company. I've got an IF/ELSE statement that identifies whether an issue is new, updated, or resolved to pull the necessary information together and format it accordingly. As far as I can tell, everything here is fine, however I'm having an issue writing to a text box ('smsToSend') which should allow the user to review before they copy the text across to our sms sender app, as nothing is being output into this box.
function generateSMS(){
var issueTitle = document.getElementById("incidentTitle");
var advisorImpact = document.getElementById("advisorImpact";
var incidentUpdate = document.getElementById("incidentUpdate");
var incidentStatus = document.getElementById("incidentState");
var startTime = document.getElementById("startTime");
var endTime = document.getElementById("endTime");
var incidentPriority = document.getElementById("incidentPriority");
var incidentBrand = "TechTeam";
var systemImpacted = document.getElementById("systemImpacted");
var incidentReference = document.getElementById("incidentReference");
var smsToSend = document.getElementById("smsToSend");
if (incidentStatus != "Closed"){
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT RESOLVED: " + systemImpacted + ": " + incidentUpdate + ": Start: " + startTime + " End: " + endTime + " Reference: " + incidentReference;
}
else{
if (incidentUpdate == "We are investigating this issue"){
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT ISSUE: " + systemImpacted + ": " + issueTitle + ". " + advisorImpact + ": " + incidentReference;
}
else {
smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT UPDATE: " + systemImpacted + ": " + incidentUpdate + ": " + incidentReference;
}
}
}
generateSMS();
alert.getElementById(smsToSend);
Try replacing all assignments to smsToSend like this:
smsToSend = yourValue;
With this:
smsToSend.value = yourValue;
Your problem happens because smsToSend is an instance of an element, rather than a variable linked to the displayed text. To update the element's value, you have to change the value property of the element.
The Right way of setting the value to a text box is
var smsToSend = document.getElementById("smsToSend");
smsToSend.value = "Your value";
I have an issue with the following code.
I am trying to change the content of a variable if a button is clicked and then output the corresponding content as part of a larger output. The output varies depending on if the inner button within the form is clicked.
Can anyone suggest a fix for this code or improvements?
In the output I should see a longer version as the extra block would be appended on to the newly created block and grab new id values generated. Any help would be great.
Here is my code:
<script>
$(document).ready(function() {
var currentID = 1;
$(':button#add').on('click',function() {
currentID++;
var clone = $('#content').clone();
clone.children('.content_title').attr('id', 'title_content-' + currentID);
clone.children('.content_more').attr('id', 'more_content-' + currentID);
clone.attr("id", "content_1");
clone.insertAfter('#content');
if(currentID >= 2) {
document.getElementById("add").style.display = "none";
}
});
});
</script>
</head>
<body>
<div>
<div>
<form action="" method="post">
<h1>Create Code</h1>
<fieldset>
<legend><span class="number"></span>Header</legend>
<label for="name">Title:</label>
<input type = "text" id = "title" />
</fieldset>
<fieldset id = "content">
<legend><span class="number"></span>Content</legend>
<label for="name">Title:</label>
<input class = "content_title" type = "text" id = "title_content" />
<label for="mail">Content:</label>
<input class = "content_more" type = "text" id = "more_content" />
</fieldset>
<input id = "add" type = "button" value = "Add" /> </form>
<button onClick="tryTest()">Code</button>
</div>
<div style = "float:left; width:48%; padding-left:10px;">
<p id="new_block"></p>
</div>
</div>
<script>
function tryTest() {
var quote = '"';
var start = "<pre><div class=" + quote + "newest" + quote + "></pre>";
var title = "title=" + quote + document.getElementById("title").value + quote;
var end = "<pre></div></pre>";
var start_1 = "{{widget type=" + quote + "new_version" + quote;
var title_1 = "title=" + quote + document.getElementById("title_content").value + quote;
var content_1 = "content=" + quote + document.getElementById("more_content").value + quote;
var end_1 = "template=" + quote + "other" + quote + "}}";
var title_2 = "title=" + quote + document.getElementById("title_content-2").value + quote;
var content_2 = "content=" + quote + document.getElementById("more_content-2").value + quote;
var widget = start_1 + "<br />" + title_1 + "<br />" + content_1 + "<br />" + end_1;
var widget_1 = start_1 + "<br />" + title_1 + "<br />" + content_1 + "<br />" + end_1 + start_1 + "<br />" + title_2 + "<br />" + content_2 + "<br />" + end_1;
if(add.clicked == false) {
document.getElementById("new_block").innerHTML = start + "<br />" + title + "<br />" + end + "<br /><br />" widget + "<br /><br />";
} else {
document.getElementById("new_block").innerHTML = start + "<br />" + title + "<br />" + end + "<br /><br />" widget_1 + "<br /><br />"";
}
</script>
This code is a strange mix of jQuery and vanilla JavaScript syntaxes...
But it would work if there was no parse error.
Those error were quite easy to find in a code editor like CodePen, by the way.
if(add.clicked == false) {
document.getElementById("new_block").innerHTML = start + "<br />" + title + "<br />" + end + "<br /><br />" + widget + "<br /><br />";
// Added a missing + sign ---> ---> ---> ---> here -------^
} else {
document.getElementById("new_block").innerHTML = start + "<br />" + title + "<br />" + end + "<br /><br />" + widget_1 + "<br /><br />";
// Added a missing + sign ---> ---> ---> ---> here -------^
}
} // Added this curly bracket to close the tryTest() function.
Just above this code block, is a condition to choose which string to append to new_block.
The if(add.clicked == false) { condition always evaluates to false, because add is not defined. So the property .clicked of undefined, obviously also is undefined...
Then "undefined" == false is false... And makes the else block to always execute.
This condition fixed will avoid the Cannot read property 'value' of null error on "Code" click if the "Add" has not been clicked.
There is a couple ways to determine if the "Add" button has been clicked.
Check if the element title_content-2 exist
Use a boolean "flag" turned to true on "add" click
Adding a class to the "Add" button on click
I will let you think about the solution you would prefer and try it.
Here is your code freed of the mentionned syntax errors in CodePen.
Well i'm afraid that my title doesn't explain it. I'm unable to understand the behavior of variables when they store some values.
i'll try to explain what i'm saying,
My Code
<! DOCTYPE html>
<html>
<head>
<title>Current Date and Time</title>
<style>
p { font: 14px normal arial, verdana, helvetica; }
</style>
<script>
function telltime() {
var out = "";
var now = new Date() ;
out += "<br />Date: " + now.getDate() ;
out += "<br />Month: " + now.getMonth() ;
out += "<br />Year: " + now.getFullYear() ;
out += "<br />Hours: " + now.getHours() ;
out += "<br />Minutes: " + now.getMinutes() ;
out += "<br />Seconds: " + now.getSeconds() ;
document.getElementById("div1").innerHTML = out;
}
</script>
</head>
<body>
The current date and time are: <br/>
<div id="div1"></div>
<script>
telltime() ;
</script>
<input type="button" onclick="location.reload() " value="Refresh" />
</body>
it outputs as below:
but if i change:
out += "<br />Date: " + now.getDate() ;
out += "<br />Month: " + now.getMonth() ;
out += "<br />Year: " + now.getFullYear() ;
out += "<br />Hours: " + now.getHours() ;
out += "<br />Minutes: " + now.getMinutes() ;
out += "<br />Seconds: " + now.getSeconds() ;
with this:
but if i change:
out = "<br />Date: " + now.getDate() ;
out = "<br />Month: " + now.getMonth() ;
out = "<br />Year: " + now.getFullYear() ;
out = "<br />Hours: " + now.getHours() ;
out = "<br />Minutes: " + now.getMinutes() ;
out = "<br />Seconds: " + now.getSeconds() ;
then output would be like this:
I'm quiet unable to understand this behavior. up to my understandings a value stored in a variable will always get overridden if we store a new value in that particular variable, no matters the way to store the value, but in case described above, out stores all the values which get written when script runs. But if we change += with = then out only holds the last value which describe current seconds.
This is because
out += <br />Date: " + now.getDate()
means out = out + "<br />Date: " + now.getDate()
where as
out = "<br />Date: " + now.getDate()
assigns (and overwrites) output.
Update:
I think I now understand where you are getting stuck.
out = out + <br />Date: " + now.getDate() means out gets a new value which is equal to previous value of out + some new value, so is it not supposed to overwrite the previous value?
If you are asking why doesn't the second instance of out also get overwritten, then let me explain:
out = out + "<br />Date: " + now.getDate()
The out after the = is going to be replaced with out's value at the current time and then assigned to out.
function recurring_cb_fn(){
if( $("#recurring_yes").is(":checked") ){
$("div#div_add_date").html("" +
" <fieldset> " +
" <legend> " +
" Select Date of Venue " +
" </legend> " +
" <a href='#' id='add_date_fieldset' onclick='add_date()'>Add another date</a><br /><br /> " +
" <input type='date' id='date_of_venue' name='date_of_venue[]' /> " +
" <div class='add_date_for_venue'></div> " +
" </fieldset> " );
}else if( $("#recurring_no").is(":checked") ){
$("div#div_add_date").html("" +
" <fieldset> " +
" <legend> " +
" Select Date of Venue: " +
" </legend> " +
" <input type='date' id='date_of_venue' name='date_of_venue' /> <br><br>" +
" </fieldset> " );
}
}
function add_date(){
$("div#div_add_date").append("" +
" <fieldset> " +
" <input type='date' id='date_of_venue' name='date_of_venue[]' /> " +
" <a href='' id='remove_date_fieldset' name='remove_date_fieldset'><span class='el el-remove-circle'></span></a> " +
" </fieldset> " );
}
This is the function that I am using to allow a user to add multiple dates. I am using the name to store arrays in PHP, but have given them all the same ID to validate in javascript. The date must be in the future. This is my validation code:
var date_of_venue = $("input#date_of_venue").val();
if( validate_date(date_of_venue) ){
$("span.el").remove();
$("input#date_of_venue").before("<span class='el el-ok'></span>");
}else{
$("span.el").remove();
$("input#date_of_venue").before("Date must be in the future <span class='el el-remove'></span>");
}
And the function to check for date validity:
function validate_date(str) {
var selectedText = str;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
return false;
}else{
alert("Date is ok!");
return true;
}
The form is not checking for validity, and submitting the form anyway.
Thanks!