I have a datalist with "values" and "data-values". I've managed to display only values (Auckland, Bangkok) in a select. That works as needed.
But I need to pass "data-value" to another input at the moment when option (select) is changed.
I have almost zero programming skills. I have tried to ad ´attr("data-value")´ and ´$(this).data("id")´ to my code, but it doesnt work. Another input is either empty, or "undefined" is displayed, when I change value from datalist.
<input list="shop_ids" id="listshops" name="shop_id" onchange="this.form.f_shop_hidden.value=this.form.shop_id.value" />
<datalist id="shop_ids">
<option data-value="1" value="Auckland"></option>
<option data-value="2" value="Bangkok"></option>
<option data-value="3" value="Sydney"></option>
</datalist>
<!-- Text field, where data-value should be displayed -->
<input type="text" name="f_shop_hidden" id="f_shop_hidden">
Once I click on a datalist and select Auckland, "Auckland" (value) is displayed in "f_shop_hidden" input. I need to display number "1" there (data-value).
I have been trying to crack this nut the whole week. Thank you very much. :)
You can do something like this:
const select = this.form.shop_id;
const dataValue = select.options[select.selectedIndex].dataset.value;
console.log(dataValue);
You can do something like this :
$('#listshops').on('input', function() {
const value = $(this).val();
const data_value = $('#shop_ids [value="' + value + '"]').data('value');
document.getElementById("f_shop_hidden").value = data_value;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input list="shop_ids" id="listshops" name="shop_id"/>
<datalist id="shop_ids">
<option data-value="1" value="Auckland"></option>
<option data-value="2" value="Bangkok"></option>
<option data-value="3" value="Sydney"></option>
</datalist>
<!-- Text field, where data-value should be displayed -->
<input type="text" name="f_shop_hidden" id="f_shop_hidden">
I edited the answer for data list.
Call a JavaScript function when input Changes. There you could access the data list id and then assign to the textbox.
<!-- HTML Part -->
<input list="shop_ids" id="listshops" name="shop_id" onchange="idDisplay();" />
<datalist id="shop_ids">
<option data-value="1" value="Auckland"></option>
<option data-value="2" value="Bangkok"></option>
<option data-value="3" value="Sydney"></option>
</datalist>
<!-- Text field, where data-value should be displayed -->
<input type="text" name="f_shop_hidden" id="f_shop_hidden">
<!-- JAVASCRIPT Part -->
<script>
function idDisplay()
{
var element_input = document.getElementById('listshops');
var element_datalist = document.getElementById('shop_ids');
var opSelected = element_datalist.querySelector(`[value="${element_input.value}"]`);
var id = opSelected.getAttribute('data-value');
document.getElementById("f_shop_hidden").value = id;// Assigns data-value to textbox
}
</script>
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">
I've got a dropdown setup going on in which the user enters an input value, chooses a calculation to perform on that number from a dropdown, then a function displays the result.
What I would like is to add more 'values' to the dropdown, so when an option is selected from the list, it can also, say, display some text stored in the list, or some other information. Right now I can return the selected option's value (.value) and use the option's name (.text) to perform functions, but is there any more data I can add to each selection to be used later?
<html>
<head>
<script language="JavaScript">
function myfunction(form)
{
var i = parseFloat(form.Input.value, 10);
var e = document.getElementById("calculationList");
var strUser = e.options[e.selectedIndex].value;
form.Output.value = strUser*i;
}
</script>
</head>
<body>
<form>
Input Number:
<INPUT NAME="Input" SIZE=15>
Make a selection:
<select id="calculationList" onchange="myfunction(form)">
<option></option>
<option value="2">Double It</option>
<option value="3">Triple It</option>
<option value="10">Multiply It By ten</option>
</select>
Output Number:
<INPUT NAME="Output" SIZE=15>
</FORM>
</body>
</html>
Basically you may attach data attribute to your options like that:
<select id="calculationList">
<option></option>
<option value="2" data-aaa="10">Double It</option>
<option value="3" data-aaa="20">Triple It</option>
<option value="10" data-aaa="30">Multiply It By ten</option>
</select>
And later get the content of the attribute:
var dropdown = document.getElementById("calculationList");
dropdown.addEventListener("change", function() {
console.log(dropdown.options[dropdown.selectedIndex].getAttribute("data-aaa"));
});
jsfiddle -> http://jsfiddle.net/pzKrr/
Edit:
If you want to implement my solution remove onchange="myfunction(form)" from the select tag. After that add the following code just after that myfunction
window.onload = function() {
var dropdown = document.getElementById("calculationList");
dropdown.addEventListener("change", function() {
console.log(dropdown.options[dropdown.selectedIndex].getAttribute("data-aaa"));
});
};