Store a clicked option link within a select using jquery - javascript

ok, so I have this code:
$(function(){
// TODO make this work
$('select#selList').change(function(){
if($(this).val()=="alpha"||$(this).val()=="date"|$(this).val()=="nil")
$selectedValue=0;
else
$selectedValue=$(':selected').val();
$options=$('#selList').children('option');
$arrVals=[];
$options.each(function({
if($(this).val()=="alpha"||$(this).val()=="date"|$(this).val()=="nil")
{
return true;
}
else
{
$arrVals.push({
valx:$(this).val(),
txtx:$(this).text(),
datex:$(this).attr('date')
});
}
});
var sort_by = function(field, reverse, primer)
{
var key = function (x) {return primer ? primer(x[field]) : x[field]};
return function (a,b) {
var A = key(a), B = key(b);
return ((A < B ? -1 :(A > B) ? +1 : 0)) * [-1,1][+!!reverse];
}
}
switch($(':selected').attr('id'))
{
case 'alpha':
$arrVals.sort(sort_by('txtx',true,false));
break;
case 'date':
$arrVals.sort(sort_by('datex',true,false));
break;
}
$(this).html("");
for(var i=0, m=$arrVals.length;i<m;i++)
{
$($options[i]).text($arrVals[i].txtx);
$(this).append($options[i]);
}
$(this).append('<option value="nil" id="nil">---------------------------</option><option value="alpha" id="alpha">Sort alphabeticaly</option><option value="date" id="date">Sort by date</option>')
$(this).val($selectedValue);
});
});
Now all I want is to store the selected option if it defers from the "----", "Sort alphabeticaly" and "Sort by date" option, and keep it selected now matter what my succesive clicks are and the order of the options in the list.
The HTML is as follows:
<select id="selList" multiple style="height:150px">
<option value="1" date="20120126">A</option>
<option value="2" date="20120124">D</option>
<option value="3" date="20120125">B</option>
<option value="4" date="20120129">C</option>
<option value="nil" id="nil">---------------------------</option>
<option value="alpha" id="alpha">Sort alphabeticaly</option>
<option value="date" id="date">Sort by date</option>
</select>
Thanks for your help :)

Give it a try:(you may prepend the function-body to your existing function)
$('#selList')
.change(function()
{
var col=$('option:selected',this)
.filter(function(){return !isNaN(this.value);});
if(col.length)
{
$(this).data('selected',col);
}
}
);
Onchange it collects all selected options that have a numeric value. If there are any, it stores this collection as data inside the select.

Related

how to select option inside select element with javascript

So I have a select element with four options.
I want to select different options so that different functions can fire , but the onclick method is not working.
let select = document.getElementById('pbvalue');
select.addEventListener('click', dodo);
function dodo(e) {
if (e.target.value == 1) {
alert('hi')
} else {
alert('no')
}
}
<select id="pbvalue" tabindex="4">
<option value="0">""</option>
<option value="1">100</option>
<option value="2">200</option>
<option value="3">300</option>
</select>
how to select different options, so different functions can fire according to that.
Do this:
let select = document.getElementById('pbvalue');
select.onchange = function () {
// get the selected option
var value = select.options[select.selectedIndex].value
}
// get all options:
for ( int i = 0; i < select.options.length; i++ ) {
console.log( select.options[i].value )
}
This should give you an idea of how to proceed.
use onchange event.
<select id="pbvalue" tabindex="4" onchange="dodo(event)">
<option value="0" disabled>choose</option>
<option value="1">100</option>
<option value="2">200</option>
<option value="3">300</option>
</select>
<script>
function dodo(e){
switch(e.target.value){
case "1":
alert(1);//do what ever you want
break;
case "2":
alert(2);
break;
case "3":
alert(3);
break;
default:
alert("default");
break;
}
}
</script>
You can add onChange event on the select element.
<script>
function onSelectChange() {
const element = document.getElementById('pbvalue');
console.log('Selected Index: ', element.selectedIndex);
console.log('Selected Value: ', element.value);
}
</script>
<select id="pbvalue" tabindex="4" onchange="onSelectChange()">
<option value="0">""</option>
<option value="1">100</option>
<option value="2">200</option>
<option value="3">300</option>
</select>

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

change dropdown list to its original state

i have two dropdownlists in my view. by changing the value on the first one i can change the value on the second one. in the first run it works fine using scrip below.
but when i change the first dropdownlist to something else it will not work. i believe if i can change the second dropdownlist value and text and .... rest to its original state it will be ok.
here is my code :
<select id="ddlDepartment">
<option selected disabled>اselect department</option>
#foreach (var item in Model)
{
<option value="#item.DepartmentTitle">#item.DepartmentTitle</option>
}
</select>
</td>
</tr>
<tr>
<td>grade</td>
<td>
<select id="ddlgrade">
<option selected disabled="disabled">Select Grade</option>
<option id="id_bachelor" value="bachelor">bachelor</option>
<option id="id_Masters" value="Master">Masters</option>
<option id="Doctorate" value="Doctorate">Doctorate</option>
</select>
and here is my script :
$('#ddlDepartment')
.change(function() {
debugger;
var ddlDepartment = $('#ddlDepartment').val();
var grade = $('#ddlgrade').val();
getGrade();
function getGrade() {
$('#ddlgrade')
.change(function() {
grade = $('#ddlgrade').val();
$.ajax('/AdminPages/showStudents/' + ddlDepartment + '/' + grade)
.done(function(data) {
$('#lstStudents').html(data);
});
});
}
});
i get the erro here:
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
You have to move getGrade() function outside. getGrade() function bind a change event handler for second select EVERYTIME you changed the first select.
Final Solution
$('#ddlgrade').change(function() {
var ddlDepartment = $('#ddlDepartment').val();
var grade = $(this).val();
if(ddlDepartment){
$.ajax('/AdminPages/showStudents/' + ddlDepartment + '/' + grade)
.done(function(data) {
$('#lstStudents').html(data);
});
}
else{
alert("Please select department first!");
}
});
Please take a look how works your code:
$('#ddlDepartment')
.change(function() {
var ddlDepartment = $('#ddlDepartment').val();
var grade = $('#ddlgrade').val();
alert(ddlDepartment);
getGrade();
function getGrade() {
$('#ddlgrade')
.change(function() {
grade = $('#ddlgrade').val();
alert(grade);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlDepartment">
<option selected disabled>اselect department</option>
<option val="1">acb</option>
<option val="1">acfdb</option>
</select>
<select id="ddlgrade">
<option selected disabled="disabled">Select Grade</option>
<option id="id_bachelor" value="bachelor">bachelor</option>
<option id="id_Masters" value="Master">Masters</option>
<option id="Doctorate" value="Doctorate">Doctorate</option>
</select>

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!

How to change options of a select using JavaScript

I have an HTML page in which I have 2 selects.
<select id="field" name="field" onchange="checkValidOption();">
<option />
<option value="Plugin ID">Plugin ID</option>
<option value="Name">Name</option>
</select>
<select id="operator" name="operator" onchange="checkValidOption();">
<option />
<option value="EQUALS">EQUALS</option>
<option value="CONTAINS">CONTAINS</option>
<option value="NOT CONTAINS">NOT CONTAINS</option>
<option value="REGEX">REGEX</option>
</select>
What I'd like to happen is that checkValidOption() could make it so that if "Plugin ID" is selected in field that the only option is EQUALS (and it's selected) and otherwise all the other options are available. Any idea on how to approach this?
I tried changing the innerHTML of the operator select in JS:
document.getElementById("operator").innerHTML =
"<option value='EQUALS'>EQUALS</option>";
However this results in an empty select (this would also include manually setting the many options for going back to having all the ones listed above).
I can't think of another solution, any help would be greatly appreciated.
Try this:
Demo here
var field = document.getElementById('field');
var operator = document.getElementById('operator');
field.onchange = function () { fieldcheck(); }
operator.onchange = function () { fieldcheck(); }
fieldcheck();
function fieldcheck() {
if (field.value == 'Plugin ID') {
for (i = 0; i < operator.options.length; ++i) {
if (operator.options[i].value != 'EQUALS') {
operator.options[i].disabled = true;
}
};
operator.value = 'EQUALS';
} else {
for (i = 0; i < operator.options.length; ++i) {
operator.options[i].disabled = false;
};
}
}
To manipulate options when Plugin ID was selected:
function checkValidOption(){
var x=document.getElementById("field");
var y=document.getElementById("operator");
if (x.options[1].selected === true){
document.getElementById("operator").options[1].selected = true;
for(var i=0; i<y.length; i++){
if (i !== 1){
//disabling the other options
document.getElementById("operator").options[i].disabled = true;
}
}
}
else{
for(var i=0; i<y.length; i++){
//enabling the other options
document.getElementById("operator").options[i].disabled = false;
}
}
}
Here's a link to fiddle
A select field doesn't use the innerHTML method, you need to use value.
document.getElementById("operator").value = "...";
heres a jquery solution.
every time the first select changes, it produces new options from an array for the 2nd select. issue here is i had to change the option values of the first select to 0 and 1 to select which value in the array, you can manipulate those later if you are storing this info somewhere
http://jsfiddle.net/2TZJh/
$(document).ready(function() {
$("#field").change(function() {
var val = $(this).val();
$("#operator").html(options[val]);
});
var options = [
'<option value="EQUALS">EQUALS</option>',
'<option></option><option value="EQUALS">EQUALS</option><option value="CONTAINS">CONTAINS</option> <option value="NOT CONTAINS">NOT CONTAINS</option> <option value="REGEX">REGEX</option>'
];
});

Categories