ProgLang: Javascript in HTML
Issue: I'm getting a user input via a comment box (their name) and want to have it inserted mid strings throughout the rest of the code. For example: 'Are you okay, first name, I was worried!'
I tried to use ${firstname}, but it didn't print the rest of the string in the resulting comment box.
Enter Your First Name
<br><input type="text" id=firstname name="firstname" onblur="addNameToCommentBox(this)"><br><br>
.
Opening Sentence <br>
<input type="checkbox" onclick="addToCommentBox(this);" name="grade" value="statement1. statement1. " + ${firstname}.`+ "statement1. statement1.">Statement1. indentifier user read on page<br>
Second Sentence <br>
<input type="checkbox" onclick="addToCommentBox(this);" name="grade" value="statement2. statement2. ">Statement2. indentifier user read on page<br>
<br>
...
Resulting Block<br>
<textarea id="comment" rows="10" cols="80"></textarea><br>
</form>
<script>
function addNameToCommentBox(nameElement) {
var comment = $("#comment");
comment.val(comment.val() + " " + nameElement.value); }
function addToCommentBox(checkboxElement) {
var comment = $("#comment");
if (checkboxElement.checked === true) {
comment.val(comment.val() + " " + checkboxElement.value);
} else {
var currentComment = comment.val();
currentComment = currentComment.replace(checkboxElement.value, "");
comment.val(currentComment);
Could you please advise me?
You can set your template like "statement1.statement1 {0} statement1. statement1."
And then write a function to get message by passing arguments.
function getComment(template, args){
return args.reduce((acc, element) => {
console.log(element);
acc = acc.replace(/{\d}/, element);
return acc;
}, template);}
Codepen link: https://codepen.io/nithinthampi/pen/gOYJopP
You have forgot to use $ before the parameters. Try this
<script>
function addNameToCommentBox(nameElement) {
var comment = $("#comment");
comment.val(comment.val() + " " + $(nameElement).value); }
function addToCommentBox(checkboxElement) {
var comment = $("#comment");
if (checkboxElement.checked === true) {
comment.val(comment.val() + " " + $(checkboxElement).value);
} else {
var currentComment = comment.val();
currentComment = currentComment.replace( $(checkboxElement).value), "");
comment.val(currentComment);
I need to create a counter loop that begins after the user clicks the "submit" button. However, this "submit" button is already being used in another variable. The submit button needs to do two things here, at the same time, and I cannot figure out how to make that work. When the user inputs their information for their first name, last name, and middle initial, and then clicks the submit button, not only will the header change, but a counter to 125 needs to begin. Here is my code so far. What changes do I need to make sure that when the user clicks submit, the <h1> changes with their name in the greeting, and a loop begins counting from 1 to 125 with words like "hello world" after it.
example:
1)Hello World
2)Hello World
3)Hello World
etc
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="fizzbuzz.css">
<title>Fizz Buzz 0</title>
<script>
function clickFunction(){
var firstName = document.getElementById("firstName").value;
var middleName= document.getElementById("middleName").value;
var lastName= document.getElementById("lastName").value;
document.getElementById("greeting").innerHTML =
"Welcome, " + firstName + " " + middleName+ " " +lastName + "!";
};
function clickFunction = ""; {
while (var i=0;i<125;i++) {
out = out + "London Kings" + "</br>";
document.getElementById("greeting").innerHTML = out;
}
}
</script>
</head>
<body>
<div id="header">
<p>
<img src="images/banner.jpg" alt="Banner" height="130" width="940" style="border:0" />
</p>
</div>
<div id="content">
<div id="feature">
<h2 id="greeting"> Welcome to London Kings Football! </h2>
<form>
First Name <input id="firstName"> </input>
Middle Initial <input id="middleName"> </input>
Last Name <input id="lastName"> </input>
</form>
<button onClick="clickFunction()",> Submit </button>
</div>
</div>
</body>
</html>
Some changes you can make to make to your current code so it runs
change the while loop to a for loop
initialize the out variable ( you are using it before it is defined
in a right hand assignmen)
So you final function is
function clickFunction() {
var firstName = document.getElementById("firstName").value;
var middleName = document.getElementById("middleName").value;
var lastName = document.getElementById("lastName").value;
var out = '';
document.getElementById("greeting").innerHTML = "Welcome, " + firstName + " " + middleName + " " + lastName + "!";
for (var i = 0; i < 125; i++) {
out = out + "London Kings" + "</br>";
document.getElementById("greeting").innerHTML = out;
}
}
Other things that could make your code better
Dont add the event listener inline, its harder to reason for your code
instead use document.querySelector("button").addEventListener("click", function(){});
move your script tag just before the closing body tag (</body>) this way the javascript code parsing will not block the rendering of the page (js runs in one thread)
dont query the DOM for each repetition of the for loop instead move the greeting query to the top of the function so you run it only once (per function call)
dont query for the DOM elements each time you run the code(better solution to 3 above, instead either move queries to the top level (those vars will be global, we dont like globals) or create a closure which will encapsulate your valiables
#4 example
var clickFunction = (function(){
var firstName = document.getElementById("firstName");
var middleName = document.getElementById("middleName");
var lastName = document.getElementById("lastName");
var greeting = document.getElementById("greeting");
var out = '';
return function(){
greeting.innerHTML = "Welcome, " + firstName + " " + middleName + " " + lastName + "!";
for (var i = 0; i < 125; i++) {
out = out + "London Kings" + "</br>";
greeting.innerHTML = out;
}
}
}())
document.querySelector("button").addEventListener("click", clickFunction)
script tag containing the above code has to be before the closing body tag
Can some one help me in this
I had a variable
var myValue = "what is you name? what is your age?"
i want to find the '?' in the string and replace it with a html input text element
where the user can enter the answer in the text box and at last i need a string as out put like this
"what is your name my name is xyz what is your age i am 25"
Please help me in this
Thanks
Kumar
This will dynamically take your myValue, replace all ?'s with inputs and then add a button to alert you of the user input. It will place myValue into the body, but you can place it somewhere else.
$(function() {
var myValue = "what is you name? what is your age?";
myValue = "<div>" + myValue;
while(myValue.indexOf("?") > -1)
myValue = myValue.replace("?", " <input type=\"text\" />");
myValue += "</div>" + "<button type=\"button\" onclick=\"sumUp(this)\">Declare</button>";
$("body").html(myValue);
});
function sumUp(button) {
var $prevDiv = $(button).prev().clone();
$prevDiv.children("input").each(function() {
$(this).replaceWith($(this).val());
});
alert($prevDiv.html());
}
If you have 2 input elements with IDs 'name' and 'age' respectively you can do this:
var nameValue = document.getElementById('name').value;
var ageValue = document.getElementById('age').value;
var anotherValue = myValue
.replace(/name\?/, nameValue)
.replace(/age\?/, ageValue)
You should be able to do something as simple as:
var myValue = "what is you name? what is your age?"
var nameVar = window.prompt("What is your name?","");
var ageVar = window.prompt("What is your age?","");
var myValue = myValue.replace("?", nameVar).replace("?", ageVar);
Alternatively, you could do something like:
var myValue = "what is you name? what is your age?"
var nameVar = '<input type="text" id="name" name="name">';
var ageVar = '<input type="text" id="age" name="age">';
document.write(myValue.replace("?", nameVar).replace("?", ageVar))
You'd then read the two input elements using jQuery with:
$('name').val();
$('age').val();
If you have a div with the question in it:
<div id="questions">What is your name? What is your age?</div>
and you want to replace those ? marks with input boxes, you could do this to make input boxes show up right after the questions:
var questions = $("#questions").text();
var questionMarkIndex = questions.indexOf("?");
var nameQuestion = questions.substring(0, questionMarkIndex+1);
var finalHtml = nameQuestion + '<input id="name" type="text" />';
var ageQuestion = questions.substring(questionMarkIndex+1);
finalHtml += ageQuestion + '<input id="age" type="text" />';
$("#questions").html(finalHtml);
This (or something close to it) will make you end up with What is your name?[input box] What is your age?[input box].
I am trying to create a button that upon clicking, fills an input box located right next to it with 3 random words and 2 preset words.
I have the 5 words with JQuery & Javascript going into <p> tags as of now, but I cannot figure out for my life how to get them into the input box.
Here's what I have so far for the JavaScript:
jsfiddle link
It's forcing me to put some of the code, so here is the short amount of HTML I have for it.
<h1>Shakespearean Insult Generator</h1>
<div>
<p id=word4></p>
<p id=word1></p>
<p id="word2"></p>
<p id="word3"></p>
<p id=word5></p>
</div>
<input type="text" name="message" size="50" value="Thou">
<button id="wordGen">Click Me!</button>
It sounds like your only issue is with how to set the value of a text input. Use jQuery's val method to set the value of the text input to the complete sentence that you have constructed. See:
http://api.jquery.com/val/
You should give the text input an id attribute (not necessary, as you could select by name), eg.
<input type="text" name="message" size="50" value="Thou" id="finalMessage">
and then something like this to select and set its value:
// construct the sentence
var finalMessage = 'Thou ' + words1[getWord1()] + ' ' + words2[getWord2()] + ' ' + words3[getWord3()];
// set the value of the text input to the sentence
$("#finalMessage").val(finalMessage);
As others have suggested you could also improve your method of selecting a random word to make it more reusable.
Try this :
$('#wordGen').click(function() {
$('#word1').html("");
$('#word2').html("");
$('#word3').html("");
$('#word1').append('<input value="' + words1[getWord1()] + '"></input>');
$('#word2').append('<input value="' + words2[getWord2()] + '"></input>');
$('#word3').append('<input value="' + words3[getWord3()] + '"></input>');
});
Fiddle : https://jsfiddle.net/DinoMyte/fy1asfws/24/
If you have your three words and you need to put them in the <input>, then you need to use $("#message").val() to set the text for the input. Also, for this to work, you need to add id="message" to the <input> tag so that it becomes <input type="text" id="message" name="message" size="50" value="Thou">. For instance, your code might look like this:
val word1 = words1[getWord1()];
val word2 = words1[getWord2()];
val word3 = words1[getWord3()];
$('#word1').text(word1);
$('#word2').text(word2);
$('#word3').text(word3);
$("#message").val(word1 + " " + word2 + " " + word3);
Essentially, as I can see from the jsfiddle link, your question boils down to how to set the value property of an input field.
As you're using jQuery, this can be done by using the val() method.
In action for your generator:
$('input[name=message]').val(insultFunctionWord1() + insultFunctionWord2());
The javascript alternative is just as concise as the solutions written in jQuery (and, arguably, could be abbreviated further):
function getWord(i) {
var randomNumber = Math.floor(Math.random() * words[(i-1)].length);
return words[(i-1)][randomNumber];
}
document.querySelector('#wordGen').onclick = function() {
var insult = getWord(1) + ' ' + getWord(2) + ' ' + getWord(3);
document.querySelector('input').value = insult;
}
Here is the full solution in plain vanilla javascript:
var words = [
['artless',
'bawdy',
'beslubbering',
'bootless',
'churlish',
'cockered',
'clouted',
'craven',
'currish',
'dankish',
'dissembling',
'droning',
'errant',
'fawning',
'fobbing',
'froward',
'frothy',
'gleeking',
'goatish',
'gorbellied',
'impertinent',
'infectious',
'jarring',
'loggerheaded',
'lumpish',
'mammering',
'mangled',
'mewling',
'paunchy',
'pribbling',
'puking',
'puny',
'qualling',
'rank',
'reeky',
'roguish',
'ruttish',
'saucy',
'spleeny',
'spongy',
'surly',
'tottering',
'unmuzzled',
'vain',
'venomed',
'villainous',
'warped',
'wayward',
'weedy',
'yeasty',
],
['base-court',
'bat-fowling',
'beef-witted',
'beetle-headed',
'boil-brained',
'clapper-clawed',
'clay-brained',
'common-kissing',
'crook-pated',
'dismal-dreaming',
'dizzy-eyed',
'doghearted',
'dread-bolted',
'earth-vexing',
'elf-skinned',
'fat-kidneyed',
'fen-sucked',
'flap-mouthed',
'fly-bitten',
'folly-fallen',
'fool-born',
'full-gorged',
'guts-griping',
'half-faced',
'hasty-witted',
'hedge-born',
'hell-hated',
'idle-headed',
'ill-breeding',
'ill-nurtured',
'knotty-pated',
'milk-livered',
'motley-minded',
'onion-eyed',
'plume-plucked',
'pottle-deep',
'pox-marked',
'reeling-ripe',
'rough-hewn',
'rude-growing',
'rump-fed',
'shard-borne',
'sheep-biting',
'spur-galled',
'swag-bellied',
'tardy-gaited',
'tickle-brained',
'toad-spotted',
'unchin-snouted',
'weather-bitten',
],
['apple-john',
'baggage',
'barnacle',
'bladder',
'boar-pig',
'bugbear',
'bum-bailey',
'canker-blossom',
'clack-dish',
'clotpole',
'coxcomb',
'codpiece',
'death-token',
'dewberry',
'flap-dragon',
'flax-wench',
'flirt-gill',
'foot-licker',
'fustilarian',
'giglet',
'gudgeon',
'haggard',
'harpy',
'hedge-pig',
'horn-beast',
'hugger-mugger',
'joithead',
'lewdster',
'lout',
'maggot-pie',
'malt-worm',
'mammet',
'measle',
'minnow',
'miscreant',
'moldwarp',
'mumble-news',
'nut-hook',
'pigeon-egg',
'pignut',
'puttock',
'pumpion',
'ratsbane',
'scut',
'skainsmate',
'strumpet',
'varlot',
'vassal',
'whey-face',
'wagtail',
]
];
function getWord(i) {
var randomNumber = Math.floor(Math.random() * words[(i-1)].length);
return words[(i-1)][randomNumber];
}
document.querySelector('#wordGen').onclick = function() {
var insult = getWord(1) + ' ' + getWord(2) + ' ' + getWord(3);
document.querySelector('input').value = insult;
}
button {
background-image: url( 'https://media.giphy.com/media/URZcG7uLd9h4s/giphy.gif' );
background-size: 100px 130px;
height: 250;
width: 250;
//background-size: auto;
font: 15px Verdana, sans-serif;
}
h1 {
font: 35px Arial, sans-serif;
}
<h1>Shakespearean Insult Generator</h1>
<input type="text" size="30" />
<button id="wordGen">Click Me!</button>