I have a function that I need to call from html. However, the way I have the call at the moment, it is causing typeError. Can someone show me how run this function: splitboxes(); in my html markup.
The function is declared earlier and works if I run just 'splitboxes', but need to call it as a function.
Thank you
$("html").append("<div id='dialog-success' />");
var dialogSuccess = $("#dialog-success");
dialogSuccess.html('<br />Here the details of your submitted intake ' +
'<br /><b><font color="green">' + depts + '</font></b><br />' + splitboxes(); +
' This entry was successfully submitted to the database.<br />Thank you.');
You have syntax error:
...+ splitboxes(); + ...
to
...+ splitboxes() + ...
Please use IDE to do your coding. It saves you aloooooot of headache :)
$("html").prepend("<div id='dialog-success' />");
var dialogSuccess = $("#dialog-success");
dialogSuccess.html('<br />Here the details of your submitted intake <br /><b><font color="green">depts</font></b><br />' + splitboxes()+' This entry was successfully submitted to the database.<br />Thank you.');
function splitboxes(){
return "<i>output from splitboxes() function</i>";
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
</body>
</html>
just remove ; from + splitboxes(); + here is the code and output
Related
I'm trying to finish my final project for my introductory web development course (I'm very new to javascript and html), which is a simple Mad Libs project. I've been running into problems all day with trying to get it to work, and I think I've largely eradicated most of the bugs. I've really hit a roadblock though, with the button I'm using that is supposed to load in the results and call the function that builds the story using an event listener in the javascript file. When I run my program, the button doesn't do a thing. I checked the Google Chrome developer console, and I'm not getting any error messages or anything, so I have no clue what I'm doing wrong.
Here's my javascript file (named mad_libs_1.js):
var story = document.querySelector("#story");
var adjective1 = document.querySelector("#adjective1");
var verbEndingInED = document.querySelector("#verbEndingInED");
var nounPlural1 = document.querySelector("#nounPlural1");
var liquid = document.querySelector("#liquid");
var nounPlural2 = document.querySelector("#nounPlural2");
var famousPerson = document.querySelector("#famousPerson");
var place = document.querySelector("#place");
var occupation = document.querySelector("#occupation");
var noun1 = document.querySelector("#noun1");
var nationality = document.querySelector("#nationality");
var femaleCelebrity = document.querySelector("#femaleCelebrity");
var noun2 = document.querySelector("#noun2");
var femaleFriend = document.querySelector("#femaleFriend");
var nounPlural3 = document.querySelector("#nounPlural3");
var number = document.querySelector("#number");
var adjective2 = document.querySelector("#adjective2");
//event listener for the button
var finished = document.querySelector("#finished");
if(finished){
finished.addEventListener("click", createStory, false);
}
function createStory(){
console.log("createStory HAS BEEN CALLED");
var finalStory = "";
finalStory += "I enjoy long, " + adjective1.bold();
finalStory += " walks on the beach, getting " + verbEndingInED.bold();
finalStory += " in the rain and serendipitous encounters with " + nounPlural1.bold();
finalStory += ". I really like piña coladas mixed with " + liquid.bold();
finalStory += ", and romantic, candle-lit " + nounPlural2.bold();
finalStory += ". I am well-read from Dr. Seuss to " + famousPerson.bold();
finalStory += ". I travel frequently, especially to " + place.bold();
finalStory += ", when I am not busy with work. (I am a " + occupation.bold();
finalStory += ".) I am looking for " + noun.bold();
finalStory += " and beauty in the form of a " + nationality.bold();
finalStory += " goddess. She should have the physique of " + femaleCelebrity.bold();
finalStory += " and the " + noun2.bold();
finalStory += " of " + femaleFriend.bold();
finalStory += ". I would prefer if she knew how to cook, clean, and wash my " + nounPlural3.bold();
finalStory += ". I know I’m not very attractive in my picture, but it was taken " + number.bold();
finalStory += " days ago, and I have since become more " + adjective2.bold() + ".";
story.innerHTML = finalStory;
console.log(story + " IS THE STORY");
}
and here's my html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<title>Mad Libs 1</title>
<script type="text/javascript" src="mad_libs_1.js"></script>
</head>
<body lang="en-US">
<div class="container-fluid">
<h1>Mad Libs 1</h1>
</div>
<div class="container-fluid">
<ul>
<li>Adjective: <input type="text" name="adjective1" id="adjective1"><br>
<li>Verb Ending in "ED": <input type="text" name="verbEndingInED" id="verbEndingInED"><br>
<li>Noun (Plural): <input type="text" name="nounPlural1" id="nounPlural1"><br>
<li>Liquid: <input type="text" name="liquid" id="liquid"><br>
<li>Noun (Plural): <input type="text" name="nounPlural" id="nounPlural2"><br>
<li>Famous Person: <input type="text" name="famousPerson" id="famousPerson"><br>
<li>Place: <input type="text" name="place" id="place"><br>
<li>Occupation: <input type="text" name="occupation" id="occupation"><br>
<li>Noun: <input type="text" name="noun1" id="noun1"><br>
<li>Nationality: <input type="text" name="nationaltiy" id="nationality"><br>
<li>Female Celebrity: <input type="text" name="femaleCelebrity" id="femaleCelebrity"><br>
<li>Noun: <input type="text" name="noun2" id="noun2"><br>
<li>Female Friend: <input type="text" name="femaleFriend" id="femaleFriend"><br>
<li>Noun (Plural): <input type="text" name="nounPlural3" id="nounPlural3"><br>
<li>Number: <input type="text" name="number" id="number"><br>
<li>Adjective: <input type="text" name="adjective2" id="adjective2"><br>
<button id="finished">I'M FINISHED!</button>
</ul>
</div>
<div id="story"></div>
</body>
</html>
I know that my code practices are probably sloppy--I'm just trying to get it to work before I polish it up. Also, I have to use regular javascript and no jquery. I appreciate any help I get with this because I've been working in vain for hours and hours trying to figure out what's wrong.
Further to #Jaromanda X's suggestion, try wrapping your code in a function, and then assigning that function as the window.onload event handler.
This way your code won't run until the HTML document has been loaded. Otherwise your code might run before the document has loaded and there won't be any HTML elements to operate on.
function runOnLoad() {
// all your code in here
}
// assign your function as the handler for the onload event
window.onload = runOnLoad;
You might be interested to read this question for a bit more information about how to run code after the page has loaded, and a few different ways to do it.
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
You have errors in your code. bold() is not a function if you want to use bold text you can use <strong> tag.
Also if you want to get value from textbox you need to use value property.
function createStory() {
console.log("createStory HAS BEEN CALLED");
var finalStory = "";
finalStory += "I enjoy long, <strong>" + adjective1.value+ "</strong>";
story.innerHTML = finalStory;
console.log(story + " IS THE STORY");
}
I have corrected for the first textbox you can follow same for the rest.
You could use the addEventListener:
var div = document.getElementById('div');
function blah(e) {
}
div.addEventListener('click', blah);u
This would make a click event in the javascript. The e parameter is needed for this though because it calls for the event.
Hey Guys im new at coding and working right now on a Twitch Viewer. (FreeCodeCamp)
Im able to get information from the JSON file and show it through my html code.
But my problem is that i cant get the names from my "gamer" array.
Why is the for loop not working in the json function?
Thank you very much for your help!
var gamer = ["OgamingSC2","ESL_SC2"];
for(i=0;i<(2);i++){
$.getJSON('https://api.twitch.tv/kraken/streams/'+gamer[i]+'/?callback=?', function(json) {
$('.list').append("<b>Name: " + gamer[i] + "</b><br>");
var logo = json.stream.channel.logo;
$('.list').append("Game: " + json.stream.channel.game + "<br>");
$('.list').append("Status: " + json.stream.channel.status + "<br>");
$('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
console.log(json);
});}
img {
width: 5em;
border-radius: 10px;
}
<head><script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> </head>
<body>
<b>Twitch.tv JSON API</b> </br>
<div class="list"></div>
</body>
What happens here is the $.getJson is an asynchronous call, which means that it will execute only after all of the sync operations are executed. So, the for loop runs twice, and two getJSON callback functions are added to the function stack.
Now as Javascript has lexical or functional scope, the variable i lives on in the global scope as 2 (as the final i++ also has executed).
Next, the callback functions are executed one by one off of the function stack. But alas, your variable i is now 2! Now the callback functions would only see gamer[2] which doesn't exist and this throws an undefined
If you add a console.log(i) to your $.getJSON, you'll see that it outputs only 2 two times.
Why don't you try this:
var gamer = ["OgamingSC2","ESL_SC2"];
gamer.map(function(gamer) {
loopIt(gamer);
});
function loopIt(gamer) {
$.getJSON('https://api.twitch.tv/kraken/streams/'+gamer+'/?callback=?', function(json) {
$('.list').append("<b>Name: " + gamer + "</b><br>");
var logo = json.stream.channel.logo;
$('.list').append("Game: " + json.stream.channel.game + "<br>");
$('.list').append("Status: " + json.stream.channel.status + "<br>");
$('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head><script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> </head>
<body>
<b>Twitch.tv JSON API</b> </br>
<div class="list"></div>
</body>
i think it json gives nothing because you put callback=?
when you pass ? in call back variable it take value with ? and gives nothing.
so just put callback= .dont give any values and try again. and just alert json variable in function. you will know value is coming or not. i dont found nothing wrong with loop and json link.
For this types of server call in for loop , you can use custom loop.
Like this, https://jsfiddle.net/s8eLhxpx/
var gamer = ["OgamingSC2","ESL_SC2"];
var initCounter = 0;
callServerData()
function callServerData(){
$.getJSON('https://api.twitch.tv/kraken/streams/'+gamer[ initCounter ]+'/?callback=?', function(json) {
$('.list').append("<b>Name: " + gamer[ initCounter ] + "</b><br>");
var logo = json.stream.channel.logo;
$('.list').append("Game: " + json.stream.channel.game + "<br>");
$('.list').append("Status: " + json.stream.channel.status + "<br>");
$('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
console.log(json);
initCounter++
if(initCounter < gamer.length){
callServerData();
}
});
}
I am trying to create code that when you press a button, it will change the value of a variable and replace some text.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="unitts">You have 0 unitts</p>
<script type="text/javascript">
var unitt = 0;
function unittIncrease() {
var unittPrev = unitt;
unitt++;
document.getElementById(unitts).innerHTML.replace("You have " + unittPrev.toString() + " unitts.", "You have " + unitt.toString() + " unitts.");
}
</script>
<button id="unittIncrease" onclick="unittIncrease();">Digitize Unitt</button>
</body>
</html>
When I press the button, nothing happens to the text.
I don't know why this does not work.
Please help me!
EDIT: I am only 11 years old,
please don't throw your wizard
code at me.
maybe you should remove your button system and add a while loop that
automatically add a unit but waits one second with a setInterval
function
I think you should write the js code like this
document.getElementById('unitts').innerHTML = "You have"....
Instead of:
document.getElementById(unitts).innerHTML.replace("...")
Your JavaScript should be (note the unitts wrapped in quotes and the full stop removed):
document.getElementById('unitts').innerHTML = "You have " + unitt + " unitts";
Instead of:
document.getElementById(unitts).innerHTML.replace("You have " + unittPrev.toString() + " unitts.", "You have " + unitt.toString() + " unitts.");
In the latter, it is looking for the non-existent variable unitts instead of the string 'unitts'. Also, you are looking for the text You have x unitts. which cannot be found because in your HTML, it is just You have x unitts without the full stop.
Edit
See this plnkr.
Apart from the issues that the other answer mentions, by calling .replace method on the .innerHTML property of the element, the content of it doesn't change. You should reset the property by using the returned value of the method call:
el.innerHTML = el.innerHTML.replace(...);
Also, as you are trying to increase a number, instead of replacing all the characters, you can just replace the numeric part:
var unitts = document.getElementById('unitts');
function unittIncrease() {
unitts.textContent = unitts.textContent.replace(/\d+/, function(n) {
return +n + 1;
});
}
https://jsfiddle.net/h6odbosg/
I am trying to pass a variable to the onClick function using a previously stored value. I have a database setup that searches for store locations when provided with a ZIP code. For example, the following link is generated using an ajax call after a user searches for a Zip Code. The returned value "WAFHOH3" is the ID that is associated with that particular store:
Generated Link:
<input type="button" onclick="myfunction(WAFHOH1);" value="This Is My Store" data-store-code="WAFHOH3">
Based on this code:
<div class="col-sm-3"><input type="button" onclick="myfunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>
My problem is that if anything other than a number is returned I get a "Uncaught ReferenceError: WAFHOH3 is not defined" console error. When a number is passed like the example below, everything works fine and I get no errors and the application continues to work as expected.
For example (This Works):
Ive tried manually changing the character string to numbers only to isolate any database related issues. My only guess is that there is something in my code that is maybe attempting to verify the input as number.
The full code is below for the ajax call.
Full Code:
function myFunction() {
var searchValue = $('#foobar').val();
if (searchValue.length > 3) {
var acs_action = 'searchCction';
$.ajax({
async: false,
url: mysearchurl.url+'?action='+acs_action+'&term=' + searchValue,
type: 'POST',
data: {
name: searchValue
},
success: function (results) {
var data = $.parseJSON(results);
$('#resContainer').hide();
var html = '';
if (data.length > 0) {
html += '<br/><br/><ul>';
for (var i = 0; i < data.length; i++) {
var item = data[i];
html += '<li>';
html += '<div class="row myclass">';
html += '<div class="col-sm-9">';
html += ' <h3>' + item.label + '</h3>' ;
html += ' <span>' + item.desc + '</span>';
html += '</div>'
html += ' <div class="col-sm-3"><input type="button" onclick="dofunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
html += '</div>';
html += '</li>';
}
html += '</ul><br/><br/><p>This is an example message please email us at admin#admin.com for assistance.';
}
else {
html += '<br/><br/><p>This is an example message, email us at admin#admin.com for assistance.';
}
$('#foo').html(html);
$('#foo').show();
$('.foobar').hide();
}
});
} else {
$('#foo').hide();
}
}
You need to wrap the input item.store_code with quotation marks; otherwise, it tries to treat it as a variable, not a string:
html += '<div class="col-sm-3"><input type="button" onclick="noActivationCodeRegistration(\'' + item.store_code + '\');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
Ideally, you would attach a click handler after giving the buttons a class (such as register):
html += '<div class="col-sm-3"><input type="button" class="register" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
// Later
$('.register').on('click', function() {
var storeCode = $(this).data('storeCode');
noActivationCodeRegistration(storeCode);
});
I may be late, and maybe its an absolute mistake of me, but, i have to add my answer here because i just solved exactly the same situation in about three minutes ago .
I just solved this using the most simple sollution, and the error "Uncaught ReferenceError" from the console is solved, also i have my alert(); passing the variable as i needed.
I also need to include that i did not aproove the sollution gave, about "not using" the alert function, once i searched for the sollution, not for another method for that .
So, as i am using php, and the document is html, i thinked about the apostrophe charactere to the variable, after i had been spectating the element using chrome, first moving the function alert to the parent and child elements, that not solved .
After, also in the specting element, inside chrome F12 i tryed changing the function, including '' (that i passed in php code) into variable inside the alert function as: onclick="alert(variable);" to onclick="alert('variable');" and my alert had worked .
Ok. So, i try everything to insert '' 2 single quotes '' to my variable in php, that seems impossible, even if i change all my code to " and use ' or the oposite .
Then, i decided to try the most obvious and old school method, that is about charactere representation, and i cfound that ' (single quote) is represented by ' in php. Everything inside ->> ' <<-
My php code is like this : onclick="alert(''.$variable.'');"
It will work! (with no Vue), ok ? :)
I have an event which parses a certain string which contains button name and url.
than I assign the data to a button. and add on click event which suppose to open url in a new window. But this on click event doe not work. The window does not show up. If url was wrong it would open a window and prompt a mistake.
But in my case when I click the botton it does not react. Probably something is wrong with on click event here: onclick=\"myWindow = window.open('partArray[1]', '', 'width=300,height=300');\". But I can't understand what.
here is the code
<script>
...
var checkType = partArray[0].split("+");
outPuts = outPuts + " <input type='button' class='WordDocType' name='" + partArray[0] + "' value='" + partArray[0] + "' onclick=\"myWindow = window.open('partArray[1]', '', 'width=300,height=300');\" /> "
document.getElementById("demo").innerHTML=outPuts;
</script>
<body>
...
<div id="demo"></div>
...
</body>
partArray[1] is not evaluated; the browser should still open window with the URL specified as "partArray[1]" but I doubt that is what you want. Try adding double quotes and concatenating it when you build your HTML.
outPuts = outPuts + " <input type='button' class='WordDocType' name='" + partArray[0] + "' value='" + partArray[0] + "' onclick=\"myWindow = window.open('" + partArray[1] + "', '', 'width=300,height=300');\" /> "
If you provide some more context or code it'd be easier to see what might be going on. Are you sure there is not a popup-blocker getting in the way?