Select the value of a form - JavaScript - javascript

I am new to JavaScript and I am trying to understand HOW the code works.
In my form I have two inputs:
First Name: which has to be filled by the user
Countries: which has to be selected by the user (but the countries are already there)
Once the user click the "Add this destination" button, it should appear his name plus the destination he has chosen.
I understand why the "destination" appears.
HOWEVER I do not understand HOW the first name can be passed if the form is empty. Even if I write something in "first name", its value is not passed into the result string I want to display.
My questions are two:
1) Why is not my code working?
2) MORE IMPORTANTLY: how the browser (?) understands that there has been a change in the filed of "first name" from empty to be filled with a name/string?
var x;
var destination = document.myTravelForm.destination.value;
var firstName = document.myTravelForm.firstname.value;
x = document.getElementById("banana").addEventListener("click", function() {
document.getElementById("travelerInfo").innerHTML = firstName + " you chose: " + destination
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1> Welcone to the booking site </h1>
<h4> Please, choose a destination </h4>
<form name="myTravelForm">
<label> First name: </label><br>
<input type="text" name="firstname" id="firstname" /><br>
<br>
<select name="destination">
<option value="Antarctica" selected>Antarctica</option>
<option value="Costa Rica">Costa Rica</option>
</select>
<input type="button" value="Add this destination" id="banana" />
</form>
<div id="travelerInfo"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

You need to get the form values when you are clicking on the button, if you get them before click, you will get their initial values. Try something like this:
var x;
x = document.getElementById("banana").addEventListener("click", function() {
var destination = document.myTravelForm.destination.value;
var firstName = document.myTravelForm.firstname.value;
document.getElementById("travelerInfo").innerHTML = firstName + " you chose: " + destination;
});
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1> Welcone to the booking site </h1>
<h4> Please, choose a destination </h4>
<form name="myTravelForm">
<label> First name: </label><br>
<input type="text" name="firstname" id="firstname" /><br>
<br>
<select name="destination">
<option value="Antarctica" selected>Antarctica</option>
<option value="Costa Rica">Costa Rica</option>
</select>
<input type="button" value="Add this destination" id="banana" />
</form>
<div id="travelerInfo"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

Matheus Pitz answered your first question fine, the variables are initialzed at the beginning of the script where they are undefined.
As for your second question how does the browser understand that there has been a change. The browser has several build in technologies that work together to allow this.
First your HTML documents are parsed by a browser and it will show a Javascript model of it which consists of various nodes. This is called the DOM (document object model).
The browser has all sorts of built in JS functions to manipulate the DOM and thus manipulate the view. For example:
document.getElementById("travelerInfo").innerHTML = 'test';
getElementById() Is an example of such a method which allows you to access a DOM node and perform various operations on it.
Hopefully this was helpful and I would strongly suggest you to read MDN article about the DOM. This will increase your understanding and make you a better developer.

For first part:
Because you're getting the value before it's event entered
Put that code inside your click callback.
2nd part
I don't really understand what do you mean by "How does browser...". You just get the value out of input
var destination = document.myTravelForm.destination;
var firstName = document.myTravelForm.firstname
document.getElementById("banana").addEventListener("click", function() {
document.getElementById("travelerInfo").innerHTML = firstName.value + " you chose: " + destination.value
});
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1> Welcone to the booking site </h1>
<h4> Please, choose a destination </h4>
<form name="myTravelForm">
<label> First name: </label><br>
<input type="text" name="firstname" id="firstname"/><br>
<br>
<select name="destination">
<option value="Antarctica" selected>Antarctica</option>
<option value="Costa Rica">Costa Rica</option>
</select>
<input type="button" value="Add this destination" id="banana"/>
</form>
<div id="travelerInfo"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

Related

DOM is receiving empty strings

so i have been trying make a calculator webpage just to get used to DOM, but for some reason when i try to get user input i receive empty strings.
this is my html
<!DOCTYPE html>
<html>
<head>
<title>Calculator DOM Practice</title>
</head>
<body>
<h1>Welcome to Calculator Web page</h1>
<!-- <form> -->
<div class="prompts">Please enter your first number</div>
<input id="first_num" type="text" placeholder="first num"><br>
<div class = "prompts">Please enter second number</div>
<input id="second_num" type = "text" placeholder="second num"><br>
<label for="operator">Chose your operation: </label>
<select id="operator" name = "operator">
<option value ="minus">-</option>
<option value ="addition">+</option>
<option value ="multiply">*</option>
<option value ="divide">/</option>
</select>
<button id="calc_button" type="submit">Calculate</button>
<!-- </form> -->
<script type="text/javascript" src="calculator.js"></script>
</body>
</html>
and here is my javascript where i receive the user input:
var first = document.getElementById("first_num").value;
var second = document.getElementById("second_num").value;
// var oper = document.getElementById("operator").value; //this only give sme
first index
var oper = operator.options[operator.selectedIndex].value;
var button = document.getElementById("calc_button");
first = Number(first);
second = Number(second);
I have tried using document.getElementId("first_num").text but for some reason it as if my script runs as soon as the webpage is started, so it sets those variables when they are empty.
As you said this script is looking for the empty input value when the page is first rendered. You need to add an event lister which calls a function when the input value is updated.
var firstInput = document.getElementById("first_num");
var firstNumber;
function updateFirstNumber(e) {
firstNumber = e.target.value;
}
first.addEventListener('change', updateFirstNumber);
More information on events (MDN)

jQuery not reading drop down box text from id

I want to be able to read the text which is submitted in a drop down box with jQuery, as I then want to post it to php. I've been following a tutorial but I have the issue when it does not read the value from the drop down box.
An alert with the name selected should appear when the refresh button is pressed. (The submit button in the script below is for something different and links to a different js file. Not relevant)
function update() {
var p1 = $("#playerOne").text();
alert('youre name is ' + p1);
}
<div class="inputForm">
<form id="frm1" onsubmit="return formSubmit()">
<h3>Update League Table!</h3>
<section class="playerOne">
<label for="playerOne">Player One Name:</label>
<select name="playerOne" id="playerOne">
<option value="player1">Player 1</option>
<option value="player2">Player 2</option>
<option value="player3">Player 3</option>
<option value="player4">Player 4</option>
</select>
</section>
<section class="submission">
<input type="submit" value="Submit">
</section>
<input class="refreshButton" type="button" value="Refresh" onclick="update()">
</form>
</div>
In the jquery file, if I remove var p1 = $("#playerOne").text(); then the alert will work. With that in the alert does not appear at all.
I have tried having the refresh button at different points in the HTML, didn't work. I have moved where <script type="text/javascript" src="jquery.js"></script> is within the HTML, didn't work.
I have also tried .val instead of .text. And var p1 = $("#playerOne option:selected").text();. Neither of these worked.
Any help is appreciated.
You can do this by using simple JavaScript code replace your jQuery with
var _val = document.getElementById('playerOne').value;
alert(_val); // it will work for you
$('#playerOne').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$('#playerOne option:selected').text();
function update() {
var p1 = $( "#playerOne option:selected" ).text(); // for getting value in element
alert ('youre name is ' +p1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="style.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body background="mkimage.png">
<div class="inputForm">
<form id="frm1" onsubmit="return formSubmit()">
<h3>Update League Table!</h3>
<section class="playerOne">
<label for="playerOne">Player One Name:</label>
<select name="playerOne" id="playerOne">
<option value="player1">Player 1</option>
<option value="player2">Player 2</option>
<option value="player3">Player 3</option>
<option value="player4">Player 4</option>
</select>
</section>
<section class="submission">
<input type="submit" value="Submit">
</section>
<input class="refreshButton" type="button" value="Refresh" onclick="update()">
</form>
</div>
</body>
</html>
Here is your solution
use val() for getting value for the selected list.
if your using text() jquery .it will give all text in the element.
function update() {
var p1 = $("#playerOne").val(); // for getting value in value attribute
alert ('youre name is ' +p1);
}
function update() {
var p1 = $( "#playerOne option:selected" ).text(); // for getting value in element
alert ('youre name is ' +p1);
}
Try changing your selector in your jQuery sentence:
function update() {
var p1 = $("#playerOne option:selected").text();
alert ('youre name is ' + p1);
}
Try this, to get the selected option:
$( "#playerOne option:selected" ).text()

Changing a value from another field

I'm trying to change a value that was set from javascript(jQuery) from another field. I want to target only one word from that value. Here's my code (http://jsfiddle.net/zL4pc90d/):
<html>
<head>
<title>jQuery get input Text value example</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
type="text/javascript"></script>
<script
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#select_car").change(function()
{
if ($("#select_car").val() == "")
{
terms = "";
} else if ($("#select_car").val() == "Honda")
{
terms = "One year lease on <car>.";
} else if ($("#select_car").val() == "Toyota")
{
terms = "Two year lease on <car>.";
} else if ($("#select_car").val() == "Ford")
{
terms = "Three year lease on <car>.";
}
$("#contract").val(terms);
});
});
</script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<form>
<fieldset>
<legend>jQuery Get and Set input Text value</legend>
<p>
<label for="carModel">
Car Model:
</label>
<input id="myInputText" type="text" name="inputBox" />
</p>
<p>
Make:
<select id="select_car">
<option value></option>
<option value="Honda">Honda</option>
<option value="Toyota">Toyota</option>
<option value="Ford">Ford</option>
</select>
</p>
<p>
<label for="contract">
Contract:
</label>
<input id="contract" type="text" name="outputBox" readonly="readonly" />
</p>
</fieldset>
</form>
</div>
</body>
</html>
For the new values, wherever it says "", I'd like it to be what I enter in the first input field. I'd prefer to do it dynamically too, so maybe calling the keyup function or something. How would I do this?
You can use input event to track what the user inputs in your input field and update value accordingly to the other box,
$("#myInputText").on("input", function () {
if ($("#myInputText").val() != "") {
terms = "Three year lease on " + $("#myInputText").val();
} else terms = terms = "Three year lease on <car>";
$("#contract").val(terms);
});
See a demo fiddle

JQuery to Submit a Form - Spot the Error

I've checked here and here but can't get my form to submit. (noob to Jquery...)
<html>
<head>
<title>Book Notes Application - Subjects</title>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
//alert(subject_id)
//document.forms["choose_subject"].submit();
$('#choose_subject').submit();
//$('form#choose_subject').submit();
//$('form#choose_subject')[0].submit();
//alert(subject_id);
//document.getElementById("choose_subject").submit();
})
})
</script>
</head>
<body>
<!-- CHOOSE SUBJECT -->
<FORM action="/books" id="choose_subject" name="choose_subject" method="POST">
Choose a Subject:
<select name="subject_id" id="subject_id">
<option value="1">a</option>
<option value="2">a2</option>
</select><input type="submit" name="submit" value="Choose Subject"/>
<BR />
</FORM>
<!-- CREATE SUBJECT -->
<FORM action="/subjects" id="create_subject" method="POST">
<BR /><BR />
Create a new Subject
<input type="text" name="subject_name" />
<input type="submit" name="submit" value="Create Subject" />
</FORM>
<body>
</html>
I've tried each of these methods:
1) document.forms["choose_subject"].submit();
2) $('#choose_subject').submit();
3) $('#choose_subject')[0].submit();
4) $('form#choose_subject').submit();
5) $('form#choose_subject')[0].submit();
6) document.getElementById("choose_subject").submit();
The first and last result in a "TypeError: document.forms.choose_subject.submit is not a function.
The second and fourth don't have an error but they also doesn't do anything.
The third and fifth error out with a "TypeError: $(...)[0].submit is not a function"
If I remove the second form these results hold true.
Clicking the submit button works as expected.
Change your the name of your input element:
<input type="submit" name="submit" value="Choose Subject"/>
to something other than "submit". As the .submit() docs state:
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures.
jsFiddle example

How to display user entered information using JavaScript?

I have a form code tat will allow the user to enter information. I'm trying to display certain parts of that information onto a new page using javascript. Basically, the page is meant to have the user enter information and have the name, date, time, and email display in a new tab or page. But I can't seem to have it displayed. Can anyone help me?
<html lang="en" >
<head>
<title>Shy Music Booking Confirmation</title>
<link rel="stylesheet" href="music.css" type="text/css" />
<body>
<div id="wrapper">
<div id="form">
<header><h1>Shy Music Private Lessons</h1></header>
<script type="text/javascript">
function addtext()
{
var userName = document.booking.userName.value;
var userDate = document.booking.userDate.value;
var userTime = document.booking.userTime.value;
var userEmail = document.booking.userEmail.value;
document.writeln("Thank you! You have just entered the following:");
document.writeln("<pre>");
document.writeln("Name: " + userName);
document.writeln("Date: " + userDate);
document.writeln("Time: " + userTime);
}
</script>
</head>
<hr>
<form name="booking">
<h1>Book a Slot Here!</h1>
<label for="userName">Name: <br><input type = "text" name = "userName"></label> <br><br>
<label for="userEmail">E-mail Address: <br><input type = "email" name = "userEmail"></label><br><br>
<label for="userPhone">Phone Number: <br><input type = "tel" name = "userPhone"> </label><br><br>
<label for="userInstrument">Instrument:
<select>
<option>Guitar</option>
<option>Drums</option>
<option>Piano</option>
</select>
</label>
<br><br>
<label for="userTime">
Preffered Time:
<select>
<option>9:00</option>
<option>9:30</option>
<option>10:00</option>
<option>10:30</option>
<option>11:00</option>
<option>11:30</option>
<option>12:00</option>
<option>12:30</option>
<option>1:00</option>
<option>1:30</option>
<option>2:00</option>
<option>2:30</option>
<option>3:00</option>
<option>3:30</option>
<option>4:00</option>
<option>4:30</option>
</select>
</label>
<select>
<option>AM</option>
<option>PM</option>
</select>
<br>
<br>
<label for="userDate">Date: <br><input type = "date" name = "userDate"></label><br><br>
<input type="submit" value="Submit" >
<form action="#">
<input type="button" value = "Back" onclick="javascript:history.go(-1)" />
</form>
</form>
</div>
</div>
</body>
</html>
I was working on this for a lot of time, but it wasn't working. But, I tried it recently and it worked! I hope this was helpful.
<html>
<head>
<h1> Welcome</h1>
</head>
<body>
<p> Enter name: </p>
<input id="name" name="name"class="Name" type="text" placeholder="Enter Full name" required>`
<input type="Submit" onclick="submitted()"> <br> <br>
<a id="new" href="www.google.com"> </a>
<script>
function submitted()
{
var a = document.getElementById("name").value;
if (a=="")
{
document.getElementById("new").innerHTML="";
alert("Please Enter a valid name!");
}
else if (a==" ") {
document.getElementById("new").innerHTML=""
alert("Please Enter a valid name!");
}
else
{
document.getElementById("new").innerHTML="Thank you, " + a + ". " + "Click here to continue.";
}
}
</script>
</body>
</html>
Or, slightly tightened, as a working snippet:
function submitted()
{
var a = document.getElementById("name").value.trim();
document.getElementById("new").innerHTML=
a===""?"":"Thank you, " + a + ". " + "Click here to continue.";
}
<p> Enter name: </p>
<input id="name" name="name"class="Name" type="text" placeholder="Enter Full name" required>
<input type="Submit" onclick="submitted()"> <br> <br>
<a id="new" href="www.google.com"> </a>
The problem with your code was that you were using document.write in a dynamic setting. When using it in this context, document.write will erase the content of the current document and replace it with the text specified by its parameters. For this reason, document.write is commonly regarded as poor way to represent and insert text/data. And it typically affects the plethora of beginners learning JavaScript. Here are some alternatives you should keep in mind:
element.innerHTML: Like I said in the comments. Use .innerHTML to insert the formatted HTML into document through an element on the page. It doesn't necessarily have to be specified by an id attribute. It can very well be given by any other form of element obtainment.
node.appendChild: This method is more DOM-friendly than the first. It allows you to insert a node at the end of the body of the element specified by node. For example:
var form = document.myForm,
new_element = document.createElement('input');
new_element.type = "button";
new_element.value = "Submit";
form.appendChild( new_element );
I hope this helped.

Categories

Resources