javascript: I want to show city and state when the zip is filled in. I have the the geo location working but now I just want city and state to show when the zip is filled in.
This is my HTML:
<label for="city">City</label>
<input size="20" placeholder="Town or City" name="city" id="city" type="text">
<br>
<label for="state">State</label>
<input size="10" placeholder="State/Province" name="state" id="state" type="text">
And this is my JavaScript:
zip.addEventListener("change", getGeo);
function getGeo(e){
// make an send an XmlHttpRequest
var x = new XMLHttpRequest();
x.open("GET","http://maps.googleapis.com/maps/api/geocode/json?address="+this.value,true);
x.send();
// set up a listener for the response
x.onreadystatechange=function(){
if (this.readyState==4 && this.status==200){
var c = JSON.parse(this.response).results[0].address_components[1].long_name;
//alert(c);
var s = JSON.parse(this.response).results[0].address_components[2].short_name;
//alert(s);
if (c) {
city.value = c;
}
if (s) {
state.value = s;
}
//document.getElementById("output").innerHTML = o;
var l = JSON.parse(this.response).results[0].geometry.location;
if (l.lat) {
lat.value = l.lat;
}
if (l.lng) {
lon.value = l.lng;
}
}
}
}
It's all in this jsfiddle http://jsfiddle.net/lakenney/gad7ntgk/
Looks like you already have a good start, but this example might help a bit. Run the code snippet and enter a postal code or city name. I kept it very simple, but you could check the data array length. When equal to 1 you have a match and could display geo location and other into on the page.
Keep in mind that you're doing a cross domain ajax call ... which will fail in IE < 10. Lots of questions about that on SO if you need help.
<!DOCTYPE HTML>
<html>
<head>
<title>Demo</title>
<style type="text/css">
#container {position: relative; }
#location {width: 20em; border: 1px steelblue solid;}
#results { border: 1px gray solid; padding: 2px; position: absolute;background-color:aliceblue;}
#results ul { list-style: none; padding: 0; }
#results ul li {padding: 2px; color: dimgray; }
</style>
</head>
<body>
<div id="container">
Enter a city or postal code:<br>
<input id="location" type="text" onKeyup="getLocation()" value="London">
<div id="results"></div>
</div>
<script type="text/javascript">
function getLocation( ) {
var value, xhr, html, data, i;
value = document.getElementById('location').value;
if (value.length < 2) return;
xhr = new XMLHttpRequest();
xhr.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=" + value, true );
xhr.onreadystatechange = function() {
if (xhr.readyState==4 && xhr.status==200) {
data = JSON.parse(xhr.responseText);
html = '';
for(i=0; i< data.results.length; i++ ) {
html += '<li>' + data.results[i].formatted_address;
}
document.getElementById('results').innerHTML = '<ul>' + html + '</ul>';
}
}
xhr.send();
}
getLocation();
document.getElementById('location').focus();
</script>
</body>
</html>
See updated jsfiddle.
http://jsfiddle.net/gad7ntgk/3/
Problem that you had is that this HTML was commented out:
<!--<label for="city">City</label>
<input size="20" placeholder="Town or City" name="city" id="city" type="text">
<br>
<label for="state">State</label>
<input size="10" placeholder="State/Province" name="state" id="state" type="text">-->
And when values returned the assigning of value should be:
document.getElementById('city').value = c;
Related
So, I have this contact form sending me a mail and updating my google sheet. I found this on GitHub. When I don't add the JS file I get a mail and an update. When I add the JS I get neither. I have tried with and without this script link when using JS but it does not work.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
For security purpose I have removed my google sheet link and kept it as action="#" from form and because I have added my e-mail in my google sheet I can leave my data-email="" as it is.
I also don't get the thankyou message at the submission of the form when I have added my JS file, but without it I get confirmation displaying the details submitted.
There is a honeypot input label that is hidden by CSS and needs to be left blank for the form to be submitted successfully, avoiding spam.
It seems that there is some issue with the JS(duh!).
Please help!!!
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="contact form example">
<title>Contact Form Example</title>
</head>
<body>
<h2 class="content-head is-center">Contact Us!</h2>
<aside>
<p>
We would <em>love</em> to hear from you! </p>
<p>Please use the <b><em>Contact Form</em></b>
to send us a message.
</p>
</aside>
<!-- START HERE -->
<link rel="stylesheet" href="https://unpkg.com/purecss#1.0.0/build/pure-min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Style The Contact Form How Ever You Prefer -->
<link rel="stylesheet" href="style.css">
<form class="gform pure-form pure-form-stacked" method="POST" data-email=""
action="#">
<!-- change the form action to your script url -->
<div class="form-elements">
<fieldset class="pure-group">
<label for="name">Name: </label>
<input id="name" name="name" placeholder="What your Mom calls you" />
</fieldset>
<fieldset class="pure-group">
<label for="message">Message: </label>
<textarea id="message" name="message" rows="10"
placeholder="Tell us what's on your mind..."></textarea>
</fieldset>
<fieldset class="pure-group">
<label for="email"><em>Your</em> Email Address:</label>
<input id="email" name="email" type="email" value=""
required placeholder="your.name#email.com"/>
</fieldset>
<fieldset class="pure-group">
<label for="color">Favourite Color: </label>
<input id="color" name="color" placeholder="green" />
</fieldset>
<fieldset class="pure-group honeypot-field">
<label for="honeypot">To help avoid spam, utilize a Honeypot technique with a hidden text field; must be empty to submit the form! Otherwise, we assume the user is a spam bot.</label>
<input id="honeypot" type="text" name="honeypot" value="" />
</fieldset>
<button class="button-success pure-button button-xlarge">
<i class="fa fa-paper-plane"></i> Send</button>
</div>
<!-- Customise the Thankyou Message People See when they submit the form: -->
<div class="thankyou_message" style="display:none;">
<h2><em>Thanks</em> for contacting us!
We will get back to you soon!</h2>
</div>
</form>
<!-- Submit the Form to Google Using "AJAX" -->
<script data-cfasync="false" type="text/javascript" src="form-submission-handler.js"></script>
<!-- END -->
</body>
</html>
JS
(function() {
// get all data in form and return object
function getFormData(form) {
var elements = form.elements;
var honeypot;
var fields = Object.keys(elements).filter(function(k) {
if (elements[k].name === "honeypot") {
honeypot = elements[k].value;
return false;
}
return true;
}).map(function(k) {
if(elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
}else if(elements[k].length > 0){
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name){
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
formData.formGoogleSendEmail
= form.dataset.email || ""; // no email by default
return {data: formData, honeypot: honeypot};
}
function handleFormSubmit(event) { // handles form submit without any jquery
event.preventDefault(); // we are submitting via xhr below
var form = event.target;
var formData = getFormData(form);
var data = formData.data;
// If a honeypot field is filled, assume it was done so by a spam bot.
if (formData.honeypot) {
return false;
}
disableAllButtons(form);
var url = form.action;
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
form.reset();
var formElements = form.querySelector(".form-elements")
if (formElements) {
formElements.style.display = "none"; // hide form
}
var thankYouMessage = form.querySelector(".thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
}
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
}).join('&');
xhr.send(encoded);
}
function loaded() {
// bind to the submit event of our form
var forms = document.querySelectorAll("form.gform");
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener("submit", handleFormSubmit, false);
}
};
document.addEventListener("DOMContentLoaded", loaded, false);
function disableAllButtons(form) {
var buttons = form.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
})();
CSS
body {
margin: 2em;
}
aside {
background: #1f8dd6; /* same color as selected state on site menu */
padding: 0.3em 1em;
border-radius: 3px;
color: #fff;
margin-bottom: 2em;
}
textarea {
width: 100%;
}
.content-head {
font-weight: 400;
text-transform: uppercase;
letter-spacing: 0.1em;
margin: 2em 0 1em;
}
.is-center {
text-align: center;
}
.button-success {
color: white;
border-radius: 4px;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
background: rgb(28, 184, 65); /* this is a green */
}
.button-xlarge {
font-size: 125%;
}
button {
float: right;
}
#name, #email {
width: 50%;
}
.honeypot-field {
display: none;
}
I want to create an HTML application form and send it to applicants through email. each individual has to download the file, fill it out separately and send it back to me.
Is it possible to embed a save button and overwrite the changes permanently ? all I could find was save the changes locally (or as a separate file) which is not what I want. here is a simple form I could find on w3schools:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Save">
</form>
I found this code instead. all I had to do was change the output to html and style it the way I want. though it saves the changes as a new file but that's ok. I couldn't find anything else :
<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<style>
* {
box-sizing: border-box;
}
div {
padding: 10px;
background-color: #f6f6f6;
overflow: hidden;
}
input[type=text], textarea, select {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type=button]{
width: auto;
float: right;
cursor: pointer;
padding: 7px;
}
</style>
</head>
<body>
<div>
<!--Add few elements to the form-->
<div>
<input type="text" id="txtName" placeholder="Enter your name" />
</div>
<div>
<input type="text" id="txtAge" placeholder="Enter your age" />
</div>
<div>
<input type="text" id="txtEmail" placeholder="Enter your email address" />
</div>
<div>
<select id="selCountry">
<option selected value="">-- Choose the country --</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="USA">USA</option>
</select>
</div>
<div>
<textarea id="msg" name="msg" placeholder="Write some message ..." style="height:100px"></textarea>
</div>
<!--Add to button to save the data.-->
<div>
<input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
</div>
</div>
</body>
<script>
let saveFile = () => {
// Get the data from each element on the form.
const name = document.getElementById('txtName');
const age = document.getElementById('txtAge');
const email = document.getElementById('txtEmail');
const country = document.getElementById('selCountry');
const msg = document.getElementById('msg');
// This variable stores all the data.
let data =
'\r Name: ' + name.value + ' \r\n ' +
'Age: ' +age.value + ' \r\n ' +
'Email: ' + email.value + ' \r\n ' +
'Country: ' + country.value + ' \r\n ' +
'Message: ' + msg.value;
// Convert the text to BLOB.
const textToBLOB = new Blob([data], { type: 'text/plain' });
const sFileName = 'formData.txt'; // The file to save the data.
let newLink = document.createElement("a");
newLink.download = sFileName;
if (window.webkitURL != null) {
newLink.href = window.webkitURL.createObjectURL(textToBLOB);
}
else {
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
}
newLink.click();
}
</script>
</html>
I want to change width of a textfield when user enters more than 17 characters in that textfield using Javascript (if possible) otherwise by any other means.
I wrote a code to do the same, but it only changes width when user click outside the textfield after entering more than 17 characters. I want it to change width automatically when user enters more than 17 characters :
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onchange="widen()" value="" required>
</form>
onchange gets activated when the input looses focus, that's why it works when you click outside. On the other hand oninput will be triggered immediately when the value changes:
const nametf = document.getElementById('nametf');
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<html>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" oninput="widen()" value="" required>
</form>
</html>
You need to pass a self-reference to the function using this. I would also change on-change to on-key-up, because on-change waits for you to move focus away from the field.
onkeyup="widen(this)"
Then you need to parameterize the function with your variable "nametf"
function widen(nametf) {
// ...
}
Example
function widen(nametf) {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onkeyup="widen(this)" value="" required>
</form>
A better approach would be to use em units to expand the text are based on the current value.
initExpandingFields();
function initExpandingFields() {
Array.from(document.querySelectorAll('.expanding-field')).forEach(field => {
field.addEventListener('keyup', onFieldChange);
});
}
function onFieldChange(e) {
let field = e.target,
len = field.value.length;
field.style.width = (len * 0.667) + 'em';
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" class="expanding-field" name="name1" id="nametf" value="" required>
</form>
Try this:
var nametf = document.getElementById("nametf");
nametf.addEventListener("input", function(){
if(nametf.value.length > 17) {
nametf.size = "30";
} else {
nametf.size = "20";
}
});
#nametf {
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" size="20" value="" required>
</form>
I'm kinda new to programming and I cant solve this problem. The paragraphs are coming out like a stair case.
p
p
p
p
p
The p's are examples, but here is all the code I have done so far.
Keep in mind I'm not the best at css(I'm still learning)
All help would be appreciated
Please show me on how I an fix this problem, and tell me where in my code is this problem occurring.
I tried google but couldn't find anything...
var house = {}
function House() {
var msg = 'This house is painted'
var bath;
var bed;
var cook;
var Paint = document.getElementById('paint').value;
var square = document.getElementById('Square').value;
var bath = document.getElementById('bath').value;
var bed = document.getElementById('Bed').value
var cook = document.getElementById('Cook').value;
//Get paragraphs to store values
var paint = document.getElementById('isPaint');
var squareFeet = document.getElementById('sq_Feet')
var bathRoom = document.getElementById('bathroom')
var bedRoom = document.getElementById('BedRoom')
var kitchen = document.getElementById('kitchen');
if(Paint == 'Yes' || Paint == 'yes') {
house['isPainted'] = true;
paint.innerHTML = msg;
}
else if(Paint == 'No' || Paint == 'no') {
house['isPainted'] = false;
var msg = 'this house is not painted'
paint.innerHTML = msg;
}
else if(Paint == '') {
house['isPainted'] = undefined;
var msg = 'no details given';
paint.innerHTML = msg;
}
if(square != '' ) {
var squareFeetMsg = 'the house is';
squareFeet.innerHTML = squareFeetMsg + ' ' + document.getElementById('Square').value + ' square feet';
house['squareFeet'] = document.getElementById('Square').value
}else {
var squareFeetMsg = 'No Details Given';
squareFeet.innerHTML = squareFeetMsg;
}
}
body {
width: auto;
height: auto;
}
#houseDtails{
width: 350px;;
}
#container {
width: auto;
height: auto;
}
.houseDetails {
height: 0px;
float: right;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>House App</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div id="conatainer">
<div id="houseDtails">
<label for="paint">Is this house painted: </label><br>
<input type="text" id="paint" class="Detail" /><br>
<label for="Square">How many SQ feet does this have? :</label>
<input type="text" id="Square"><br>
<label for="bath">How many bathrooms does your house have</label>
<input type="text" id="bath"><br>
<label for="Bed">How many bedrooms dos your house have</label>
<input type="text" id="Bed"><br>
<label for="Cook">Does your house have a kitchen</label>
<input type="text" id="Cook"><br>
<input type="submit" name="" id="sub" class="subm" onclick="House()">
</div>
<div id="addDetailsToPage">
<p id="isPaint" class="houseDetails"></p>
<p id="sq_Feet" class="houseDetails"></p>
<p id="bathroom" class="houseDetails"></p>
<p id="Bedroom" class="houseDetails"></p>
<p id="Kitchen" class="houseDetails"></p>
</div>
</div>
<script src="House.js"></script>
</body>
The reason for the paragraphs rendering in that manner is result of float set on .houseDetails.
.houseDetails {
height: 0;
float: right;
}
This is because you have float: right; in your CSS for .houseDetails. Remove it and you should have your p aligned on the left below one another
So what I'm trying to do is change value of input with id championSpell[] whenever something from dropdown is chosen this code is generated dynamically so I'm always trying to get the closest/next input after select.
UPDATE: Full code below:
<script src="LeagueNotes/js/jquery.min.js"></script>
<script src="LeagueNotes/js/champions_list.js"></script>
<script src="LeagueNotes/js/jquery.validate.min.js"></script>
<style>
* { font-family:Arial; }
h2 { padding:0 0 5px 5px; }
h2 a { color: #224f99; }
a { color:#999; text-decoration: none; }
a:hover { color:#802727; }
p { padding:0 0 5px 0; }
input { padding:5px; border:1px solid #999; border-radius:4px; -moz-border-radius:4px; -web-kit-border-radius:4px; -khtml-border-radius:4px; }
</style>
<h2>
Add Another Champion
</h2>
<form name="second_form" id="second_form" action="#" method="POST" style="margin: 0;" >
<div id="p_scents">
<p>
<label for="p_scnts">
<input type="text" id="champion[]" size="20" list="champions" value="" placeholder="Enter Champion's name">
<datalist id="champions"></datalist>
Add General Change<a></a>
Add Spell<a></a>
</label>
</p>
</div>
<br/><input type="submit" value="submit">
</form>
<script>
for(var key in champions){
if(champions.hasOwnProperty(key)){
$('#champions').append('<option value="' + key + '">');
}
}
var config = {
fillAll: true
};
document.forms["second_form"].oninput = function(e) {
var champion = this["champion[]"];
//Force into array
if (champion[0] === undefined)
champion = [this["champion[]"]];
var reached = {
valid: 0,
unique: 0
};
var inputs = [].map.call(champion, function(n) {
return n.value
}).filter(function(n) {
return n.length
});
var valid = [].every.call(champion, function(n, i) {
n.setCustomValidity("");
if (config.fillAll) return (reached.valid = i, champions.hasOwnProperty(n.value));
else return n.value ? (
reached.valid = i,
champions.hasOwnProperty(n.value) > -1
) : true;
});
var unique = inputs.slice(0).sort().every(function(n, i, a) {
reached.unique = inputs.lastIndexOf(n);
return n != a[i - 1];
});
//Check for valid champions
if (!valid) {
champion[reached.valid].setCustomValidity("This is not a valid champion, please correct this field and resubmit.")
}
//Check for duplicates
if (!unique) {
champion[reached.unique].setCustomValidity("This champion has already been entered.")
}
this.checkValidity();
};
function change(x, dblchamp){
if(dblchamp===true){
if(x==="Passive"){x=0;}
if(x==="Q"){x=1;}
if(x==="Q2"){x=2;}
if(x==="W"){x=3;}
if(x==="W2"){x=4;}
if(x==="E"){x=5;}
if(x==="E2"){x=6;}
if(x==="R"){x=7;}
if(x==="R2"){x=8;}
}else if(dblchamp===false){
if(x==="Passive"){x=0;}
if(x==="Q"){x=1;}
if(x==="W"){x=2;}
if(x==="E"){x=3;}
if(x==="R"){x=4;}
}
console.log(x);
return x;
}
function val(elm) {
var championsWithExtraSpells = ["Aatrox", "Elise", "Fizz", "Heimerdinger", "Jayce", "Lee Sin", "Nidalee", "Rek'Sai","Twisted Fate"];
//var championName = $("#change").closest('input').val();
//var championName =$("#champion\\[\\]").val();
var championName = $(elm).closest("label").find("input").val();
//document.getElementById("champion[]").value;
console.log(championName);
if($.inArray(championName, championsWithExtraSpells)==-1){
var existsInArray = false;}
else{
var existsInArray = true;}
var d = $(elm).val();
// console.log(d);
//d = document.getElementById("change[]").value;
var spellname = document.getElementById("championSpell[]");
var z = champions[""+championName+""][change(d, existsInArray)];
test = $(elm).nextAll("input").first().val('test');
console.log(test);
//console.log(d+spellname);
//test.value=champions[""+championName+""][change(d, existsInArray)];
}
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents label').size() + 1;
var j =0;
$('body').on('click', '#addChampion', function() {
$('<p>Remove<br><label for="p_scnts"><input type="text" id="champion[]" size="20" list="champions" name="champion[]" value="" placeholder="Enter Champion\'s name" /><datalist id="champions"></datalist>Add General Change Add Spell<a></a></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('body').on('click', '#remScnt', function() {
if( i >2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
$('body').on('click', '#addGeneral',function() {
$(
'<p><label for="var"><textarea type="text" id="champion[]" size="20" name="GeneralChange[]" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> Remove Change</p>').appendTo($(this).next());
j++;
return false;
});
$('body').on('click', '#remVar',function() {
$(this).parent('p').remove();
return false;
});
$('body').on('click', '#addSpell',function() {
$(
'<p><select name="change[]" id="change[]" onchange="val(this)"><option value="Passive">Passive</option><option value="Q" selected>Q</option><option value="W">W</option><option value="E">E</option><option value="R">R</option></select><label for="var"><input type="text" id="championSpell[]" readOnly="true"><br><textarea type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> Add Change Remove Spell</p>').appendTo($(this).next());
return false;
});
});
</script>
It is be next sibling of the select, so use .next(), .closest() is used for finding the first ancestor element matching the given selector
function val(elm) {
var test = $(elm).next("input");
console.log(test);
test.val("test: " + elm.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="change[]" id="change[]" onchange="val(this)">
<option value="Passive">Passive</option>
<option value="Q" selected>Q</option>
<option value="W">W</option>
<option value="E">E</option>
<option value="R">R</option>
</select>
<input type="text" id="championSpell[]" readOnly="true">
But it is better to use jQuery event handlers
jQuery(function() {
$('select[name="change[]"]').change(function() {
$(this).next().val('t: ' + this.value);
}).change(); //the last change value is used to set the initial value on page load
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="change[]" id="change[]" onchange="val(this)">
<option value="Passive">Passive</option>
<option value="Q" selected>Q</option>
<option value="W">W</option>
<option value="E">E</option>
<option value="R">R</option>
</select>
<input type="text" id="championSpell[]" readOnly="true">
Use .next() .
var test = $(elm).next("input").val('test');
your code
function val(elm) {
var test = $(elm).next("input").val('test');
}
This one depends on how robust to changes in the DOM you want to be.
If you may have elements in between, the best option is
$(elm).nextAll("input").first().val('test');
nextAll() returns all following siblings of the element, used with "input" will return all following inputs only. Then apply first().
If that hierarchy may change, you would go up the DOM to a closest container with both elements, then search down again.
e.g. if these were in two standard <div class="form-group"> containers (ala a Bootstrap form):
$(elm).closest(".form-group").next(".form-group").find("input").first().val('test');
Update:
You should avoid inline event handlers with jQuery. They do not support all the same features jQuery handlers do and separate the event registration from the event handler for no good reason.
A practical example is here http://jsfiddle.net/TrueBlueAussie/mo94pv8k/
$('select').change(function () {
$(this).nextAll("input").first().val($(this).val());
});
Notes:
Your current ids are not useful for jQuery use as [] is reserved to indicate attribute selection in a jQuery selector. For example $('#change[]') is an invalid selector.