I'm trying to display a message that appears after the user has input some details into input boxes. Once they put in the info in the input boxes, the page should add the info to the multi-line text and then display the entire message on the webpage with the new info included. This code I have only displays the message without the input.
Here, I'm simply having the user put in the text in the box, then I tried to "parse" the input's value by giving it a variable name with a value within the code so it can be added as a property to the "libs" object. I have more to the message, but I can't even get this one sentence to process correctly.
<!DOCTYPE html>
<html>
<head>
<title>Madder Libs</title>
</head>
<body>
<div id="input">
<form>
<p>
<h4>Piece of clothing:</h4><input id="cloth" type="text" value=" " />
</p>
</form>
</div>
<script>
let clothes = document.getElementById('cloth').value;
let libs = {
a: clothes,
/*b: firstBodyPart,
c: secondBodyPart,
d: verbOne,
e: thirdBodyPart,
f: verbTwo,
g: firstNoun,
h: secondNoun,
i: verbThree,*/
};
let showThis = function()
{
let display = function(message)
{
let sayThis = `I wear a ${message.a} on sundays.`;
return sayThis;
}
document.getElementById('madlibs').innerHTML += "<br/>" + display(libs);
}
</script>
<div id="madlibs">
<button type="submit" onclick="showThis()">Show Message</button>
</div>
</body>
</html>
I want my message to be displayed including whatever the user put in the text box
Let's start by addressing why your sentence does not work. It is simply a matter of timing or in other words when things get executed. In your code (which isn't very well structured but onto that later) you execute
let clothes = document.getElementById('cloth').value;
at the very beginning of the script. In this case you are not obtaining some form of reference that would allow you to read the value at later stage but the actual value at the time. Since your input field has value attribute set to empty string, this is all you will ever get no matter how many times you execute the function later.
In order to get value of the input at the time of calling your method you would have to move it into the function itself.
But as I mentioned earlier your code is overall structured poorly so allow me to provide a few suggestions.
button of type submit by default executes submission of the form if placed within the form; you are not taking advantage of that (this has benefits such ability to submit form with "Enter" key e.g.
placing <script> in the middle of your document is poor choice as it blocks rendering of the rest of the document. Best options are to place it either within <head> when used with defer attribute or at the end of the document just before closing </body> tag.
Nesting your function within each other has not benefit here. You can easily define them independently and call one within the other if needed.
heading element <h4> cannot appear within <p> tag
Example
<!DOCTYPE html>
<html>
<head>
<title>Madder Libs</title>
</head>
<body>
<form action="/" onsubmit="return showThis()">
<div>
<label for="cloth">Piece of clothing:</label>
<input id="cloth" type="text" value="" />
</div>
<div id="madlibs"></div>
<div>
<button type="submit">Show Message</button>
</div>
</form>
<script>
// let's get references to our elements, so we don't have to
// do it multiple times
let clothes = document.getElementById('cloth');
let madlibs = document.getElementById('madlibs');
// let's define our functions
function display(message) {
let sayThis = `I wear a ${message.a} on sundays.`;
return sayThis;
}
function showThis() {
const clothesValue = clothes.value;
let libs = {
a: clothesValue,
/*b: firstBodyPart,
c: secondBodyPart,
d: verbOne,
e: thirdBodyPart,
f: verbTwo,
g: firstNoun,
h: secondNoun,
i: verbThree,*/
};
madlibs.innerHTML += "<br/>" + display(libs);
return false;
}
</script>
</body>
Related
I am trying to write a simple Regex Checker function that takes the user input and checks it against certain criteria. Only problem is, I can't get the user input to be passed into the new variable to begin the checking.
Can someone help me understand why I'm not seeing the user input in the log? I just want to be able to see the user input in the console so I can continue writing the code I need. EDIT-I know it is set to ALERT at the moment and not console.log-
let first = document.getElementById('firstName').value;
let last = document.getElementById('lastName').value;
function regexChecker () {
alert(first + last);
};
<!DOCTYPE html>
<html>
<head>
<title>Regex Checker</title>
</head>
<body>
<form id='form'>
<h2>Please enter your first and last name</h2>
<label for='firstName'>First Name: </label>
<input type='text' id='firstName'>
<label for='lastName'>Last Name: </label>
<input type='text' id='lastName' >
<button onclick='regexChecker()' type='reset'>Verify Input</button>
</form>
<script src='./script.js'></script>
</body>
</html>a
Thanks in advance.
Just assign values of first and last inside the function cause these two lines invoke when the page loads so have null or empty string values. You must reassign them.
function regexChecker () {
let first = document.getElementById('firstName').value;
let last = document.getElementById('lastName').value;
alert(first + last);
};
<!DOCTYPE html>
<html>
<head>
<title>Regex Checker</title>
</head>
<body>
<form id='form'>
<h2>Please enter your first and last name</h2>
<label for='firstName'>First Name: </label>
<input type='text' id='firstName'>
<label for='lastName'>Last Name: </label>
<input type='text' id='lastName' >
<button onclick='regexChecker()' type='reset'>Verify Input</button>
</form>
<script src='./script.js'></script>
</body>
</html>a
html>
<head>
<title>Landing</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
</head>
<body>
<form name="testForm" action="move.jsp">
<label><h1>Enter the data <h1/></label><br/>
<input type="text" name="DATA"><br/>
<input type="submit">
</form>
<% out.println(DATA) %> <!-- WRONG!! -->
</body>
</html>
Please ignore the action part
I am working on a spring mvc project and I have a problem. What I want is that, when the user clicks submit, we should not leave the page, we should just stay. But the values submitted would be used as a parameter to a function in the same page. Here, let's just say I want to print it, and that is the part that is wrongly entered.
What should I do to accomplish this? Please help
You can use ajax here when your submit button is clicked call this function and then using this call your ajax passed the value from your input to your server and then at your server side perform operation which you needed to do and then the result back to ajax .
Your form :
<form name="testForm" action="move.jsp">
<label><h1>Enter the data <h1/></label><br/>
<input type="text" name="DATA"><br/>
<input type="button" onclick="submit_values()">
<!--^^added this-->
</form>
<div id="result"><!--here data will come back--></div>
Then on click of your button submit_values() function will get called . i.e :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<script>
function submit_values() {
//get input value
var values = $("input[name='DATA']").val();
console.log(values);
$.ajax({
type: 'POST',
data: {
values: values//passing to server
},
url: "Your_server_url",
success: function(data) {
alert(data);//this will display whatever server will return
$("#result").html(data);//add response back to show
}
});
}
</script>
Then at your server-side do like below :
String data =request.getParameter("values");//get value
String send_back = something(data);//call your function
out.println("DATA BACK"+send_back );//this will go back to ajax
I've met a weird behavior. I'm trying to get / set the value of an input textbox After FeatherLight lightbox is closed. I get "Undefined" when trying to fetch the value of the textbox (again, after it was opened and closed via Featherlight). You can see my source code here:
https://jsfiddle.net/hgyba4dg/
The only relevant part is the html code. try running the code on JSFiddle and see the input's value (the textbox's value). You'll see that you'll get "undefined" after closing the Featherlightbox. Here is the html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var storeData = null;
function openFeatherLight()
{
if (!storeData)
{
storeData = $.featherlight($('#MyDiv'), { 'persist' : true , 'beforeOpen' : sayHi , 'beforeClose' : sayBye, 'afterClose' : changeInputValueAfterClose });
}
else
{
storeData.open();
}
}
function sayHi()
{
alert('Value of textbox BEFORE opening FeatherLight LightBox Is: ' + $('#MyTextBox').val());
}
function sayBye()
{
alert('Value of textbox BEFORE CLOSING the FeatherLight LightBox Is: ' + $('#MyTextBox').val());
}
function changeInputValueAfterClose()
{
$('#MyTextBox').val("Bla");
alert('Current Value Of Input TextBox After Change is: ' + $('#MyTextBox').val());
alert('We get "Undefined". Why?');
}
</script>
</head>
<body>
<div id="Shit" style="display: none;">
<div id="MyDiv">
Text
<form id="MyForm">
<input type="text" value="Initial_Value_Set_By_Me_For_Testings" id="MyTextBox">
</form>
</div>
</div>
<input name="Button1" type="button" value="Open FeatherLight" class="AddToMenuButton" onclick="openFeatherLight();">
</body>
</html>
After the first time, the DOM elements remain detached (I open to reinsert it one day...). So $('#MyTextBox') won't work afterwards. Either keep a reference to it, or use storeData.$content.find('#MyTextBox')
Here is the code I'm working with:
<form id="myForm" action="form_action.asp">
First name: <input type="text" name="fname" value="Bob"><br>
Last name: <input type="text" name="lname" value="Smith"><br>
</form>
<button onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myForm").elements[1].value;
document.getElementById("demo").innerHTML = x;
}
</script>
I like how this works, but can't figure out how to define where and how the values are displayed. Ideally, I would like them to appear at specified places within a large block of text.
For example, with the values above, I could have the person put in their first name and last name, and then have the following show with the appropriate values in place:
[FirstName]'s last name is [LastName].
Right now, I can't figure out how to have the values they input show where I want them within other text.
I have this code: <p class = "foo">Text</p>
And I also have a form: <form action = "XXX.php" method = post></form>
However, how can I get the value of the <p> when I submit it, as the <p> element can be changed.
So what I mean is to be able to post the value of the <p> when the user submits the form, and to be able to access it from that php file with: $_POST['foo'];
Thanks, I have tried to be as clear as possible.
You have to use Javascript for that
A jQuery function that will work
$("form").submit(function(){
var value = $("p").html();
// If foo already exists
if( $("[name=foo]").length > 0 )
{
$("[name=foo]").val(value);
}
else
{
var input = $("<input />", { name : "foo",
value : value ,
type : "hidden" });
$(this).append(input);
}
});
Use
<input type="hidden" value="something" name="something" id="something" />
and when you change inner html of <p> change the value of hidden input.
I think your best bet is to make it an input with readonly enabled, and style to to look like a <p>. It's better then trying to add it to the POST parameters with JavaScript.
Here's a quick example. I bet it could still be improved with a few extra CSS quirks, experiment a bit.
The easiest thing to do is set the value of a hidden form field when you change the contents of your <p>.
Alternatively, you can get its contents and post with JavaScript.
For text you need to use input field:
<input type="text"/>
Form fields should must have an id:
<input type="text" id="pewpew" class="foo"/>
I would go with:
<input type="text" id="pewpew" class="foo" value="default text goes here"/>
OR
Go with different workarounds, like setting form's hidden elements on the fly, etc.
You can create hidden field on the fly and set its value on form submit. Like this:
<form id="form" action="/somewhere" method="post">
<p>Some text</p>
<input type="submit" value="Submit"/>
</form>
<script type="text/javascript">
var form = document.getElementById('form');
form.onsubmit = function()
{
var p = this.getElementsByTagName('p')[0];
if (!document.getElementById('pval'))
{
var pinput = document.createElement('input');
pinput.setAttribute('type', 'hidden');
pinput.setAttribute('id', 'pval');
pinput.setAttribute('name', 'p');
this.appendChild(pinput);
}
document.getElementById('pval').value = p.innerHTML;
return true;
}
</script>
Works, i've tested.