Set Form Input Attribute by Selected Option Attribute - javascript

My goal is to add the value and attribute(s) of the options in a select field to an input element.
The options are generated dynamically - it would be feasible for me to give each a unique ID if that would help divine a solution.
I have the following code ( here's my fiddle ):
HTML
<select size="3" width="220" style="width:220px" id="select_trainer" multiple="yes">
<option value="1" name="unique-code-1" id="unique-id-1">Jillian</option>
<option value="2" name="unique-code-2" id="unique-id-2">James</option>
<option value="3" name="unique-code-3" id="unique-id-3">Jean</option>
</select>
<input value="" name="" id="save_select_profile" checked="checked"/>
JAVASCRIPT
document.getElementById('select_trainer').onchange = function () {
document.getElementById('save_select_profile').value = event.target.value;
document.getElementById('save_select_profile').setAttribute('name', event.target.name);
}
The javascript (from here and here) does a great job of setting the value of the input field to match the option that is selected.
But my addition - document.getElementById('save_select_profile').setAttribute('name', event.target.name); - does not set the selected-option name attribute to the input.
I found that if the <select> element has a name value set, that value is added to input instead.
How do I pass the selected, child element name value to the input field?

Updated Fiddle
Try to target the selected option by index using selectedIndex then get attribute name using getAttribute function.
document.getElementById('select_trainer').onchange = function () {
var my_select = event.target;
var option_name = my_select.options[my_select.selectedIndex].getAttribute('name');
document.getElementById('save_select_profile').value = my_select.value;
document.getElementById('save_select_profile').setAttribute('name', option_name);
}
Hope this helps.
Snippet
document.getElementById('select_trainer').onchange = function () {
var my_select = event.target;
var option_name = my_select.options[my_select.selectedIndex].getAttribute('name');
document.getElementById('save_select_profile').value = my_select.value;
document.getElementById('save_select_profile').setAttribute('name', option_name);
document.getElementById('test').value = document.getElementById('save_select_profile').getAttribute('name');
}
<select name='55' size="3" width="220" style="width:220px" id="select_trainer" multiple="yes">
<option value="1" name="unique-code-1" id="unique-id-1">Jillian</option>
<option value="2" name="unique-code-2" id="unique-id-2">Jillian</option>
<option value="3" name="unique-code-3" id="unique-id-3">Jillian</option>
</select>
<br>
<input value="" name="null" id="save_select_profile" checked="checked"/>
<br>
<input type='text' id="test"/>

event.target will return the whole select element, not the nested option tag, which stores the name that you're trying to set. To get the selected option, you need to do:
event.target.options[event.target.selectedIndex]
Then to get that selected option's name, you do:
event.target.options[event.target.selectedIndex].getAttribute('name');
Then you set the name, the way you were doing it with your setAttribute function.
Here is a working CodePen

Related

Can't get the option value into a hidden field

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!

Pass field title attribute through onchange another field

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()" />

How to set default value in input datalist and still have the drop down?

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>

Html select onchange get custom attribute value set to other input value

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">

Removing Selected attribute from Selectbox in javascript

I am having one selectbox which has multiple selected attribute for options. I have one hidden variable also. based on the hidden variable value have to remove the other selected attribute to options.
<option value="68" >A1</option>
<option value="49" >A2</option>
<option value="69" selected="selected">A3</option>
<option value="59" selected="selected">A3</option>
<option value="79" selected="selected">A3</option>
<input type= hidden id="someId" value="69" />
as in the example based on hidden value 69, I have to remove the selected attributes for 59 and 79.
I can do it in Jquery
$(".selected").removeAttr("selected");
var new_selection = $(this).find('option:selected');
new_selection.attr("selected",true).addClass(".selected");
But i want in javascript. Is there any best way to do in javascript
document.getElementsByClassName("selected").removeAttribute("selected");
var e = document.getElementById("asdf");
var strUser = e.options[e.selectedIndex].text;
e.setAttribute("selected",true);
e.classList.add("selected");
this is just interpreted in javascript from your jQuery code

Categories