I'm trying to disable an option from a selection through its value. When the value is equal to 'sure' the option is available. When the option is 'wrong' let it be disabled for options.
$(document).ready(function() {
$.getJSON("https://sheets.googleapis.com/v4/spreadsheets/1_TBtn730WbjJF_qRjo3c6SQXj_EeGU_qKOZbPTkVxfg/values/Page!A2:B5?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
$.each(result.values, function(i, field) {
$("#SelectTestID").append('<option hidden="hidden" selected="selected" value="">Options</option><option value="' + field[1] + '">' + field[0] + '</option>');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<select class="SelectTest" id="SelectTestID"></select>
If I've understood what you're asking you can check the value of field[1] and set the disabled property of the option element accordingly.
Also note that in the example below I remove the hidden option element as it served no purpose, and I also used a template literal for building the string as it's easier to read and less verbose.
$(document).ready(function() {
$.getJSON("https://sheets.googleapis.com/v4/spreadsheets/1_TBtn730WbjJF_qRjo3c6SQXj_EeGU_qKOZbPTkVxfg/values/Page!A2:B5?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
$.each(result.values, function(i, field) {
$("#SelectTestID").append(`<option value="${field[1]}" ${(field[1] === 'wrong' ? 'disabled' : '')}>${field[0]}</option>`);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<select class="SelectTest" id="SelectTestID"></select>
In the current example you can do so by checking if field[1] is equal to "wrong", if it is then you add the disabled="true" attribute to the option.
Here's an example of what that might look like:
$(document).ready(function () {
$.getJSON(
"https://sheets.googleapis.com/v4/spreadsheets/1_TBtn730WbjJF_qRjo3c6SQXj_EeGU_qKOZbPTkVxfg/values/Page!A2:B5?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI",
function (result) {
$.each(result.values, function (i, field) {
let optionString = `<option hidden="hidden" selected="selected" value="">Options</option><option value="${field[1]}">${field[0]}</option>`;
if (field[1] === "wrong") {
optionString = `<option hidden="hidden" selected="selected" value="">Options</option><option value="${field[1]}" disabled="true">${field[0]}</option>`;
}
$("#SelectTestID").append(optionString);
});
}
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="SelectTestID">
</select>
There are other approaches you could use, but since you're already using a string to append your Select element I used a string as well.
Related
I am trying to wrap my head around the each function. In this fiddle here
I would like to iterate through the selected elements of the list box one by one.
Essentially I was expecting an output like this
found itemA
found itemB
However I get an output like this
found itemA,itemB
I would like to know why that is happening and how I can fix it.
This is the code I am using
HTML
<select multiple="multiple" size="5" id="test">
<option>itemA</option>
<option>itemB</option>
</select>
<br>
<button type="button" id="bid">test</button>
JQuery
$( "#bid" ).click(function() {
$("#test").each(function () {
console.log("found " + $(this).val());
});
});
You are iterating over the select and not the options. The function you passed to each is getting called just once. Change your selector to #test > option and, like the comments on the question, change val() to text().
$( "#bid" ).click(function() {
$("#test > option").each(function () {
console.log("found " + $(this).text());
});
});
You have to specify the elements selector. Using only #test won't iterate over options because you didn't actually refer to it.
$("#bid").click(function() {
$("#test option").each(function() {
console.log("found " + $(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" size="5" id="test">
<option>itemA</option>
<option>itemB</option>
</select>
<br>
<button type="button" id="bid">test</button>
You'll want to use
$.each($("#test").prop("options"), function () {
console.log("found " + this.value);
});
or
$("#test").children().each(function () {
console.log("found " + this.value);
});
Here is an example that might explain it more: https://jsfiddle.net/Twisty/dr1tay6f/6/
HTML
<select multiple="multiple" size="5" id="test">
<option value="a">Item A</option>
<option value="b">Item B</option>
</select>
<br>
<button type="button" id="bid">test</button>
JavaScript
$(function() {
$("#bid").click(function() {
$("#test option").each(function(ind, el) {
console.log("At Index " + ind +" found Option with Value: " + $(el).val() + " and Label of: " + $(el).html());
});
});
});
The $(selector).each(callback(index, element)); will iterate over each element in the selector, passing it's index and element to the function.
I have a small project in which I have a select dropdown menu provided by the JQuery UI plugin.The dropdown contains a list of countries and their call code numbers.Is there a way that I show the country name and call code when the select is on focus and show only the call code when its out of focus with selected value.
Here is the code
HTML
<select class="form-control" id="cdropmovil" name="dropmovil"></select>
JavaScript Function
$.getJSON('../../Content/paises.json', function (json) {
var countries = json.countries;
countries.forEach(function (country) {
var opcion = '<option value="'+country.code+'">' + country.name + ' '
+ country.code + '</option>';
$("#cdropmovil").append(opcion);
}, this);
And here is what I tried obviously unsuccesfully...
$("#cdropmovil").on('change', function () {
$(this).text($("#cdropmovil option:selected").val());
})
You can use data-* attribute to store each option tag text value. This way you text value will not get lost if you update your option tag text value on value change.
your $.getJSON(...) will get modified to
$.getJSON('../../Content/paises.json', function (json) {
var countries = json.countries;
countries.forEach(function (country) {
//updated opcion variable
var opcion = '<option data-country-code-name="'+country.name+' '+country.code+'" value="'+country.code+'">' + country.name + ' '+ country.code + '</option>';
$("#cdropmovil").append(opcion);
}, this);
Now you can use data-* attribute value to change text on change() event handler
Here is the modified code
$(document).ready(function(){
$("body").on("focus","select",function(){
$(this).children("option").each(function(){
$(this).text($(this).data("country-code-name"));
});
});
$("body").on("change","select",function(){
var see = $("select option:selected").val();
$("select option:selected").text(see);
//This blur is added to remove focus on value select which was not commented link
$(this).blur();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="countries">
<option data-country-code-name="USA 1" value="1">USA 1</option>
<option data-country-code-name="Africa 2" value="2">Africa 2</option>
<option data-country-code-name="Switzerland 3" value="3">Switzerland 3</option>
<option data-country-code-name="Germany 4" value="4">Germany 4</option>
</select>
https://jsfiddle.net/weuydu6e/2/
When you modify the DOM of you select box, you need to re-initialise or refresh your JQuery SelectMenu:
$( "#cdropmovil" ).selectmenu( "refresh" );
This line should be after your forEach.
Reference:
http://api.jqueryui.com/selectmenu/#method-refresh
When you select the element from the UI the text should change automatically in the UI.
If you want to take it from the callback to use somewhere else:
$("#cdropmovil").on('change', function () {
var text = $(this).val();
// Do whatever you want with text
});
How can I re-order the comma delimited value of a select multiple element based on the order in which the options were selected by the user instead of the order of the options in the html?
For example:
<select multiple>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
... If the user selects "3", then "1", then "2", the returned value of the select will be "1,2,3". How can I make it return "3,1,2"?
Note, I am using jQuery and HTML5, so I can use those tools if needed.
Thanks!
This records the click of each elements add saves it to an array. When an item is deselected it is removed from the array.
var vals = [];
$(document).ready(function(e) {
$('#selector').change(function(e) {
for(var i=0; i <$('#selector option').length; i++) {
if ($($('#selector option')[i]).prop('selected') ) {
if (!vals.includes(i)) {
vals.push(i);
}
} else {
if (vals.includes(i)) {
vals.splice(vals.indexOf(i), 1);
}
}
}
})
$("#final").click(function(e) {
var order = '';
vals.forEach(function(ele) {
order += $($('#selector option')[ele]).val() + ',';
})
console.log(order);
})
})
Codepen: http://codepen.io/nobrien/pen/pydQjZ
None of the proposed solutions floated my boat, so I came up with this:
My solution is to add an html5 attribute to the multiselect element, data-sorted-values, to which I append new values, and remove un-selected values, based on the latest change.
The effect in the end is that data-sorted-values can be queried at anytime to get the current list of user-ordered values. Also, all selected options hold an attribute of "selected".
I hope this can help someone else out there...
https://jsfiddle.net/p1xelarchitect/3c5qt4a1/
HTML:
<select onChange="update(this)" data-sorted-values="" multiple>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Javasript:
function update(menu) {
// nothing selected
if ($(menu).val() == null)
{
$.each($(menu).find('option'), function(i)
{
$(this).removeAttr('selected');
$(menu).attr('data-sorted-values', '');
});
}
// at least 1 item selected
else
{
$.each($(menu).find('option'), function(i)
{
var vals = $(menu).val().join(' ');
var opt = $(this).text();
if (vals.indexOf(opt) > -1)
{
// most recent selection
if ($(this).attr('selected') != 'selected')
{
$(menu).attr('data-sorted-values', $(menu).attr('data-sorted-values') + $(this).text() + ' ');
$(this).attr('selected', 'selected');
}
}
else
{
// most recent deletion
if ($(this).attr('selected') == 'selected')
{
var string = $(menu).attr('data-sorted-values').replace(new RegExp(opt, 'g'), '');
$(menu).attr('data-sorted-values', string);
$(this).removeAttr('selected');
}
}
});
}
}
try this https://jsfiddle.net/ksojitra00023/76Luf1zs/
<select multiple>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<div id="output"></div>
$('select').click(function(){
$("#output").append($(this).val());
});
var data = '3,1,2';
var dataarray=data.split(",");
var length =dataarray.length;
for(i=0;i<length;i++){
// Set the value
$('#select').multiSelect('select',dataarray[i]);
}
I want to make one option the default value so if I clear my drop-down it is populated by the default.
This is my code:
<script language="JavaScript">
function getEnvNames(result){
$("#environmentName").empty();
Here I clear the drop-down, but I want my default value to populate.
var data = JSON.parse(result);
$.each(data, function(key, value)
{
$("#environmentName").append("<option>" + value.name +" - "+ value.purpose + "</option>");
});
}
This is my HTML:
<select class="body" name="environmentName" id="environmentName" class="body">
<option selected="selected" disabled="disabled">Select An Environment</option>
</select>
If default selected value is select an environment, then use append function:
$('#environmentName').empty().append('<option selected="selected" disabled="disabled">Select An Environment</option>');
Or if you don't want to remove the selected value (once the user changes the option)
$("#environmentName").children().not($("#environmentName option:selected")).remove();
At the time of clear your select box put a empty option will solve your problem
function getEnvNames(result){
$("#environmentName").html('<option value="" > Select An Environment </option>');
data = JSON.parse(result);
$.each(data, function(key, value)
{
$("#environmentName").append("<option>" + value.name +" - "+ value.purpose + "</option>");
});
}
I need to make Select name with option value, to select a specific value or index. the data where comes from db in a value "{{design}}".
I do get the value currectly, but I dont manage to set "selected" on the currect option value.
here is the code:
console.log("{{design}}");
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( options[i].innerHTML==="{{design}}")
{
options.selectedIndex=i;
}
}
});
the html is :
<select name="design" required id="design" >
<option value="1">flowers</option>
<option value="2">classic</option>
<option value="3">roses</option>
</select>
I need to make to currect {{design}} value, lets say it's 2, so it will be <option value="2" selected>classic</option>`
thanks!
SOLVED
Hi, found the solution to the issue, if anyone eles goes into trouble.
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( $('select').children('option')[i].value === "{{design}}")
{
$('select').children('option')[i].selected=true;
}
}
});
the currect way is to find the right option value and then-> [i].selected=true
goodluck
Try this
var selectedvalue=2; //option with value 2 should be selected
$("#design option[value=selectedvalue]").attr("selected","selected");
Hope this helps...
If I understood right, you are on the right path just taking a minor detour. Try this:
if ( options[i].innerHTML==="{{design}}")
{
options.attr('selected', 'selected');
}
The example of .each() usage:
$(document).ready(function(){
$('select option').each(function(i){
if( i.value === "{{design}}"){
$(this).attr('selected','selected');
}
});
});
try this:
$(document).ready(function(){
$('select option').each(function(i){
//if this option contains the word "{{design}}" Then this is selected
if( $(this).html().indexOf("{{design}}") != -1)
$(this).attr('selected',true);
});
});