Convert html select option list to radio buttons - javascript

I have a html page which works with select/option and I want to convert this feature to input type=radio (list to radio butons).
Actually i have a list of selects like this:
<select name="DEC-51537a4b580452b9e145b75c-A">
<option selected="" value="OK">OK</option>
<option value="NOK">NOK</option>
</select>
<select name="DEC-51537a4b58045459e145b75c-R">
<option selected="" value="OK">OK</option>
<option value="NOK">NOK</option>
</select>
<select name="DEC-51537a88880452b9e145b75c-A">
<option selected="" value="OK">OK</option>
<option value="NOK">NOK</option>
</select>
The user select the value that he want and click on a button.The button call a javascript which get the result for each "DEC-".
For each select which start with "DEC-", I retrieve :
- dec-number (51537a88880452b9e145b75c for example)
- original dec value (A or R)
- and i get select.value in order to retrieve the dec value select by the user
If i want to convert select to input type=radio, first of all I have change select to this:
<input name="DEC-51537a4b580452b9e145b75c-A" type="radio" checked value="A">A
<input name="DEC-51537a4b580452b9e145b75c-A" type="radio" value="R">R
And here the javascript function which works with select but not radio buttons:
var elements = $doc.getElementsByTagName('select');
var sel;
for(var i=0; i<elements.length; i++){
sel = elements[i];
if(sel.name.indexOf('DEC-') === 0){
var selName = sel.name.split('-');
var oid = selName[1];
var originalDecision = selName[2];
var supervisorDecision = sel.value;
decisions++;
if(originalDecision == supervisorDecision) {
rightDecisions++;
} else {
wrongDecisions++;
if(originalDecision == "ACCEPTED") {
originalDecision="<h3 class='green'>ACCEPTED</h3>";
} else if(originalDecision == "REFUSED") {
originalDecision="<h3 class='red'>REFUSED</h3>";
}
if(supervisorDecision == "ACCEPTED") {
supervisorDecision="<h3 class='green'>ACCEPTED</h3>";
} else if(supervisorDecision == "REFUSED") {
supervisorDecision="<h3 class='red'>REFUSED</h3>";
}
var content = $doc.getElementById(oid).innerHTML;
wrongDecisionsTab += "<tr><td>" + content + "</td><td>"
+ originalDecision + "</td><td><h3>" + supervisorDecision + "</h3></td></tr>";
}
}
}
I need the same things but with radio buttons, so i have tried to change:
var elements = $doc.getElementsByTagName('input');
but it's not sufficient.
What i'm missing?

Related

How to change to default the selected dropdown [duplicate]

I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P

Using jquery data attributes with each function

I'm building a quote generator, and there is a product field where a user can select a product, select the quantity, then add another if they wish.
I'm using an each function to loop through all the products they add to sum the price.
For regular values, my JS is running great, but I want to add a second price (minimum price) that the product can be sold for. I've added the data as an attribute and i'm trying to use the same method to pull the price from the attribute, but it just keeps returning 'undefined'!!!!
HTML
<select class="form-control onChangePrice system1" name="SystemModel">
<option value="">Select...</option>
<option value="3300" data-min-price="3000">System 1</option>
<option value="4500" data-min-price="4000">System 2</option>
<option value="6000" data-min-price="5500">System 3</option>
<option value="6000" data-min-price="5500">System 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice systemNumber" type="number" name="SystemModelAmount" value="1">
</div>
JS
var systemTotal = 0;
var systemMin = 0;
var i = 0;
$('.system1').each(function(){
if (this.value != "") {
systemEachMin = $(this).data("minPrice");
console.log(systemEachMin);
systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
systemTotal += parseFloat(systemEachTotal);
systemMin += parseFloat(systemEachMin);
};
i++;
});
The code works flawlessly for the regular value of the option, i just cant get it to repeat for the data attribute!
Thanks
You're doing a couple of things slightly wrong here:
$('.system1').each(function(){
should be:
$('.system1 option').each(function(){
and
systemEachMin = $(this).data("minPrice");
should be:
systemEachMin = $(this).data("min-price");
So in full:
var systemTotal = 0;
var systemMin = 0;
var i = 0;
$('.system1 option').each(function(){
if (this.value != "") {
systemEachMin = $(this).data("min-price");
console.log(systemEachMin);
systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
systemTotal += parseFloat(systemEachTotal);
systemMin += parseFloat(systemEachMin);
};
i++;
});
$(this).data("minPrice"); refers to the select tag and not the options tag, there is no data-min-price on the select tag.
this.options will return all the options in an array
or you could use the following for the selected options data attribute
$(this).find('option:selected').data("minPrice")
or
$("option:selected", this).data("minPrice")

Make first option of select unselectable through arrow keys in Google Chrome

I have a select with options and when a user selects an option, it is removed from the select and displayed as a button. When the button is pressed, the option goes back to my select. Everything works fine with mouse click, but if we navigate with the arrows key, the user can select my first option which is "choose fruit". How do I make it unselectable? disabled="disabled" doesn't work. Here's a jsfiddle http://jsfiddle.net/gbjcw1wp/2/. To reproduce the problem, select a fruit, then press Up arrow key on your keyboard.
EDIT : ONLY HAPPENS IN GOOGLE CHROME.
Disabling arrow keys work, but i'd like another way of accomplishing this.
HTML:
<select id="combobox" onchange="cbchange();">
<option selected="selected">Choose Fruit</option>
<option value="apple">apple</option>
<option value="pear">pear</option>
<option value="orange">orange</option>
<option value="banana">banana</option>
</select>
<br>
<br>
<div id="buttons"></div>
Javascript :
var fieldnames = [];
var valuenames = [];
function sortComboBox() {
document.getElementById("combobox").remove(0);
var my_options = $("#combobox option");
my_options.sort(function (a, b) {
if (a.text.toUpperCase() > b.text.toUpperCase()) return 1;
if (a.text.toUpperCase() < b.text.toUpperCase()) return -1;
return 0;
});
$("#combobox").empty().append('<option>Choose Fruit</option>').append(my_options);
$('#combobox option:first-child').attr("selected", "selected");
}
function cbchange() {
var index = $('#combobox').get(0).selectedIndex;
var text = $('#combobox option:selected').text();
var selectedItem = $('#combobox').val();
$('#buttons').append('<table class="ui"><tr><td class="variable">' + text + '</td><td class="icon"><span id="' + selectedItem + '" class="icon ui" value="X" onclick="addOption(\'' + text + '\',this.id)">X</span></td></tr></table>');
$('#combobox option:eq(' + index + ')').remove();
fieldnames.push(text);
valuenames.push(selectedItem);
}
function addOption(text, selectedItem) {
for (var i = valuenames.length - 1; i >= 0; i--) {
if (valuenames[i] === selectedItem) {
valuenames.splice(i, 1);
fieldnames.splice(i, 1);
}
}
$("#combobox").append($("<option></option>").val(selectedItem).text(text));
$('#' + selectedItem).parent().parent().parent().parent().remove();
sortComboBox();
}
A simple change to your code can resolve your problem.
Give the default option some weird value. Eg:
<option value="null" selected="selected">Choose Fruit</option>
And append the follow code the the start of your cbchange() function.
if($('#combobox').val()=="null"){
return false;
}
See jsfiddle example

how to show 2 select options value in another element?

I am have been searched too much on net but nothing found.
I have 2 select options tag.
I want to show option value in the input tag by multiplying option tag value whatever it is.
and selecting 2nd option tag I want to assign 2nd option tag value to 1st option tag value.
and I also want to multiply that values as the 1st options value have before.
how to do this?
here is my code.
My 1st options tag.
<select name="" id="test">
<option selected="" value="0" disabled='disabled'>Select Duration</option>
<option value="1">1/month</option>
<option value="2">2/month</option>
<option value="3">3/month</option>
<option value="6">6/month</option>
<option value="12">12/month</option>
</select>
<input type="text" data-val="9" id="price_value" style="border:1px solid #0a0; padding:1px 10px; color: #f90;" value="0" size="5"/><br>
Here is 2nd option tag.
<select id="plan">
<option value='Basic'>Basic</option>
<option value='Standard'>Standard</option>
<option value='Professional'>Professional</option>
<option value='Enterprice'>Enterprise</option>
</select>
here is JS.
$('#test').on('change',function(e){
var input = $(this).next('input[type="text"]');
var value = $(this).find('option:selected').val();
input.val( input.data('val') * parseInt(value) );
});
$('#plan').on('change',function(e) {
var plan = $(this).find('option:selected').val();
var price_value = $('#price_value');
if (plan == "Basic") {
price_value.removeAttr('data-val');
price_value.attr('data-val','9');
}
else if (plan == "Standard"){
price_value.removeAttr('data-val');
price_value.attr('data-val','19');
}
else if (plan == "Professional"){
price_value.removeAttr('data-val');
price_value.attr('data-val','29');
}
else if (plan == "Enterprice") {
price_value.removeAttr('data-val');
price_value.attr('data-val','59');
}
});
Here is Demo
Changes
Use $(this).val() instead of $(this).find('option:selected').val() to fetch select value. or even better use this.value
use .data() to set value like price_value.data('val', 9); instead of price_value.attr('data-val','9');
No need to use price_value.removeAttr('data-val');
Code
$('#test').on('change',function(e){
var input = $(this).next('input[type="text"]');
var value = $(this).val(); //Or this.value
input.val( input.data('val') * parseInt(value, 10) );
});
$('#plan').on('change',function(e) {
var plan = $(this).val();
var price_value = $('#price_value');
if (plan == "Basic") {
price_value.data('val',9);
}
else if (plan == "Standard"){
price_value.data('val',19);
}
else if (plan == "Professional"){
price_value.data('val',29);2
}
else if (plan == "Enterprice") {
price_value.data('val',59);
}
$('#test').trigger('change'); //Trigger $('#test') change event
});
DEMO
This solution would work if you are okay with changing your HTML a bit:
<select id="plan">
<option value='9'>Basic</option>
<option value='19'>Standard</option>
<option value='29'>Professional</option>
<option value='59'>Enterprise</option>
</select>
Then simply use:
$('#test, #plan').on('change',function() {
var valueOne = $('#test').val();
var valueTwo = $('#plan').val();
$('#price_value').val(parseInt(valueOne) * parseInt(valueTwo));
});
That's all!

Is there a SelectedIndex for an HTML5 DataList?

You can pick the current option of any select element:
mySelect.options[mySelect.selectedIndex]
Can I do the same with a DataList? Something like this:
<input id = "input" list = "datalist" type = "text" />
<datalist id = "datalist">
<option value = "No. 1"></option>
<option value = "No. 2"></option>
<option value = "No. 3"></option>
</datalist>
<script>
var datalist = document.getElementById ("datalist");
var input = document.getElementById ("input");
input.addEventListener ("keyup", function (event) {
if (event.which === 13) {
alert (datalist.options[datalist.selectedIndex]); // Example
}
}, false);
</script>
No, the datalist element is for providing autocomplete to inputs. It is a source of data, is hidden from the user, and multiple inputs may link to it. Therefore it doesn't make sense to have a selectedIndex.
Instead, you should simply check the .value of the input:
var datalist = document.getElementById ("datalist");
var input = document.getElementById ("input");
input.addEventListener ("keyup", function (event) {
if (event.which === 13) {
alert(input.value);
}
}, false);
Judging by specs, datalist object doesn't have selectedIndex property. But you can find it's default option, which have selected. Or compare input's value to each option value and manually find the index.
for (var i=0;i<datalist_id.options.length;i++)
if (datalist_id.options[i].value == input_id.value)
{alert(datalist_id.options[i].innerText);break;}
Lets say you have data attributes in the above example like this,
<input list="browsers" name="browser" value="Internet Explorer">
<datalist id="browsers">
<option value="Internet Explorer" data-company="Microsoft">
<option value="Firefox" data-company="Mozilla">
<option value="Chrome" data-company="Google/Alphabet">
<option value="Opera" data-company="Opera">
<option value="Safari" data-company="Apple">
</datalist>
and you want to obtain the data-company attribute of the selected item,
using the loop above
for (var i=0;i<datalist_id.options.length;i++) {
if (datalist_id.options[i].value == input_id.value) {
// obtains the data-company attrbute
console.log(datalist_id.options[i].getAttribute("data-company");
alert(datalist_id.options[i].innerText);
break;
}
}
You can just add a value to the input element. This will be shown to the user as the "default" value. If the user decides to change it, i.e. delete this value from the input field, then the list in the datalist will show up:
<input list="browsers" name="browser" value="Internet Explorer">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
Here is the script for getting index from SelectedIndex of Datalist. Html from #pingle60
let x = document.getElementById("browsers").options;
let input = document.querySelector('input');
input.onchange = getIndex;
function getIndex(e) {
for (var i=0;i<x.length;i++) {
if (x[i].value == e.target.value) {
return i;
// alert('The index of SellectedIndex is : ' + i + ' and the value is : ' +x[i].value);
break;
}
}
}

Categories