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
Related
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()
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>
on my form, I have many text input fields with pre-filled decimal values, the user can edit the values before submitting the form.
I was wondering if there is anyway using javascript/jquery, to make each input allow only values less than its initial value.
I find it quite challenging, so I thought about posting it here.
Thank you guys
Use jQuery Validation plugin's max method.
Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and 23 or smaller.</title>
<link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
</head>
<body>
<form id="myform">
<label for="field">Required, maximum value 23: </label>
<input type="text" class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
max: $('your_input_selector').val()
}
}
});
</script>
</body>
</html>
This may help you:
var initialValue = $("#myTextbox1").val()
$("#myTextbox1").on("input", function() {
if($("#myTextbox1").val() > initialValue) {
$("#myTextbox1").val(initialValue);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextbox1" type="text" value="5"/>
This solution converts the input into a number, prevents default form action, checks if the input value is a number and if not it alerts the user and resets the default input value, checks to see if the new value is less the the original and if it is not it resets the input to the original value.
HTML
<form id="myForm" action="">
<input type="text" id="myValue" value="5" />
<input type="button" id="myButton" value="validate" />
</form>
JavaScript
var origVal = $('#myValue').val();
$('#myButton').on('click', function(e) {
var getVal = Number($('#myValue').val());
e.preventDefault();
if (isNaN(getVal) === true) {
alert('The input value has to be a number.');
$('#myValue').val(origVal);
}
if (getVal > origVal) {
alert('The input value has to be less than the original value of ' + origVal);
$('#myValue').val(origVal);
}
});
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.
This is my HTML/Javascript Code.I am submitting the filled form to a Servlet. There seems to some problem with the form validation. I am not able to figure out why. It is supposed to prompt me to enter a new value if I enter 0 in textbox2 and select Divide from the drop down list box. But it doesn't and the form is submitted without any prompting to the servlet which throws Exception due to division by zero.
<html>
<head>
<title>A simple calculator</title>
<script language="text/javascript">
function validate(b,op)
{
var newval=b;
if(b=="0"&&op=="/")
newval=prompt("Enter a non-zero value for B:",1);
document.CalculatorForm.textbox2.value=newval;
}
</script>
</head>
<body>
<form name="CalculatorForm" method="get" action="http://localhost:8080/hello/CalculatorServlet" onsubmit="validate(this.textbox2.value,this.dropdown.options[this.dropdown.selectedIndex].value);">
A:<input type="text" name="textbox1" id="T1" /><br>
B:<input type="text" name="textbox2" id="T2" /><br>
Operation<br>
<select name="dropdown" id="dd">
<option value="+">Add</option>
<option value="-">Subtract</option>
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select>
<br>
<input type="submit" value="compute"/>
</form>
</body>
</html>
Change the function to:
function validate()
{
var b = document.getElementById('T2').value;
var op = document.getElementById('dd')
var opValue = op.options[op.selectedIndex].value;
if(b=='0' && op=='/')
//do something
else
// submit
}