set the value of select option dynamically - javascript

This is my code. I am trying to set the value of select tag from database. but it's not working as expected. My requiremnet is value='Auto' then 0th index should be selected else 1sst index should be selected. But its not happening that way. can some one help me?
<div class="form-group">
<label class="medium mb-1" for=""> Select Mode of Update </label>
<select class="form-control" name="avupdatemode" value="<%= data.updatemode %>" >
<option value="Auto" >Auto Update</option>
<option value="Manual">Manual</option>
</select>
</div>
<script>
var sel= document.getElementById('avupdatemode');
if(document.getElementById('avupdatemode').value =='Auto'){
sel.options.selectedIndex = 0;}
else{
sel.options.selectedIndex = 1;
}
</script>

First there is no id attribute on your select.
Second .value will take the value from the selected option and not the value attribute from the select.
So i've added data-value="sAuto" to the select and then done document.getElementById('avupdatemode').dataset.value == 'Auto'
DEMO
var sel = document.getElementById('avupdatemode');
if (document.getElementById('avupdatemode').dataset.value == 'Auto') {
sel.options.selectedIndex = 0;
} else {
sel.options.selectedIndex = 1;
}
<div class="form-group">
<label class="medium mb-1" for=""> Select Mode of Update </label>
<select class="form-control" id="avupdatemode" name="avupdatemode" data-value="sAuto">
<option value="Auto">Auto Update</option>
<option value="Manual">Manual</option>
</select>
</div>

I am getting my backend data in an array to my ejs page.
So I tried this and it worked:
var sos = <%- JSON.stringify(sos) %>;
I iterated the array and based on the value i set my index for the select option.

Related

dropdown selected value not setting and displaying blank text in angular js

I am working on C#/MVC application with angularJS. I need to display dropdown on popup, If record already have value then by default that value should be selected otherwise default option choose an option.
I am able to bind dropdown and If I debug I am getting correct ng-model value but its displaying blank.
Here is controller code on pop up open click
$scope.ShowAdPopup = function (adId) {
$scope.Popup.CategoryId = 0;
$scope.Popup.InterestId = 0;
$scope.Popup.SourceId = 0;
var filteredData = $filter('filter')($scope.gridAdData, { id: adId }, true);
if (filteredData.length > 0) {
$scope.Popup.Id = filteredData[0].id;
$scope.Popup.AdId = filteredData[0].adId;
$scope.Popup.AdName = filteredData[0].adName;
$scope.Popup.Category = filteredData[0].category;
$scope.Popup.Interest = filteredData[0].interest;
$scope.Popup.Source = filteredData[0].source;
$scope.Popup.AdUrl = filteredData[0].adUrl;
$scope.Popup.CategoryId = filteredData[0].categoryId;
$scope.Popup.InterestId = filteredData[0].interestId;
$scope.Popup.SourceId = filteredData[0].sourceId;
}
$("#divAddGroup").modal({ show: true, backdrop: 'static', keyboard: false });
}
And html is as below
<div class="form-group">
<label class="col-sm-3 control-label">Category</label>
<!--<div class="col-sm-9">
<input type="text" name="category" class="form-control" ng-model="Popup.Category" />
</div>-->
<div class="col-sm-9">
<select class="form-control" name="categoryDrp" ng-model="Popup.CategoryId">
<option value="">-- choose an option --</option>
<option ng-repeat="item in CategoryData" value="{{item.id}}">{{item.categoryName}}</option>
</select>
</div>
Now If I debug and I can see CategoryId setting correct id . e.g. 7 or 8 or 9 which CategoryData have already but its display 'blank' as first option if Id is available
If CategoryId is null then it display '-- choose an option --' which is correct
Try ng-selected="item.id == Popup.CategoryId" as :
<select class="form-control" name="categoryDrp" ng-model="Popup.CategoryId">
<option value="">-- choose an option --</option>
<option ng-repeat="item in CategoryData" value="{{item.id}}"
ng-selected="item.id == Popup.CategoryId">{{item.categoryName}}</option>
</select>

Setting 'selected' option for select element in Vue.js

I have an array- selected_players, which I am looping through in Vue.js, but am not able to set the selected attribute of an option.
What I am trying: :selected="player.round.best_player == 1"
Here is the section of the related template:
<div v-if="selected_players.length && ! loading">
<h4>Select Best Player</h4>
<div class="form-group">
<select name="best-player" id="best-player" v-model="best_player" class="form-control">
<option v-for="player in selected_players" :value="player.id" :selected="player.round.best_player == 1">{{ player.name }}</option>
</select>
</div>
<br />
When loaded, this is the related HTML:
<select name="best-player" id="best-player" class="form-control">
<option value="1">Ashley</option>
</select>
How can I achieve this?
To have a selected option, you can just set the best_player as the one you want to have by default selected.
With below code I am iterating over your player array and finding the player which has round.best_player === 1. The idea is to set the best_player with the selected option.
best_player = player.filter(p => p.round.best_player === 1).id

Option value not changing with user selection

I have a form with the following dropdown selection menu in HTML:
<div class="input-field col s4">
<select id="disposition" required>
<option value="No_Sale" id="noSale">No Sale</option>
<option value="Sale" id="yeahSale">Sale</option>
<option value="Unreachable" id="noContact">Unreachable</option>
<option value="Call_Back" id="callBack">Call Back</option>
</select>
<label>Disposition</label>
</div>
The above snippet for dispositions should affect whether or not other form elements are disabled. However, I cannot seem to get the value to change on user input.
Here is the javascript with jQuery:
$(document).on('change', 'select', function(){
console.log(disposition);
console.log($("#yeahSale").selected == true);
if ($("#yeahSale").selected == true) {
$("#fund").removeAttr('disabled');
}
});
For both $("#disposition").val() and $("#yeahSale").selected, the console.log returns
"No_Sale"
and false when I click on the form element and select
"Sale."
The first thing I tried was:
if (disposition == "Sale")
I have also tried:
var disposition = $("#disposition").find(":selected").text();
I've been searching stack exchange and google for answers for almost an hour but I haven't any success so far. My apologies if I just completely missed an extant question that's already been solved.
Thanks for your help!
$("#disposition").val() gives you the value of selected option.
So you simply want to put condition according to the value you got selected.
$(document).on('change', '#disposition', function(){
/*
If you want to put condition based on
option with specific id is selected or not then
if($("#yeahSale").is(':selected')) {
}
*/
if ($("#disposition").val() == 'Sale') {
// Do here what you want to do
// $("#fund").removeAttr('disabled');
console.log("Sale Selected");
} else {
console.log("Selected Option is: "+ $("#disposition").val());
}
//Get Id attr of selected option
console.log("Id of selected option is: " + $(this).find('option:selected').attr('id'));
// Check weather option with specific Id is selected or not:
console.log($("#yeahSale").is(':selected'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-field col s4">
<select id="disposition" required>
<option value="No_Sale" id="noSale">No Sale</option>
<option value="Sale" id="yeahSale">Sale</option>
<option value="Unreachable" id="noContact">Unreachable</option>
<option value="Call_Back" id="callBack">Call Back</option>
</select>
<label>Disposition</label>
</div>
If you want to get id attribute of selected option you can use this
$(this).find('option:selected').attr('id')
If you want to see option with ID yeahSale is selected or not than try this:
$("#yeahSale").is(':selected')
<div class="input-field col s4">
<select id="disposition">
<option value="No_Sale">No Sale</option>
<option value="Sale">Sale</option>
<option value="Unreachable">Unreachable</option>
<option value="Call_Back">Call Back</option>
</select>
<label>Disposition</label>
</div>
<script>
$(document).on('change', function(){
alert($("#disposition").val());
console.log($("#yeahSale").selected == true);
if ($("#yeahSale").selected == true) {
$("#fund").removeAttr('disabled');
}
});
tested and found it working
var disposition = $('#disposition').val();
$('#disposition').change(function() {
disposition = $(this).val();
console.log(disposition);
}
All you need is disposition.value and an onchange event.
The script below will acknowledge user input and return the updated disposition.value whenever a new selection is made:
var disposition = document.getElementById('disposition');
disposition.addEventListener('change', function(){console.log(disposition.value);}, false);
<select id="disposition" required>
<option value="No_Sale">No Sale</option>
<option value="Sale">Sale</option>
<option value="Unreachable">Unreachable</option>
<option value="Call_Back">Call Back</option>
</select>

Jquery Select field populates Input field

I am trying to Select one of the options from the drop-down and populate the input field with the correct values.
I want to set the value 1 to ($100) val 2 to ($200)
I will not have access to a database to store the values.
<div class="row">
<div class="form-group">
<select class="form-control" id="costfield" name=
"costfield">
<option value="Select Country"> Select Country</option>
<option value="1"> country 1</option>
<option value="2"> country 2</option>
<option value="1"> country 3</option>
</select>
</div>
</div>
<div class="form-group">
<input type="estimate" class="form-control" id="exampleInputEstimate1" placeholder="Estimate">
</div>
</div>
<script>
$( "#costfield" ).val();
$( "#estimate" ).text( "this" ).show();
</script>
</div>
You can store the values in the HTML5 data- attribute for each <option> element. This approach is useful when there is no direct relationship between the option's value attribute and the dollar value you are assigning it to.
p/s: type="estimate" is not a valid attribute value. Try type="text" (anyway, browsers will parse invalid type into text automagically.
// Listen to change
$('#costfield').change(function() {
$('#exampleInputEstimate1').val($(this).find('option:selected').data('dollar-value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<select class="form-control" id="costfield" name="costfield">
<option value="Select Country">Select Country</option>
<option value="1" data-dollar-value="$100">country 1</option>
<option value="2" data-dollar-value="$200">country 2</option>
<option value="1" data-dollar-value="$100">country 3</option>
</select>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" id="exampleInputEstimate1" placeholder="Estimate" />
</div>
$('[name="costfield"]').change(function () {
console.log("test");
var cost = this.value;
var str = "";
switch (cost) {
case "1":
str = "$100";
break;
case "2":
str = "$200";
break;
}
$("#exampleInputEstimate1").val(str);
});
JSFiddle
You could use jQuery to get the value from the Select when it changes and then change the value of the input accordingly. So put this in between the script tags.
$('#costfield').on('change', function() {
var value = $(this).val();
$('#exampleInputEstimate1').val(value);
});
You can either set your option values to be 100 or 200 then on any change in the drop down set the value of your input to the value.
$("#costfield").on("change", function(){
$("#exampleInputEstimate1").val($("#costfield").val());
} );
If you want to keep your option values as they are then you can still use the same as above with a small change. (on the assumption that 1 will be 100, 2 will be 200, 3 will be 300, and so on)
$("#costfield").on("change", function(){
$("#exampleInputEstimate1").val($("#costfield").val() + "00" );
} );
Also you may want to put a new option and set it as blank with no value that way you force the user to select something. Or you can set the input on document load and keep the number of options you have. AKA:
<option value="" ></option>

only one value is equal to and selected in multiple select

I have the exact same question as this:
jQuery Hide / Show input when selected option is equal to
However, it doesn't work when you go to multiple select, when the specific option is selected it works, but when you select another option alongside it stops working.
The question again is this: I want to show a div(#showme) if option 4 was selected, and I want to to work even if option 3 & 4 were selected, so at any given time if option 4 was selected the div should show.
This is the Javascript & HTML I have so far: (please note that I have more than one select in this form)
$('select[multiple]').each(function() {
$(this).change(function() {
obj = '#' + $(this).attr('id') + '_desc';
if($(this).val() == "4") {
$(obj).parent().parent().parent().removeClass('hide');
$(obj).css('display','block');
}
else {
$(obj).parent().parent().parent().addClass('hide');
$(obj).css('display','none');
}
});
});
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1">Hello?</label>
<select class="form-control selectpicker show-tick" name="feedback_q1[]" id="feedback_q1" multiple="multiple" title="Choose...">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</div>
</div>
<div class="row hide">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1_desc">desc <span class="glyphicon glyphicon-pencil"></span></label>
<textarea name="feedback_q1_desc" id="feedback_q1_desc" class="form-control" data-toggle="tooltip" data-placement="top" title="desc" rows="2"></textarea>
</div>
</div>
</div>
Thanks for the help
When multiple selections are made, $(this).val() will contain an array of the values. Iterate through them and check for '4'. If $(this).val() is null, then nothing has been selected.
The example below does exactly what you want, including the changes after our extensive exchange in the comments and chat, including your most recent request to handle values pre-selected when the document loads.
Additionally, you were missing the bootstrap JavaScript file, and the files you were already including were in the wrong order and wrong location. The example below includes all of the .js and .css files in the correct order and location.
HTML
<!-- These should be in head -->
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" rel="stylesheet" />
<!-- Body content -->
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1">Hello?</label>
<select class="form-control selectpicker show-tick" name="feedback_q1[]" id="feedback_q1" multiple="multiple" title="Choose...">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
<option value="4" selected>4</option>
</select>
</div>
</div>
</div>
<div class="row hide">
<div class="col-sm-12">
<div class="form-group">
<label for="feedback_q1_desc">desc <span class="glyphicon glyphicon-pencil"></span>
</label>
<textarea name="feedback_q1_desc" id="feedback_q1_desc" class="form-control" data-toggle="tooltip" data-placement="top" title="אנא פרט" rows="2"></textarea>
</div>
</div>
</div>
<!-- These should be at the end of <body> -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
JavaScript
// Check a select for a specific value and show/hide div based on selection
// Select will come in as a jQuery object
function checkSelect(control) {
// Build selector for associated description field
var selector = '#' + control.attr('id') + '_desc';
// Handle scenario where nothing is selected
if (control.val() == null) {
$(selector).parent().parent().parent().addClass('hide');
$(selector).css('display', 'none');
return;
}
// Get array containing selected values
var vals = control.val();
// Handle scenario where something is selected
for (i = 0; i < vals.length; i++) {
if (control.val()[i] == "4") {
$(selector).parent().parent().parent().removeClass('hide');
$(selector).css('display', 'block');
return; // Stop checking as we know the value we want is selected
} else {
$(selector).parent().parent().parent().addClass('hide');
$(selector).css('display', 'none');
}
}
}
// This runs when the DOM is ready
$(function () {
// Bind selectpicker
$('.selectpicker').selectpicker();
// Iterate through all multiple selects
$('select[multiple]').each(function () {
// Check for pre-selected values when page first loads
checkSelect($(this));
// Bind to change event so that values are checked after something is changed
$(this).change(function () {
checkSelect($(this));
});
});
});
Demo (third version): http://jsfiddle.net/BenjaminRay/7ckp7epf/
<div class="form-group">
<select class="form-control selectpicker show-tick" name="Status" id="Status" multiple="multiple" title="Choose...">
#foreach (SelectListItem item in ViewBag.Status)
{
if (item.Selected == false)
{
<option value="#item.Value">#item.Text</option>
}
else
{
<option value="#item.Value" selected>#item.Text</option>
}
}
</select>
</div>

Categories

Resources