Change span text with selected option - javascript

I am on beginning of the coding life. I am trying to change text in span with selected option, but it gives me values not texts. For example, when I select the bus option, I want it to shows me the "bus" text. I do not want value number. Thanks in advance.
<select id="vehicles" onchange="showChange()">
<option value="1">Bus</option>
<option value="2">Car</option>
<option value="3">Plane</option>
</select>
<span id="vehicle"></span>
<script>
function showChange(){
var selected_vehicle = document.getElementById("vehicles").value;
document.getElementById("vehicle").innerText = selected_vehicle;
}
</script>

You can first pass this keyword to the function then get the text using selectedIndex of option.
<select id="vehicles" onchange="showChange(this)">
<option value="1">Bus</option>
<option value="2">Car</option>
<option value="3">Plane</option>
</select>
<span id="vehicle"></span>
<script>
function showChange(el){
var selected_vehicle = el.options[el.selectedIndex].text;
document.getElementById("vehicle").innerText = selected_vehicle;
}
</script>

If you keep the inline declarations from your HTML ( generally the preferred approach ) you can assign your event handlers in a separate file. Also, as a point of note - if you submit the form data in the traditional manner ( rather than with AJAX etc ) then the select element needs a name - an ID will NOT appear in the REQUEST array!
document.querySelector('select[name="vehicles"]').addEventListener('change',e=>{
e.target.nextElementSibling.textContent=[ e.target.value, e.target.options[e.target.options.selectedIndex].text].join(' ')
})
<select name='vehicles'>
<option selected hidden disabled>Select mode of transport
<option value='1'>Bus
<option value='2'>Car
<option value='3'>Plane
</select>
<span id='vehicle'></span>

Related

How can i put an option value in a input text after clicking a button?

I'm not familiar with javascript and jQuery and I'm asking you.
I would like the code of a product to be selected, once I have selected it from the select dropdown, I click the button and it should add the value in an input box text, that I have created, so that I can also accumulate more codes of more products.
Keep in mind that once the button is clicked, the same value is no longer added indefinitely but that it is possible to choose another code and add it next to the one already present in the input text.
I don't know if it is more practical to use the <input type = "submit"> tag instead of the button tag to send or in this case transfer the selected text from the select to a text form.
You would save my life if you could please complete this action for me with javascript or jQuery :)
<select class="select" id="select-code">
<option value="">Select a code</option>
<option value="value1">Code 1</option>
<option value="value2">Code 2</option>
<option value="value3">Code 3</option>
<option value="value4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input name="my-quote" type="text" placeholder="code1,code2...">
First of all, it seems that you are complete beginner. so you should learn DOM api to learn how to manipulate the window.
Anyway here is the code to do so which you want;
document.getElementById('code-btn').onclick = () => {
let e = document.getElementById('select-code');
document.getElementById('input').value = e.options[e.selectedIndex].text;
}
<select class="select" id="select-code">
<option value="">Select a code</option>
<option value="value1">Code 1</option>
<option value="value2">Code 2</option>
<option value="value3">Code 3</option>
<option value="value4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input id='input' name="my-quote" type="text" placeholder="code1,code2...">
document.getElementById('code-btn') gets the element with id 'code-btn'. As that is a button, we can use onclick property which will will take a function and that function will be called when it is clicked.
Inside that function, i am simply getting the input field and setting its value to the text of the selected option from dropdown.
I think the code here is self-documented.
This isn't a direct answer to your question, but an alternative solution. If possible for your situation, I would consider using <select multiple>: the select tag with the "multiple" attribute. It's a native HTML feature that allows the user to select multiple options from the list. I don't know how you're submitting the form data, but if using a <form> tag then the form's data will include which values have been selected.
Tutorial about select multiple
<label for="select-code">Select a code</label>
<select class="select" id="select-code" multiple>
<option value="value1">Code 1</option>
<option value="value2">Code 2</option>
<option value="value3">Code 3</option>
<option value="value4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input id='input' name="my-quote" type="text" placeholder="code1,code2...">
This is actually very simple and might be used as beginers excercise, so I'm gonna give you a brief walkthrough of how I would solve it:
register button onClick event
read selected value
add it to the placeholder attribute
so something like this (not tested at all)
//button click event
$("#code-btn").click(function (event) {
//in element #select-code
var textToAdd = $('#select-code')
//find element with pseudo selector :selected
.find(":selected")
//get its inner text
.text();
//check if input already contains the text here, if not
if (!$("input").attr("placeholder").includes(textToAdd)) {
//into input element
$("input")
//into attribute placehoder
.attr("placeholder",
//insert original text //insert colon //insert new text
$("input").attr("placeholder") + ", " + textToAdd)
}
});
function myFunction() {
var newText = document.getElementById('select-code').value
var input = document.getElementById('my-quote')
if (input.value == '') input.value = newText
else input.value = input.value + ', ' + newText
}
<select class="select" id="select-code" onchange='myFunction()'>
<option value="">Select a code</option>
<option value="Code 1">Code 1</option>
<option value="Code 2">Code 2</option>
<option value="Code 3">Code 3</option>
<option value="Code 4">Code 4</option>
</select>
<button id="code-btn">submit to form</button>
<input id="my-quote" type="text" placeholder="code1,code2...">

Get a select box by name and set another select box by same name?

I am building a fairly complex form-- I need to copy some data between one and another and I am using jQuery to do this. The only road block I am running into is setting the state.
I have two drop downs, one us using the full state name as the value and the other is using the state abbreviation as the value. The names are the same-
so on form 1 it looks like
<option value="Illinois">Illinois</option>
and form 2 it looks like
<option value="IL">Illinois</option>
Each form has its own unique css selector. How can I set the selected value of form 2 to match what is in form 1 using jQuery?
I do not have any control over the forms, just need to manipulate the input. Have tried using a name selector in jQuery, but I'm not having any luck.
Thank you.
You can do something like this
<select id="fullName">
<option value="Maryland" data-abbr="MD">Maryland</option>
<option value="Illinois" data-abbr="IL">Illinois</option>
<option value="Delaware" data-abbr="DE">Delaware</option>
</select>
<select id="abbr">
<option value="MD">Maryland</option>
<option value="IL">Illinois</option>
<option value="DE">Delaware</option>
</select>
And your jQuery
$('body').on('change', '#fullName', function(){
var abbr = $(this).find('option:selected').data('abbr');
$('#abbr').val(abbr);
});
Try this
<form id="form1" name="form1">
<select name="states" onchange="changeselect(this)">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
</form>
<form id="form2" name="form2">
<select name="states">
<option value="opt1">option1</option>
<option value="opt2">option2</option>
<option value="opt3">option3</option>
<option value="opt4">option4</option>
<option value="opt5">option5</option>
</select>
</form>
function changeselect(elem)
{
var value1 = $(elem).val();
$('#form2 select option').removeAttr('selected');
$('#form2').find('select option').each(function(){
var value2 = $(this).html();
if(value1 == value2)
{
var selected = $(this).attr('value');
$('#form2 select').val(selected);
}
});
}
If you create 2 arrays which exactly correspond with one another:
var StateNames = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];
var StateAbbreviations = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];
You can:
get the value from the first option list;
find that value's index in the first array; (hint: use indexOf)
use the same index to find out what the corresponding abbreviation is in the second array;
use the returned abbreviation to locate the correct option in the second option list

Select box not returning expected value

I have a form that will display different options depending on the first select box.
If option 1 is selected then a second dropdown will be shown with an option pre selected. If option 2 is selected then a different dropdown with two options will be shown.
The two new dropdowns will have the same ID and name for passing the option through to the backend but it keeps returning wrong values. Here is a
jsbin
<p class="input_title">I will use:</p>
<select name="js-rp-use" class="signup-select js-rp-use" id="rp-use" class="signup-select">
<option value="">Select Plan</option>
<option value="SOLO">Manage my own items</option>
<option value="OTHER">Manage others items</option>
</select>
<div class="js-rentpro-plan-solo">
<p class="input_title">System Plan:</p>
<select name="plan_id" id="plan_id" class="signup-select">
<option value="-1">Select plan</option>
<option value="1" selected>Plan Solo</option>
</select>
</div>
<div class="js-rentpro-plan-other">
<p class="input_title">System Plan:</p>
<select name="plan_id" id="plan_id" class="signup-select">
<option value="-1">Select plan</option>
<option value="2">Plan Business</option>
<option value="3">Plan Max</option>
</select>
</div>
<br><br><br>
<button type="button" id="submit">Submit</button>
// jquery
$("div[class^='js-rentpro-plan-']").hide();
$('.js-rp-use').change(function(){
$('#js-rp-plan-text, .js-rentpro-plan-solo, .js-rentpro-plan-other').hide();
if( $(this).val() == 'SOLO' ){
$('.js-rentpro-plan-solo').show();
} else if( $(this).val() == 'OTHER' ){
$('.js-rentpro-plan-other').show();
} else {
$('#js-rp-plan-text').show();
}
});
$('#submit').click(function(){
console.log( 'plan id is: ' + $('#plan_id').val() );
});
ID's must be unique. Instead of using the same id, use class.
The reason for you getting the wrong value is you're using $('#plan_id').val() It will return the value for the first match it finds.
EDIT:
To get the correct value with the current structure you can use:
var vl = $(this).siblings('div:visible').find('select').val()
console.log('plan id is: ' + vl );
But I suggest you modify the structure, wrap them in a form, give your select containers same class, so you'll have access to them more easily.
jsfiddle DEMO
your selector will always use the first match, regardless of you using element, class or id. Or using the class you can:
$('.signup-select:visible').val()

Sending both the value and key of an option box as parameters?

I want to send both the value and key of the option box when I submit a form. I feel like this should be pretty simple, but I'm unsure how to do it. Below is a snippet from my form to demonstrate what I'm referencing:
<form name='form' onSubmit="return checkForm();" action="../servlet/AccountRequest">
<select name="type1">
<option value="1">Option A</option>
<option value="2">Option B</option>
</select>
<br/><input type="button" id="Submit" onclick="checkForm(this.form)" value="Request" />
<input type="reset" value="Cancel"/>
</form>
​
In a normal scenario, if I selected "Option A" in the drop-down box, I would want to send the value, or "1". However, I want to actually send the value AND key of the selection, in this case both "1" and "Option A".
In my case, I call a checkForm() JavaScript function that validates form input (there are other fields, like First Name, Last Name, Email Address, and Password), which then forwards the parameters to a Java class (AccountRequest). I'm sure there is a way to store the key as a variable when the "Request" button is clicked, I just don't know how.
Any help would be much appreciated!
You could play with a jSON representation of your data:
<select name="type1">
<option value="{'1':'Option A'}">Option A</option>
<option value="{'2':'Option B'}">Option B</option>
</select>
It might not be the approach you were expecting, but you could send the key/value pair as your value and parse it when you receive it server-side.
<select name="type1">
<option value="1,Option A">Option A</option>
<option value="2,Option B">Option B</option>
</select>
In HTML, this is impossible: the data contributed by a select element is defined to be the value attribute of the selected option, when present (otherwise the content of the selected option element).
In JavaScript, it would be pretty easy, once you have decided how the content (“key” in your description) should be passed. At the simplest, you could append the content to the value attribute, with some separator between the strings; then you would have to parse that server-side, but that would be simple too.
However, it is part of the very idea of option elements that the content is the visible string in the user interface, understandable to the user, and the value attribute is the machine-readable easily processable data. In good design, they are kept as separate, not combined; the server should only need the data from the value attribute; otherwise there is a design flaw that should be fixed.
You could add this code to get the text of your selected <option> tag in your checkform function:
var select = document.getElementsByName("type1")[0]; // get select element - simpler if it has an ID because you can use the getElementById method
var options = select.getElementsByTagName("option"); // get all option tags within the select
for (i = 0; i < options.length; i++) { // iterate through all option tags
if (options[i].value == select.value){ // if this option is selected
var key = options[i].innerHTML; // store key of selected option here
}
}
DEMO, which tells you the key that's selected
Use a compound value, then parse it out on the server:
<option value="1_A">Option A</option>
you can send the value with an input type hidden
1.-choose the default value:
<input type="hidden" id="theValue" name="type1Value" value="Option A"/>
2.-add onChange function to your select, which changes previous hidden value
<select id="type1" name="type1" onChange="updateValue()">
<option value="1">Option A</option>
<option value="2">Option B</option>
</select>
assuming you are using jQuery:
function updateValue(){
var value= $('#type1').find(":selected").text();
$('#theValue').val(value);
}
so the value of the select will be sent in type1Value variable, EASY!!
using React js
I want to get two values from the option at the same time
so, I use the Split method
var string = "0,1";
var array = string.split(",");
alert(array[0]);
I create a sting on option
const getKioskSelectedUsageType=(e)=>{
let sl = e.target.value
let array = sl.split(",")
console.log("check :- ",array[1] )
}
<select
id=""
className="form-control"
value={kioskSelect}
aria-label="kioskSelect"
name="kioskSelect"
title="kioskSelect"
onChange={(e) => getKioskSelectedUsageType(e)}
style={{ color: "#495057" }}
>
<option value="">Select Kiosk</option>
{kioskConfiData.map((item, i) => {
return (
<React.Fragment key={i}>
<option value={`${item.kioskid},${item.language}`}>
{item.location}
</option>
</React.Fragment>
);
})}
</select>

How do I stop the content with onChange?

I have this problem with onchange:
<form class="form" action="javascript:update();">
<select name="calendar" id="calendar" onchange = "update(); location.href = 'http://orario-preghiera.it/newsito/try.html?id=' + this.value">
<option value = "x" selected="selected">Bologna</option>
<option value = "y1">Other city</option>
<option value = "y2">Other city</option>
<option value = "y3">Other city</option>
<option value = "y4">Other city</option>
<option value = "y5">Other city</option>
</select>
</form>
When I choose a option, from x (i.e. selected) to y, the URL changes to y, and is displays the contents of y for a few seconds and then returns to x (selected), but the link changes and remains.
How can I stop the content?
Thanks!
Your problem is that update() function is called on every page load. Seems from the debugger that it happens from the onchange method. Anyways, I'd suggest you to change the selected attribute to the active town when the page is first requested, so that you wouldnt default to the same or remove the update from onchange on the select tag.
Also, why the hell do you have jQuery loaded twice and then you override the $ method, rendering jQuery useless.

Categories

Resources