Reputation: 895
Here's my code:
$(".dropdowncitymenu").change(function () {
$("#sCity").val($(this).val());
$("#sRegion").val($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div style="font-size:12px;margin-bottom:20px;">City Field
<input placeholder="CITY" class="input-text" type="text" id="sCity" />
</div>
<div style="font-size:12px">Region Field
<input placeholder="REGION" class="input-text" type="text" id="sRegion"/>
</div>
<div style="margin-top:20px;width:100%;display:block;">
<select id="dropdowncities" class="dropdowncitymenu">
<option value="">Select a Location...</option>
<option value="Los Angeles (California)">Los Angeles (California)</option>
<option value="Miami (Florida)">Miami (Florida)</option>
</select>
</div>
How can i make it using jquery or even plane javascript, so when i select a location from the select box, to pass the city into the city input field and the region into the region input field accordingly ?
Upvotes: 1
Views: 1379
Reputation: 337626
The simplest way to achieve this would be to separate the city/state in the value
attribute by a single character which you can then split()
to create an array. Then you can set the elements of the resulting array as the values of the text fields. In the example below I used ,
as the delimiting character, but anything will work so long as it won't be used within a value itself. Try this:
$(".dropdowncitymenu").change(function() {
var location = $(this).val().split(',');
$("#sCity").val(location[0]);
$("#sRegion").val(location[1]);
});
#container {
margin-top: 20px;
width: 100%;
display: block;
}
#city {
font-size: 12px;
margin-bottom: 20px;
}
#region {
font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="city">City Field
<input placeholder="CITY" class="input-text" type="text" id="sCity" />
</div>
<div id="region">Region Field
<input placeholder="REGION" class="input-text" type="text" id="sRegion" />
</div>
<div id="container">
<select id="dropdowncities" class="dropdowncitymenu">
<option value="">Select a Location...</option>
<option value="Los Angeles,California">Los Angeles (California)</option>
<option value="Miami,Florida">Miami (Florida)</option>
</select>
</div>
Also note that I placed the CSS rules in to an external stylesheet. You should avoid inline styling where possible.
Upvotes: 1