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

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>

Related

Change span text with selected option

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>

Get Select Array Value on JavaScript

I want to get Select Element Array value using javascript but i cant get i get all other element value like text etc but cant get select array value.
Select element in My Html code
<select name="abc[]"></select>
<select name="abc[]"></select>
and Javascript Code for get Select Value
document.querySelectorAll("input[name='abc[]']")
but cant get its value, Help me out of this
First: use select, not input in your css selector. Here's a snippet to find the value and text of the selected option:
const selectedOption = document.querySelector(`select[name='abc[]'] > option:checked`);
console.log(`Value: ${selectedOption.value}, Text: ${selectedOption.textContent}`);
<select name="abc[]">
<option value="1">text 1</option>
<option value="2">text 2</option>
<option value="3" selected>text 3</option>
<option value="4">text 4</option>
</select>
Try this : [1]: https://jsfiddle.net/phiphophe/c7a3gdtn/1/
var matches = document.querySelectorAll("select[name='abc[]']");
for(var select of matches){
console.log(select.value);
}

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

How to store a javascript function value inside a php variable

function check_val(val) {
document.getElementById("select_action")=val;
alert(val);
return val;
}
this is my javascript function
<select name='select' id='select' onchange='check_val(this.value)'>
<option value='0'><------select------></option>
<option value='4'>apple</option>
<option value='5'>mango</option>
<option value='6'>berry</option>
</select>
<?php <input type=hidden name='select' value=???> //by using javascript I need the value
this is my select tag now I want to put the values inside a hidden field
a few things here:
to post into a different page from javascript, you could use .post(...) or $.ajax({ type: 'post',... there's an example of the latter in the answer here
hidden html inputs are useful for storing values, but they do not need to be inside php tags, which I think is what adeneo was pointing out
your hidden input does not have an id, only a name, and the name is the same as your select box
you are trying to reference something using getElementById("select_action"), but you don't have anything with that id.
Pam, you don't need php at all for this, just set the value of the hidden input in your javascript function with the manipulated val
function check_val(val) {
val++; // do things to val (add 1)
document.getElementById("hidden_input").value=val; //set value in the hidden input
return;
}
Make sure your hidden input has an ID
<select name="select" id="select" onchange="check_val(this.value)">
<option value='0'><------select------></option>
<option value='4'>apple</option>
<option value='5'>mango</option>
<option value='6'>berry</option>
</select>
<input id="hidden_input" type="hidden" name="hidden_input" value="0">
On the page that you are posting to, you will access the data in PHP with
echo $_POST['hidden_input'];
// or
echo $_REQUEST['hidden_input'];

Drop updating a hiddenfield with an unrelated value

If you wanted to change the value of the hidden field to something not in the value of the dropdown like so
<form>
<select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
<option value="foo">One - 42</option>
<option value="bar">Two - 40</option>
<option value="wig">Three - 38</option>
</select>
<input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
</form>
And i want to pass (if two selected) dropdown="bar" and hiddenInput="40"
The value has to be passed but needs to effect the hiddenfield.
What do you think? Would you need to If then? or could you have it something like
<form>
<select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
<option value="foo" onchange="set hiddenInput - 42">One - 42</option>
<option value="bar" onchange="set hiddenInput - 40">Two - 40</option>
<option value="wig" onchange="set hiddenInput - 38">Three - 38</option>
</select>
<input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
</form>
You have the right idea with the onchange attribute. Your function could look like:
function changeHiddenInput(mySelect) {
var map = {foo: "42", bar: "40", wig: "38"};
var index = mySelect.selectedIndex;
var value = mySelect.options[index].value;
var hiddenInput = document.getElementById("hiddenInput");
hiddenInput.value = map[value];
}
The map variable there maps each option's value on to what the hidden attribute should be set to.
I'd keep the mapping on the server rather then trying to handle it client side.
Forget the hidden input. Just look up the value based on the value of the dropdown after the data reaches the server.
Unfortunately, you'd need the IF statement. You can use the onclick event for the option tags in Firefox and probably other browsers, but in IE you can't set any events on the option elements, only on the select element.

Categories

Resources