I'm new to coding and have to make a "madlib" game for class. It just needs to be basic. I need the user to fill in 4 words and replace those words for any random ones I choose in a poem or short story. The problem I'm having it that I need the poem/short story to be in the body of web page after it has been "madlibbed".
I'm really not sure how I can take some JavaScript from the head and insert it into the body. Here's what I have so far and I'll try to be specific in what my thoughts/confusions are. Don't worry if there are specific little errors in the code so far, I can figure that out later.
<!doctype html>
<html>
<meta charset="utf-8">
<title>Mad Lib</title>
<script type="text/javascript">
function myFunction()
{ var noun=prompt(“Type a noun here”);
var noun2=prompt(“Type a noun here”);
var verb=prompt(“Type a verb here”);
var verb2=prompt(“Type a verb here”);}</script>
</head><body>
<p>sad indeed, there are other (noun) still freedom from (noun2) no ideas
, from this dryness, freedom from having (verb) as a poet on forced (verb 2)</p>
</body></html>
So basically I'm trying to declare variables in the script and have users enter their answers as a prompt. I'm then trying to take their answers and insert them into the body of the paragraph where I've put (noun) (noun2) (verb) and (verb2). I'm sorry this is so elementary and I can't figure this out. I don't expect you to write the whole code out for me, you can just give me conceptual advice.
Also if you're having problems non-coding related that I might be able to help with I could try to help you with that :D
You could store the text in a variable and use the string replace function to get your content in:
var input = prompt("word");
var text = "My text PLACEHOLDER1";
var newText = text.replace("PLACEHOLDER1", input);
// render text to dom
document.getElementById('myId').innerText = newText;
More advanced would be usage of a regular expression or a template engine.
I don't like giving direct answers when it's obviously for class, so I'll try to point you to a few helpful starting places.
First, you are going to want the user to be able to enter the required verbs, nouns, etc. So, setup a form that has several text inputs.
Next, I would put a button that does a couple things when clicked. First, it would check to make sure none of the text boxes are empty (we want the person to participate, after all). Then, the button will get the input from the user and insert it into the quote where needed. Finally, it will output the whole quote. To do this, I would create a function that, when the user clicks, would write to the p tag something like this:
"sad indeed, there are other " + noun1 + " still freedom from " + noun2 +
"no ideas, from this dryness, freedom from having "...etc.
My final hint: You can update the value of the p tag (I say 'p' because that is what you mentioned earlier. Personally, I would make it a div) if you give it an ID and reference that ID like this: http://www.w3schools.com/jsref/prop_text_value.asp (under more examples, you'll see how to set that to the variables noun1 and noun2).
Leave a comment if you need more hints.
Related
The Question and Codes
I am struggling with the below code:
$('.rdsubs-mysubscriptions table tbody tr td a').each(function() {
var subItem = $(this).html();
//console.log(subItem);
var subItemStripped = subItem.substring(12);
console.log(subItemStripped);
$('body').find('span:contains("subItemStripped")').addClass('HELLO');
}); // end of each function
When I check the console for subItemStripped then it shows this:
Framework
Content
Slideshow
Which means (in my head at least ;-)) that for each span that is inside the body it should find one of these subItemStripped and where it finds a match it should add the class hello but this is not happening.
Actually, nothing is happening.
When I change this line:
$('body').find('span:contains("subItemStripped")').addClass('HELLO');
to
$('body').find('span:contains("Framework")').addClass('HELLO');
It works nicely. So am I putting the variable subItemStripped wrongly in there or has it something to do with the .each() function.
I tried the below things to make it work
With the above code I tried a couple of variations before I came here:
$('body').find('span:contains(subItemStripped)').addClass('HELLO');
$('body').find("span:contains('subItemStripped')").addClass('HELLO');
I also tried it with completely different sets of code I gathered from other SO posts but none of those worked. Why I don't know.
$("span").filter(function() {
return $(this).text() === subItemStripped;
}).addClass("hello");
$("span").filter(function() {
return $(this).text() === subItemStripped;
}).css("font-size", "6px");
Why do I need this
I know I don't have to explain why I need this but it could be useful in coming up with other great ideas if the above is not feasible.
I have a webpage and on that page is a menu filled with products that a user can download if he/she has access.
Each menu item has a span with the title in it. Those titles are built up like: Framework Content Slideshow
On this same page is also a component that shows all the users subscriptions.
With the above code, I look to all the subscriptions of the user. Which returns
CompanyName Framework CompanyName Content CompanyName Slideshow
Then I Strip .substring(12) all the parts that I know are not present inside the menu. Which leaves me with Framework Content Slideshow
At this point, I know that some menu titles and the stripped item are the same and for every match, I want to add a class upon which I can then add some CSS or whatnot.
Hopefully, the question is clear and thanks to everyone in advance for helping me out.
#gaetanoM You are completely right. Right after I posted the question I came on this site:
jQuery contains() with a variable syntax
And found the answer which is the same as you are saying!
$('body').find("span:contains('" + subItemStripped + "')").addClass('HELLO');
Thanks so much!
#gaetanoM Can you make your comment in an answer? Then I can select it as the accepted answer. I am answering this question now just to make sure it has an answer. As people get punished for asking questions that don't get answers.
The best way to explain my question is using the example:
https://www.priberam.pt/DLPO/casa
As you hover each word within the main content, it refers to a link for the meaning of the "hovered" word. Is it possible to configure each word to turn into a link, and refer all links to its "meaning"?
I believe that a function that turns all words into links to its "pages" would be ok.
This is what we've been trying:
var link = /wordToReplace/gi;
var urlLink = 'https://www.priberam.pt/DLPO/wordToBeReplaced';
var newLink = urlLink.replace(wordToBeReplaced, 'wordToReplace');
Thanks!
You would need to write a function that upon hover of each element with a particular class would then see the html content inside the tag and then search for the definition attaching an additional class that would display a info-layer with the content your JS would inject (the meaning of the word).
I would start writing with some pseudo-code in order to determine all the steps that your JS script would need to do to achieve this.
I would then design the HTML so that each word has a span tag with the same class as what the JS will be looking for in order to trigger this function. You can write a separate JS function to split a paragraph into an array and then append the span tag on each array value before placing the array content back into the page.
Once you have your HTML, I would write your hover function following your pseudo-code you wrote before.
Finally I would style the code that JS is injecting into the DOM with CSS to finish.
If you are fairly good with jQuery, you can have this done in a few hours, but personally I would just use vanilla JavaScript since this seems like a learning experience for you but it would take longer.
Something similar to the example below?
var textToConvert = 'Words to be converted to links';
var lookupUrl = 'http://www.merriam-webster.com/dictionary/';
var convertedText = textToConvert.replace(
/(\w+)/g,
'$1'
);
document.getElementById('output').innerHTML = convertedText;
console.log(convertedText);
<p id="output"></p>
I have a ( probably very unclean) script that I intend to convert letters put into a text field into html image tags with corresponding pathways. I know there are probably easier ways of doing this, PHP for example however I am using it as a bit of an experiment to familiarise myself further with JS/Jquery. I have overcome a few obsticles to get where I am now as most of this is new ground for me.
In some cases the letters will have multiple images associated with them that will be selected at random so there are a couple of lines included which do this. These are fine however, the issue comes with the section of code that replaces the letters from the text field with the text and variables that make up the image tag. Whilst they work fine individually, when I want to convert multiple letters the replace overwrites instances of that letter in the previously generated image tag. Any ideas can I stop this? I've tried shifting the points at which the script occurs around but it seems the whole thing is somewhat fragile and haven't been able to create a workable solution.
Code in question:
// replace all instances within variable to generate thumbs
final_result = result.replace(/a/g, str_start+chosen_folder+"a"+random_variation+str_end)
.replace(/e/g, str_start+chosen_folder+"e"+random_variation+str_end);
JS Fiddle here: http://jsfiddle.net/N77wZ/
Many thanks in advance !
Do only a single replace:
final_result = result.replace(/a|e/g, str_start+chosen_folder+"$&"+random_variation+str_end);
Often times, when I use struts 2 tags, the loading of a page will be incomplete apparently because of single quote or double quote characters from the struts 2 tag interfering with such characters from javascript.
One example I am very eager to get working is as follows:
var me = '<s:a href=\'http://www.google.com\'>Google Link</s:a>';
$('#appnSelect').html(me);
So what I am concerned about is when single and double quotes are inside that me string on the right side of line 1. Ultimately, I need to get <s:select> to work, but this problem seems to creep in with a number of tags like the above example. Replace the <s:a> tag with an <a> tag, and voila, it works. However, when the <s:a> tag gets expanded, the page will incompletely load.
Is there an easy solution somewhere I am missing? One thing I did try was with the theme attribute setting theme="simple" because sometimes that helps me when the output gets rendered incorrectly. That did not work in this case.
Generating HTML from tags like that in the middle of a JavaScript string constant is always going to be an ugly business. In addition to quote characters, you're also likely to get newlines. Strictly speaking you don't know what you're going to get, and you can't control it.
One thing that comes to mind is that you could drop the tags into dummy <script> blocks marked as a non-JavaScript type:
<script id='anAnchor' type='text/html'>
<s:a href='http://www.google.com'>Google Link</s:a>
</script>
The browser won't try to execute that. You can then do this in your JavaScript code:
$('#appnSelect').html($('#anAnchor').html());
What should work with very little thinking:
<s:a id="google" style="display: none;" href="www.google.com">Google Link</s:a>
Now just grab the the element using the id in your script. Might be better if you set up a class. There are id, style and class attributes for all struts2 tags.
I believe the issue is with your escaping of the single quotes inside the <s:a> tag. In my experience with using <s:url>, I've done the following:
var url = "<s:url value='/someAction.action' />"
I believe the same syntax should hold true for <s:a>.
Additionally, look in your JSP container's error log, and see if you can find an error relating to that <s:a> tag. That may provide some additional insight to the problem.
This is my answer, which will not be the best answer because Pointy's response pointed me in the correct direction. However, up votes still appreciated :)
First, you need the script blocks which are not rendered. I have 2 because a checkbox will toggle between which one is displayed:
<script type="myType" id="abc">
<s:select name="selectName" list="#list1" listValue="%{prefix + '-' + name}" theme="simple"/>
</script>
<script type="myType" id="abc2">
<s:select name="selectName" list="#list2" listValue="%{prefix + '-' + name}" theme="simple"/>
</script>
Next, I create a region which is blank in the html code
<div id="innerRegion">
</div>
Then, I need to put something on the screen when the page first comes up, so go with this:
<script type="text/javascript">
$(document).ready(function(){
$('#innerRegion').html( $('#abc').html() )
});
I needed to put this at the end of my document because onLoad was already being used by a parent page. So I am saying abc is the correct default.
Then I need logic to handle what happens when the checkbox is pushed:
var buttonPressed = false;
$(window).load(
function()
{
LocalInit();
});
function LocalInit() {
$('#myForm input[name=buttonValue]').change(
function()
{
buttonPressed = !buttonPressed;
if (buttonPressed == true)
{
$('#innerRegion').html( $('#abc2').html() )
} else
{
$('#innerRegion').html( $('#abc').html() )
}
$('#dataId').href = document.location.href;
}
);
}
I think what was tripping me up ultimately was that I was trying to force the s:select tag through jQuery functions when as you see above it did not turn out to be necessary. I could just write the s:select as normal.
I'm trying to change the value of a text input field based on user actions. I'm doing it like this:
document.getElementById(textFieldID).value = newValue;
It isn't quite working -- the original text in the field remains on the screen, unchanged. However, when I submit the form, it behaves as though the value was indeed changed correctly. (And a debug alert confirms that yup, I'm hitting that bit of the code and passing in the right field ID and text value.) Anybody have any insights? Is there something I need to be doing to redraw the input element?
Edit: Per Jeff B's request, and per the fact that this seems to have everybody stumped, here's some relevant bits of code:
<script LANGUAGE="JavaScript" TYPE="text/javascript">
function changeText(changeSelector)
{
var myindex = document.getElementById(changeSelector+"Recent").selectedIndex;
var SelValue = document.getElementById(changeSelector+"Recent").options[myindex].value;
document.getElementById(changeSelector).value = SelValue;
document.getElementById("historicalText").value = SelValue;
document.getElementById("historicalTextSelect").value = changeSelector;
}
</script>
<input onChange="updateScrollingPreview1217(this); return true;" type="text" id="crawlMsg1217" name="crawlMsg1217" size="60" maxlength="1000" value="">
<select id="crawlMsg1217Recent" name="crawlMsg1217Recent" onchange="javascript:changeText('crawlMsg1217');">
[options go here]
</select>
And that "onChange" handler isn't what's gumming up the works; I get the same behavior with or without it.
Edit 2: It looks like the problem is being caused by "JSpell", a third-party spelling checker our product uses. (I'm told that clients prefer using it to a spellcheck built into the browser; go figure.) It appears to be slightly misconfigured on my test machine, so I'm going to try straightening that out and praying that it makes the problems go away. If it doesn't ... should be interesting.
Edit 3: Yup. Fscking JSpell. Just posted a complete answer for the sake of posterity, will accept it tomorrow when I'm allowed. My thanks to everybody who tried to help; +1's all around, wish I could give more.
I have confirmed that the culprit is indeed JSpell, and that the precise trouble spot is this line:
window.onload=jspellInit;
Despite the prayers mentioned in Edit 2 above, making sure it was configured correctly did NOT make the problem go away. And this line is indispensable to JSpell's functionality. I don't know if JSpell always hoses Javascript functionality this way, or if there's some sort of perfect storm of factors that's causing it to pick a fight with my page, but that is indeed the source of my problems.
My thanks to everybody who tried to help. This was obviously a bit of a no-win in terms of getting the right answer, since it was caused by a component that was seemingly entirely unrelated and thus didn't get mentioned by me, but you at least confirmed that I was (in theory) doing things right and not simply going insane.
Is the document's id actually "textFieldID" or is "textFieldID" a javascript variable that contains the ID of the text input to change? If it is not a variable, I believe you should make it:
document.getElementById('textFieldID').value=newValue;
It's hard to debug this without the context, since the code you have ought to work fine. Can you confirm that you've got the right node by doing something like:
document.getElementById(textFieldID).style.border = "4px solid red";
What does any other element on the page have a name attribute that is the same as the id?
Internet Explorer 8 and later. In IE8
mode, getElementById performs a
case-sensitive match on the ID
attribute only. In IE7 mode and
previous modes, this method performs a
case-insensitive match on both the ID
and NAME attributes, which might
produce unexpected results. -
http://msdn.microsoft.com/en-us/library/ms536437%28VS.85%29.aspx
Try alerting your the nodeName and id ofr the returned element and make sure its the input you expect.
Use div element instead of textfield. I had same problem, my textfield which is changed with another script wasnt get the right value. you can easily use any div element like textfield with some CSS. than you can get the value from div using innerHTML.