I'm using a select with options and i would like to use a form to submit the text of an option field into a database.
It's not working and I can't figure out why. the p-element changes its value (i only used it for debugging, i actually don't need it) but the hidden field stays empty.
can anybody help me out here?
function GetSelectedText(){
var e = document.getElementById("kunde");
var result = e.options[e.selectedIndex].text;
document.getElementById("title").textContent = result;
}
<select id="kunde" name="kunde" class="form-control" onchange="GetSelectedText()">
<option value="1">text for 1</option>
<option value="2">text for 2</option>
<option value="3">text for 3</option>
</select>
<p id="title">this text will be replaced</p>
<input name="title" type="hidden" id="title" value="">
Since the hidden field is an input field, change textContent to value.
Also, you can't have more than one element with the SAME ID, so get rid of the P element since you don't need it anyway.
This is probably because your p element has the same ID as the input element. HTML specifies that an ID must be unique. Something like this would work:
<p id="title">this text will be replaced</p>
<input name="title" type="hidden" id="titleInput" value="">
And the javascript:
// [...] rest of the function
document.getElementById("title").textContent = result;
document.getElementById("titleInput").value = result;
"textContent" has to be changed to "value".
Thanks for your help!
Related
I would like to pass the text portion (not the value) of a form Select-Option to a hidden text-input field within the same form when the user makes a selection.
I have explored some java and PHP 'examples' I found in my research, but none of them seem to work for me.
I have posted a raw example of the form to see if anyone can lead me to water. Any help wouold be appreciated.
HMTL
<html>
<head>
</head>
<body>
<form action="fruitBasket.php" method="post" enctype="multipart/form-data">
<select id="fruitSelector" name="fruitSelector">
<option value="0" selected="selected" disabled="disabled">Select Fruit</option>
<option value="1">Grapes</option>
<option value="2">Strawberries</option>
<option value="3">Peaches</option>
<option value="4">Blueberries</option>
</select>
<br>
<br>
<input type="text" class="hiddenField" name="hiddenField" placeholder="Selected fruit appears
here.">
</form>
</body>
</html>
It's not as easy as getting the selected option's value, which can be retrieved simply as selectElement.value, yet it's not difficult at all.
selectElement.options will give you an array of ALL the options inside the select element.
You will find the selected option's index to be selectElement.selectedIndex.
With that said, you can access to the selected option like this: selectElement.options[selectElement.selectedIndex].
Finally, you can get the text property like this: selectElement.options[selectElement.selectedIndex].text
Here's the code:
// THIS CONSTANT REPRESENTS THE <select> ELEMENT
const theSelect = document.getElementById('fruitSelector')
// THIS LINE BINDS THE input EVENT TO THE ABOVE select ELEMENT
// IT WILL BE EXECUTED EVERYTIME THE USER SELECTS AN OPTION
theSelect.addEventListener('input', function() {
// THIS IS HOW YOU GET THE SELECTED OPTION'S TEXT
let selectedOptText = theSelect.options[theSelect.selectedIndex].text
// FINALLY, THIS COPIES THE ABOVE TEXT TO THE INPUT ELEMENT:
document.querySelector('.hiddenField').value = selectedOptText;
})
<form action="fruitBasket.php" method="post" enctype="multipart/form-data">
<select id="fruitSelector" name="fruitSelector">
<option value="0" selected="selected" disabled="disabled">Select Fruit</option>
<option value="1">Grapes</option>
<option value="2">Strawberries</option>
<option value="3">Peaches</option>
<option value="4">Blueberries</option>
</select>
<br>
<br>
<input type="text" class="hiddenField" name="hiddenField" placeholder="Selected fruit appears
here.">
</form>
well if you want to pass the text portion you should add the names as the values too like
---
code
---
<option value="Grapes">Grapes</option>
<option value="Strawberries">Strawberries</option>
---
code
---
Here is my code.
//I want to pass field1 selected option's title through onkeyup
function select_data(field1) {
alert(field1);
}
<select id="field1" onchange="select_data(this.options[this.selectedIndex].title)">
<option value="213" title="1">A</option>
<option value="214" title="12">AB</option>
<option value="215" title="13">AC</option>
</select>
<input type="text" id="vat" onkeyup="select_data()" />
I want to get the selected option's title by onkeyup from text field.
Advance thanks for help.
let selText = document.getElementById('field1').options[document.getElementById('field1').selectedIndex].title
You want this:
<script>
//I want to pass field1 selected option's title through onkeyup
function select_data(field1) {
//alert(field1);
alert(field1.options[field1.selectedIndex].title);
}
</script>
<select id="field1" onchange="select_data(this.options[this.selectedIndex].title)">
<option value="213" title="1">A</option>
<option value="214" title="12">AB</option>
<option value="215" title="13">AC</option>
</select>
<input type="text" id="vat" onkeyup="select_data(document.querySelector('#field1'))" />
You can achieve this by selecting the select inside of the function instead of passing all that parameter by inline HTML (which is not advisable).
So, use querySelector() get the select, get the current selected index and title, show it.
THe below method can be called from everywhere and it will work, since all job of getting the title is inside the function
Note: Always when possible, avoid assing listeners in the HTML, it's not the right place and it is also obstrusive and not easy to maintain, opt for adding listeners in the JS/script part, also avoid passing parameters in HTML inline listeners.
//I want to pass field1 selected option's title through onkeyup
function select_data() {
let select = document.querySelector("#field1")
let title = select.options[select.selectedIndex].title;
console.log(title)
}
<select id="field1" onchange="select_data()">
<option value="213" title="1">A</option>
<option value="214" title="12">AB</option>
<option value="215" title="13">AC</option>
</select>
<input type="text" id="vat" onkeyup="select_data()" />
I am using the datalist HTML property to get a drop down inout box:
<input list="orderTypes" value="Book">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
The problem is that now I have to clear the input box to view all the drop down values. Is there a way to have a default value but still view all the values in the datalist when the drop down icon is clicked?
I have the same problem.
I just simple added placeholder with the default data.
In your example:
<input list="orderTypes" name="orderType" id="orderType" placeholder="Book" />
I listen submit event. If the input value is empty, I use Book as default value, otherwise I use the given value...
$("#mySubmitButton").click(() => {
// use event prevent here if need...
const orderType = $("#orderType").val() || "Book";
console.log(orderType);
});
I know of no way to do this natively. You could make a "helper" div to use when the input field has value. I couldn't hide the native drop down so I renamed the ID. Uses jQuery.
html
<input list="orderTypes" id="dlInput">
<div id="helper" style="display:none;position:absolute;z-index:200;border:1pt solid #ccc;"></div>
<datalist id="orderTypes" style="z-index:100;">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
script
$(function(){
// make a copy of datalist
var dl="";
$("#orderTypes option").each(function(){
dl+="<div class='dlOption'>"+$(this).val()+"</div>";
});
$("#helper").html(dl);
$("#helper").width( $("#dlInput").width() );
$(document).on("click","#dlInput",function(){
// display list if it has value
var lv=$("#dlInput").val();
if( lv.length ){
$("#orderTypes").attr("id","orderTypesHide");
$("#helper").show();
}
});
$(document).on("click",".dlOption",function(){
$("#dlInput").val( $(this).html() );
$("#helper").hide();
});
$(document).on("change","#dlInput",function(){
if( $(this).val()==="" ){
$("#orderTypesHide").attr("id","orderTypes");
$("#helper").hide();
}
});
});
jsFiddle
Is this what you trying to do?
var demoInput = document.getElementById('demoInput'); // give an id to your input and set it as variable
demoInput.value ='books'; // set default value instead of html attribute
demoInput.onfocus = function() { demoInput.value =''; }; // on focus - clear input
demoInput.onblur = function() { demoInput.value ='books'; }; // on leave restore it.
<legend>(double) click on the input to see options:</legend>
<input list="orderTypes" id="demoInput">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
The only "problem" here is that in order to see the options the user have to click the input again so it's like "double-click the input to see options".
Hope that helps.
I would use input's placeholder attribute along with a Javascript code that'll make sure that the field isn't empty upon submission.
Obviously this is just an example, you'll have to modify the submission event.
document.getElementById('submitButton').addEventListener('click', function() {
let inputElement = document.getElementById('myInput');
if (!inputElement.value) {
inputElement.value = 'Book';
}
});
<input id="myInput" list="orderTypes" placeholder="Book">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
<input id="submitButton" type="submit">
I've menaged to get what You described with just <select> + <option> tags instead of <input> + <datalist>:
<select name="sortBY">
<option value="Book">Book</option>
<option value="Copy">Copy</option>
<option value="Page">Page</option>
</select>
Putting it all inside <form></form> tags will send it eg. with POST method with $_POST['sortBY'] value.
If this helps at all:
$('#grouptext').val($('#grouplist option#48').attr('value'));
where '#grouptext' is your text input to which your datalist '#grouplist' is attached, and #48 is the ID you're looking to "pre-select".
here's what my data list looks like, for clarity
worked for me.
In Chrome's console it shows up like this with "option#115", which corresponds to the correct text in the datalist for that "id" (being 115)
set id for your input and with js set default value
<script>
setTimeout(() => {
document.getElementById('orderTypes').value = "Book";
}, 100);
</script>
onchange I want to get the select option custom attribute and set to the other input's value. Somehow I cannot get the course_price in the input onchange of the select. It only shows the first option value in the input only.
function selectFunction(e) {
var value1 = $("#test").data('typeid'); //to get value
document.getElementById("money").value = value1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" onchange="selectFunction(event)">
<option id="test" data-typeid="<?php echo $row1['course_price']?>"
value="<?php echo $row1['course_id']?>"><?php echo $row1['course_name']?>
</option>
</select>
<input type="number" value="" id="money" class="form-control">
The issue is because the data-typeid attribute is on the selected option, not the select, so your jQuery code is looking at the wrong element. You can fix this by using find() and :selected to get the chosen option before reading the data attribute from it.
Also note that on* attributes are very outdated. You should be using unobtrusive event handlers, something like this:
$(function() {
$('select.form-control').change(function() {
var typeId = $(this).find('option:selected').data('typeid');
$("#money").val(typeId);
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option data-typeid="1111" value="courseId1">courseName1</option>
<option data-typeid="2222" value="courseId2">courseName2</option>
</select>
<input type="number" value="" id="money" class="form-control">
In your question you are using #test which is id for all options and so it will always consider first occurance of id test. So do not use same id multiple times on the same DOM, change it to class="test" if you need it, otherwise, you need to target the selected option, and it will not need any id or class. Check here:
var type_id = $('select option:selected').attr('data-typeid');
and assign the variable to input box:
document.getElementById("money").value =type_id;
So the entire updated function will be like this:
function selectFunction(e) {
var type_id = $('select option:selected').attr('data-typeid'); //to get value
document.getElementById("money").value =type_id;
}
Another way to make it:
$(document).on('change', 'select.form-control', function() {
var r = $('select.form-control option[value="'+$(this).val()+'"]').attr("data-typeid")
$("#money").val(r)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option selected disabled>-- Select one --</option>
<option data-typeid="1111" value="courseId1">courseName1</option>
<option data-typeid="2222" value="courseId2">courseName2</option>
</select>
<input type="number" value="" id="money" class="form-control">
Having this fieldset:
<fieldset>
<legend>[*death]</legend>
<select name=death style="width: 120px">
<option value=Dead>[*died]
<option value=NotDead>[*alive]
<option value="" selected>-
</select>
</fieldset>
i want to set the [2].value to "-".
i have tried without any success:
document.getElementsByName('death')[2].checked = 'true';
document.getElementsByName('death')[2].value = '-';
Same kind of code works fine for radio boxes, checked boxes or other inputs in the form. How to do it with the option select (which is not an input)?
Thanks
[EDIT] of course, appropriate fieldset is:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
thanks.
It's a little bit unclear what you're asking. Are you simply asking to make the option at index 2 selected?
document.getElementsByName('death')[0].selectedIndex = 2;
Or, are you asking to change the value of option at index 2?
var d = document.getElementsByName('death')[0];
d.options[2].value = '-';
You need to manipulate the selected property of your select object, try
document.getElementsByName('death')[0].selectedIndex = 1;
In english, this reads "set the selected option to the second option in the first element in the document with name 'death'".
Fixing your HTML might make the results of your javascript more predictable. Close your tags, quote your attribute values, as follows:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
you can do this using jQuery... it's easy...
j("#death").val(2)
document.getElementsByName('death')[2] returns the third element named death - but you only have one element with that name. Instead, you want the first element named death (i.e. the one at index 0), and then you want its third option: document.getElementsByName('death')[0].options[2].value = ...
Here's an alert example of how to access your specific option values with getElementsByName
alert(document.getElementsByName('death')[0].options[0].value); // will return Dead
alert(document.getElementsByName('death')[0].options[1].value); // will return NotDead