Jquery to get the value of Dropdown list - javascript

I'm using following html for dropdownlist,
<select id="dd">
<option>Select ReportType</option>
<option value="1">Blocked Details</option>
<option value="2">Supervisor Input</option>
</select>
Following code for a button,
<input type="button" name="Excel" value="ExportToExcel" onclick="javascript:DownloadExcel($('#dropdown').val());" />
Following is the Jquery function,
function DownloadExcel(value)
{
debugger;
if(value=="Blocked Details"){
value="1";
}
else if(value=="Supervisor Input"){
value="2";
}
$.ajax({
url:"#Url.Action("TravelReadyAdminDownload", "TravelReady")",
datatype:"html",
type:"post",
data:{Id:value},
error:function(){},
success:function(data){
window.location.href=data.url;}
});
}
is it possible to get the dropdown values("1/2" instead of "Blocked Details/Supervisor Input").What is the javascript i need to use to get the value in that function?

Selected dropdown value can be fetched like
$('#dd').val();
or
$('#dd option:selected').val();
EDIT: Actually you're doing it right, following are your mistakes
1) wrong selector
$('#dropdown').val()// WRONG selector
it has to be
onclick="javascript:DownloadExcel($('#ddd').val());" //Correct
2) value parameter will hold only value (1 or 2) not text (Blocked Details or Supervisor Input)
Also following is the right way
if(value=="1"){
//do something
}
else if(value=="2"){
//do something
}

Can you try the following
$('#dropdown :selected').val()

Related

change selected value in msdropdown

I'm trying to use the msDropdown JavaScript plugin (https://github.com/marghoobsuleman/ms-Dropdown) to create html tags that include images.
It seems to work good except for if I try to change the selected value using JavaScript.
Like in this jsFiddle: https://jsfiddle.net/cmu845eh/7/
I'm trying to make it so that if you call the setValue() function, it will change the selected value to a certain index.
I've tried multiple different solutions online but none work, solutions such as this:
var oHandler = $("#main").msDropDown().data("dd");
oHandler.set("length", 0);
always result in an error, and more basic jquery approaches dont work either.
Can someone help me change the value of my select tag to a certain index using javascript?
Using msdropdown
Let me give you a full code on how to populate select dropdown from server-side using another select dropdown.
1st Select Dropdown
<select name="" id="from" class="selectFlags" style="width:100%;">
<option value="2" title="https://fxtop.com/ico/aon.gif">GBP</option>
<option value="3" title="https://fxtop.com/ico/aon.gif">GBP</option>
</select>
2nd Select Dropdown
<select name="" id="selectFlagTo" class="selectFlagTo form-control" style="width:100%;height:52px;">
</select>
JScript
<script language="javascript">
$(document).ready(function(e) {
try {
$(".selectFlags").msDropDown({mainCSS:'dd'});
} catch(e) {
alert(e.message);
}
$(".dd").css({ 'width' : '100%' });
});
$(document).on("click",".dd .ddChild",function(e){
let $from=$("#from option:selected").val();
let $to=$("#selectFlagTo");
$to=$to.empty();
$(".dd").css({ 'width' : '100%' });
$(".dd2").css({ 'width' : '100%' });
$.ajax({
url: "http://odin.test/load_countries",
type: "POST",
data: {from:$from},
success: function(response) {
$.each(response, function(key, entry) {
$to.append("<option title='https://fxtop.com/ico/aon.gif' value='"+entry.id+"'>"+entry.name+"</option>" );
});
var oDropdown = $(".selectFlagTo").msDropDown({mainCSS:'dd2'});
$(".dd3").css({ 'width' : '100%' });
}
});
});
</script>
Enjoy coding!!!
Solved it here by fixing how I was initializing the msdropdown element after the html was created.
https://jsfiddle.net/uvbjhy31/

JQuery Selector not working, where looping does. Why?

I have two jquery selectors that I used which did not find the desired option where the third "brute force" method did. I am at a complete loss as to why. Each looked like they should of and I validated the document was fully loaded when the selector ran. I tried each with value and text in the selector and got the same result in my page. The html is dynamically loaded using the jquery load method below (where theType is a value coming from a html select control) as well as the associated javascript:
var theType = $('#TicketType option:selected').val();
var theId = $("#Id").val();
var url = '/SystemBuildSiteConfigs/' + theType + '/' + theId;
$('#ticketDiv').html("");
$("#ticketDiv").load(url, function (response, status, xhr) {
if (status == "error") {
alert("There was an error loading the " + theType + " form");
}
else {
$.getScript("/Scripts/SiteConfig" + theType + ".js", function () {
});
}
});
The html select in question:
<select name="SupportOrganization" class="form-control" id="SupportOrganization">
<option value="">- Please Select -</option>
<option>Auxiliary IT</option>
<option>Business Intelligence</option>
<option>Change Management</option>
<option>Engineering RnD</option>
<option>Enterprise Business Solutions</option>
<option>Enterprise Solutions</option>
<option selected="selected">Hosting</option>
<option>Infrastructure and Operations</option>
<option>Manufacturing</option>
<option>Professional</option>
<option>Support</option>
</select>
First selector statement:
$("#SupportOrganization").find('option[value="' + jsonObj.SupportOrganization + '"]').attr("selected", true);
Second selector statement:
$('#SupportOrganization option[value="' + jsonObj.SupportOrganization + '"]').attr("selected", true);
What worked:
$('#SupportOrganization option').each(function (idx, ele) {
if ($(ele).val() == jsonObj.SupportOrganization)
$(ele).attr("selected", true);
});
The page segment loads correctly and all the other javascript that fires to load html controls with content are executing as expected. Another page type loads and fires correctly performing similar functions. Using jsfiddle, both selectors show they work correctly. What I found through testing was
The variable did have the expected value.
The text selector did not work correctly on my page
The value selector did select an object. However I was unable to determine what the object was and the attr() method did not set the target attribute value.
I can go with what I found that will work, just wanted to find out why this wouldn't work. Guessing it has something to do with the dynamically loaded html and javascript?
The jQuery .val() function uses a "hook" for <option> elements to return the text content of the element if the "value" attribute is missing. Your <option> elements don't have "value" attributes, so the selector does not match.
You should select option by using the select .val(string) function, it will find the option with matched string if available in options having value attribute.
So, Your options should be containing the value attribute which is missing in your case e.g:
$(function(){
$("#userEducationDegree").val('A');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree">
<option value="-1">--Select--</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
To continue with what #Pointy said above, you should try :contains instead.
$('#SupportOrganization option:contains("' + jsonObj.SupportOrganization + '")').attr("selected", true);

jQuery SELECT with Textarea

Just wondering if someone can help me on a problem, I don't fully undersand why it doesn't work.
I have this fiddle, http://jsfiddle.net/uomt99zp/
What it is doing:
When you select from the drop down box, insert that word into the textarea.
Which it DOES, when the textarea isn't "touched".
If you type something into the box, and then try to select an item, it doesn't work.
I'm not sure why this doesn't update the textarea. Perhaps someone can shed some light on this issue?
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
You need to set value using .val():
$('.template').val($('.template').val()+text);
Working Demo 1
Also .val() can have callback function which can be used for setting a new value:
function
Type: Function( Integer index, String value ) => String
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
$('.template').val(function(i,v){ return v+ text});
Working Demo 2
You can try val(function) with old value + new text to append,
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').val(function(ind,val){
return val+text;
});
});
Live Demo
To answer to the "why" it does not work, it's because, the contents of a textarea represent its default value. So, when you append an element to the textarea, you change the default value of this textarea.
So it changes the textarea as long as you did not type in. Once you typed in, the default value is no more used, even if you remove all the text of the textarea.
By using .append you are just concatinating your output string if you want only the dropdown element it would be better to use the .text() or .val() method
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
var existing=$('.template').val();
$('.template').val(existing+text);
});
.append(), .html() and .text() methods do not work with form elements, for setting/getting value of a from element .val() method should be used instead:
Your code is working ...i tried it in visual studio .... Only change I had made is I kept the script under the option control... I am not sure about.for me its working fine.
<body >
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
<script type="text/javascript">
$('.templatesAvailableFields').on('change', function () {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
</script>
</body>
You should control input value's with val() method
// cache element
var $select = $('.templatesAvailableFields');
$select.change( function() {
$('.template').val($select[0].value);
});
just replace append with text
here is the updated fiddle
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').text($('.template').text() + text);
// $('.template').val(text); this won't work in IE <= 7
});
http://jsfiddle.net/rrehan/uomt99zp/2/

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

How do I select displayed value as opposed to VALUE options?

We have the following SELECT combobox that is populated dynamically with ajax and httphandler web service (.ashx).
When SELECT combobox is dynamically populated, it looks like this:
<select name="selectid" id="selectid">
<option value="">-Select an option-</option>
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</o4tion>
<option value="4">Test5</option>
<option value="5">Test6</option>
<option value="6">Test7</option>
</select>
Below is the js:
function getText() {
$.ajax({
url: 'rulings.ashx',
dataType: 'json'
})
.done(function(textInfo) {
$(textInfo).each(function(i, texts) {
$('<option>').val(texts.dbtextID).text(texts.textToBeDisplayed).appendTo( $('#selectid') );
})
});
}
When we display the values from the dropdown, it displays the VALUE options instead of the displayed text.
Example from the combobox above, it displays 1 instead of Test1.
How do I modify the script to show displayed text instead of VALUE options?
Try this code , just put it inside
$(document).ready(function(event){
$("#selectid").on('change',function() {
//alert($("#selectid option:selected").text());
$('#summTextvalue').html($("#selectid option:selected").text());
});
})
The ON method in jQuery can bind events to dynamically created elements.
or you can also do something like
function _bindEvent()
{
$("#selectid").on('change',function() {
alert($("#selectid option:selected").text());
});
}
and call _bindEvent() from your AJAX done method
Try this to get text, instead of value.
$('#selectid').change(function(){
var selectedVal=$(this).val();
alert($(this).children("option[value='"+selectedVal+"']").text());
});

Categories

Resources