Automatically update select options list using jQuery or Javascript? - javascript

I have a select list that's generated by the Javascript code of my app
<select name="addToContexts" id="addToContexts">
<option selected>private</option>
<option>public</option>
<option>shared</option>
</select>
What I need to do is that when the user performs a certain action the selected parameter shifts to another option, so that the result would be something like:
<select name="addToContexts" id="addToContexts">
<option>private</option>
<option selected>public</option>
<option>shared</option>
</select>
Do you know if there's a way to do it without regenerating the whole options list simply using jQuery to get the select element by ID and to change the selected option?
Thank you!

<body>
<select name="addToContexts" id="addToContexts">
<option selected>private</option>
<option>public</option>
<option>shared</option>
</select>
<button id="changeSelect">Change</button>
<script>
$("#changeSelect").click(function(){
$("#addToContexts option:nth-child(2)").prop("selected", true);
});
</script>
</body>
Something like this?

Hope this help.
http://jsfiddle.net/6Ljn1rzr/
$('input[type=checkbox]').on(
'change',
function() {
$('option').attr("selected",false);
$('option:contains(public)').attr("selected",true);
}
);

its very simple you can visit this thread
http://www.stackoverflow.com/questions/1314245/set-the-selected-index-of-a-dropdown-using-jquery
it has explained the in a very good manner and hopefully you will get your answer from this thread

http://jsfiddle.net/washington_guedes/ovpkLexj/5/
I used an ul-li "click" event as "certain action"... and it worked well
$("li").on("click", function(){
var aux = $(this/*li*/).html();
$('#addToContexts > option')
.prop("selected", false)
.each(function(){
if( $(this/*option*/).html() === aux){
$(this/*option*/).prop("selected", true);
}
});
});

Related

Removing duplicates from a select dropdown using javascript or jquery

I have a select dropdown field that is being created dynamically from a database based on locations. Due to the way this is being created it results in the dropdown having duplicate locations listed.
<label for="club_feed_town">Location:</label>
<select id="locationList" name="club_feed_town">
<option value="">All Locations</option>
<option value="Andover">Andover</option>
<option value="Andover">Andover</option>
<option value="Bishops waltham">Bishops waltham</option>
<option value="Blandford forum">Blandford forum</option>
<option value="Boscombe">Boscombe</option>
<option value="Bournemouth">Bournemouth</option>
<option value="Bournemouth">Bournemouth</option>
<option value="Etc">Etc</option>
</select>
Does anyone know if there is a way to use some code on the page which checks the dropdown for duplicates and removes any duplicates from the menu?
Thanks in advance,
Tom
Simple enough using jQuery and a temporary array to store values ( or text)
Following assumes values are repeated
var optionValues =[];
$('#selectID option').each(function(){
if($.inArray(this.value, optionValues) >-1){
$(this).remove()
}else{
optionValues.push(this.value);
}
});
DEMO
A modern JS solution without jQuery:
const options = []
document.querySelectorAll('#locationList > option').forEach((option) => {
if (options.includes(option.value)) option.remove()
else options.push(option.value)
})
if you can edit the query, Use DISTINCT keyword on your query to the db, so that it do not repeat the same location.
I assumed you want something like this.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<select id="select_id">
<option>abc</option>
<option>abc</option>
<option>bcd</option>
<option>xyz</option>
<option>bcd</option>
<option>xyz</option>
</select>
<script type="text/javascript">
var opt = {};
$("#select_id > option").each(function () {
if(opt[$(this).text()]) {
$(this).remove();
} else {
opt[$(this).text()] = $(this).val();
}
});
</script>
If order is not important, you can try this jQuery snippet
$("form select option").each(function(){
var value = $(this).val();
var elems = $("form option[value="+value+"]");
if (elems.length > 1) {
elems.remove();
$("form select").append("<option value="+value+">"+value+"</option>");
}
});
Usually the problem is not in the client-side but in the database-side
if the selection is not acurated doesnt really worth clean the selection.
Select DISTINCT(var) from X;
should work even better than a new "function" in JavaScript

How do I get a child attribute from a e.currentTarget.value JQuery

I am trying to get an attribute from the child of the the currentTarget. I have tried this,
(e.currentTarget.child.attr("data-english")
I have googled it and have had no luck finding anything useful, maybe its me being new with code I might be looking up the wrong thing.
Here is the HTML
< select class="form-control" id="select_fundFamily" name="select_fundFamily" autocomplete="off" >
< option value="stuff" data-english="english" data-family-locallang="model" >
At the moment in JQuery, the e.currentTarget.value; is showing the select element.
Can someone please kindly advise me in what path to take to solve this issue?
For the value of the selected option in a select, you can use
$(e.currentTarget).find(':selected').attr("data-english");
Run the snippet below to see it work
$(document).ready(function(){
$('select').change(function(e){
var eng = $(e.currentTarget).find(':selected').attr("data-english");
$('body').append(eng);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="select_fundFamily">
<option selected disabled>Select something</option>
<option value="stuff1" data-english="english1" >1</option>
<option value="stuff2" data-english="english2" >2</option>
<option value="stuff3" data-english="english3" >3</option>
<option value="stuff4" data-english="english4" >4</option>
<option value="stuff5" data-english="english5" >5</option>
</select>
If you try to determine the selected option's attribute. A simple solution is:
var dataEnglish = $('#select_fundFamily option:selected').attr('data-english'); // dataEnglish = english
currentTarget will respond any element that event listener triggered the event. In your case, i think you want to use e.target to target the right element.
$("select#select_fundFamily").on('click','option', function(e) {
e.preventDefault();
$(e.target).attr('data-english'); // you can use $(this) instead
//something else
});

How to make option selection change button link?

I have a drop down list and a button. I want to make the selection of list reflects on the button link.
Example JSFiddle
Here is the example code:
<select style="float:left;">
<option value="5">$5.00 monthly</option>
<option value="10">$10.00 monthly</option>
<option value="15">$15.00 monthly</option>
<option value="20">$20.00 monthly</option>
</select>
<div id="button" style="width:100px;height:30px;float:left;background:#ccc;line-height:30px;text-align:center;margin:auto 5px;">
Order
</div>
What I want to achieve is when the user for example selects the second option, the button link changes to http://ordernow/10/ instead of http://ordernow/5/ and so on. Can someone inform me how do that or provide a link for a tutorial regarding this? Thank you.
Using pure javascript and adding ids to some of the elements:
JSFiddle
Here's the JavaScript:
document.getElementById("subscription").onchange = function() {
document.getElementById("order-btn").href = "http://ordernow/"+this.value+"/";
}
You can listen to select's onchange to get the new selected option's value. And then add the value to button's href:
$('select').on('change', function () {
$('#button > a').attr('href', 'http://ordernow/' + $(this).val() + '/');
});
jsfiddle DEMO
Can use a regex to parse the end of the href so path doesn't need to be known
$('select').change(function(){
var val =$(this).val();
$('#button a').attr('href', function(_,href){
var reg = /\/\d\/$/;
return href.replace(reg, '/'+val+'/');
});
});
DEMO

Getting a Select Value after appending

This is for javascript and jquery.
I have in my body...
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<script>
$("select").change(function () {
functionLoadOpt2() }).trigger("change" );
</script>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
As we see above, the web page has 2 select boxes and a button. Depending on what you select in the first select box loads what is in the second one, using the functionLoadOpt2 function locating higher up in my code.
if (result == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
...
There is more but it follows the same code different values.
Result is the following, above the if statement(just a row up),
var result = (document.getElementById('option1_select').value);
now on the button click, the function changePage() runs,
and all I want is ...
var result = (document.getElementById('option1_select').value);
var result2= (document.getElementById('option2_select').value);
Assume they selected and option for both. Result2 doesnt work. I'd imagine because I'm appending it but how would I work around this. So that when I click changePage() I get the selected value of option1_select and option2_select.
functionLoadOpt2:
function functionLoadOpt2(){
var opt1Val = (document.getElementById('option1_select').value);
$("#option2_select").find('option').remove().end().append('<option></option>');
if (opt1Val == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
$("#option2_select").append('<option>Letter2</option>');
$("#option2_select").append('<option>Letter3</option>');
$("#option2_select").append('<option>Letter4</option>');
$("#option2_select").append('<option>Letter5</option>');
}else if (opt1Val == "Word2") {
$("#option2_select").append('<option>Letter3</option>');//they have similar ones in some cases
$("#option2_select").append('<option>Letter6</option>');
$("#option2_select").append('<option>Letter7</option>');
$("#option2_select").append('<option>Letter8</option>');
$("#option2_select").append('<option>Letter9</option>');
$("#option2_select").append('<option>Letter10</option>');
$("#option2_select").append('<option>Letter11</option>');
$("#option2_select").append('<option>Letter12</option>');
$("#option2_select").append('<option>Letter13</option>');
$("#option2_select").append('<option>Letter14</option>');
$("#option2_select").append('<option>Letter15</option>');
$("#option2_select").append('<option>Letter16</option>');
$("#option2_select").append('<option>Letter17</option>');
//this works
}
}
use jQuery to get and set the value of <select> with .val()
Both your select elements have the same id, fix it the it should be fine
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
Demo: Fiddle
Note: You can improve the script a lot by using proper jQuery constructs, like this

Get attributes values from select2 selected option

I'm using the Select2 plugin from http://ivaynberg.github.io/select2/select2-latest.html what works fine but i'm having a problem to get the values from the options attributes.
I've got a select menu like this:
<select name="invoice_line[0][vat]" class="vat">
<option value="20440" data-value="21.00" data-name="20440" selected="selected">21%</option>
<option value="20441" data-value="6.00" data-name="20441">6%</option>
<option value="20442" data-value="0.00" data-name="20442">0%</option>
</select>
How can I get the values of the attributes 'data-value', 'data-name' and 'value' of the selected option?
obj = $("#dropdown").select2("data")
in obj variable i will get all the data of the selected node.
This was answered in another SO question
There is no direct method with select2, you can use a combinaison of select2 data and jQuery :
$("#example").select2().find(":selected").data("id");
First you get the select2 data then you find your selected option with jQuery and finally the data-attribute.
We can use a combination of select2 data and jQuery :
$("#example").select2('data').element[0].attributes['data-name'].value
Following worked for me. Idea is to use "change" function as follows
<select class="drop-down">
<option value="0">A</option>
<option value="1">B</option>
</select>
$('.drop-down').select2().on("change", function(e) {
var obj = $(".drop-down").select2("data");
console.log("change val=" + obj[0].id); // 0 or 1 on change
});
var return_option = $("#your-select-input-id").select2().find(":selected")[0];
above given statement will return select option and then put that return result as given below:
var name_of_attribute = $( return_option ).attr('name-of-attribute');
This will return the attribute value.
No idea about the pluggin, and without checking if the code works i imagine it would be something like this:
$('.vat li').each(function(){
var me = $(this),
mevalue = me.attr('value'),
datavalue = me.data('value'),
dataname = me.data('name');
//do what you want with the data?
});
Put select2 into tagging mode , it will help you.
Or
Try below similar code, it may work for you ...
$("$id").select2("val", option);
$("$id").attr("data-name");
I know that this is an old post, but I was struggling with this same problem. This is the solution that me and my good friend Thys finally got to work:
<script type="text/javascript">
$(document).ready(function ()
{
$("#e1").select2();
$("#e1").change(function () {
var theID = $("#e1").val();
$('#staffNr').val(theID);
$('#staffNr').val();
//var theID = $(test).select2('data').id;
var theSelection = $(test).select2('data').text;
$('#selectedID').text(theID);
$('#selectedText').text(theSelection);
});
});
#Html.Hidden("fieldName","staffNr");
This worked in my MVC 4 view with the last line in my html form where it is correctly added to the model. Don't forget to up-vote if you use my answer please :) I haven't got much of a reputation...
I hope you solved the issue. Here we dont use select2(), if we use select2() it will not work all other functions like formatNoMatches, on-change....
$("#example").find(":selected").data("id");
el = document.getElementsByName("invoice_line[0][vat]")
el.options[[el.selectedIndex]].attributes["data-id"].value
The params.data.element object of the selected item holds the data you're looking for.
Where .foo is the select element I'm calling, and the data attribute within the options I want to access is data-bar="some value" The following works for me:
var $fooSelect = $('.foo');
$fooSelect.on(function (e) {
console.log($(e.params.data.element).data('bar'));
});
You can access to attributes looking in DOM structure:
<select id="select_name">
<option value="20440" data-value="21.00">21%</option>
<option value="20441" data-value="6.00">6%</option>
<option value="20442" data-value="0.00">0%</option>
</select>
$('#select_name option').each(function (index) {
console.log($(this).attr("data-value"));
});
set an id for your select element and this would work
$('select#your-id').find('option[value="'+$('#your-id').val()+'"]').attr('data-attribute');
You haveto do it with on("change"... because of this is a dynamicly generated option list.
$('.select_class').on("change",function(){
var selected_value= $('.hakemler').val();
var wanted= $('.select_class').find('option[value="'+selected_value+'"]').attr('data-foo');
alert(selected_value+" "+wanted);
});

Categories

Resources