Javascript set selected value of dropdownlist by text - javascript

I am using Jquery Datatables with inline editing. I have a hardcoded dropdownlist which is beeing created for each row dynamicly.
<select class="form-control edit-mode" id="Status">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
So to get the value of the currently selected item I use
var tr = $(this).parents('tr:first');
var status = tr.find('#Status').val();
And the value I want to set it to is in the label next to it. So I get the value of that with:
var stat = tr.find('#lbl_Status').html();
So how do I set the selected value of the dropdownlist to the stat variable?
I have tried using the other solutions I found on Stackoverflow but they are not working since I can't seem to get the whole element or something. Since .length is not working on the status element. And I cannot use the normal document.getElementById method since it can be multiple select lists with the same ID.
F.ex with this solution:
$(document).on("click", ".edit-action", function (e) {
var tr = $(this).parents('tr:first');
var stat = tr.find('#lbl_Status').html();
var status = tr.find('#Status');
for (var i = 0; i < status.options.length; i++) {
if (status.options[i].text === stat) {
status.selectedIndex = i;
break;
}
}
});
I get: Uncaught TypeError: Cannot read property 'length' of undefined

status is jquery object,Use:
status.find('option').length;
or convert to javascript object and use:
status[0].options.length
Demo

I solved this by just using this line instead of the whole for loop.
status.find("option:contains("+ stat +")").attr('selected', true);
Thanks for pointing out that it was a Jquery object which led me to the answer :)

Related

Unable to select first item of dynamically generated select with jquery

I am dynamically generating a select contol with jQuery on my page. The generated select is given below.
<select id="autoCompleteSelect" size="5" class="autoSelect">
<option value="firstVal">firstVal</option>
<option value="secondVal">secondVal</option>
</select>
Now i want to select the first item of this select control on my textbox keyup event. But i cannot do so. The keyup code is -
$('#searchInput').keyup(function (e) {
var a = $(".autoSelect").val();
var myDDL = $('.autoSelect');
myDDL[0].selectedIndex = 0;
});
however when i do not generate select dynamically and just put it on the page from the beginning. Everything works fine. What could be the solution for dynamically generated select.
$("#autoCompleteSelect").val($("#autoCompleteSelect option:first").val());
http://jsfiddle.net/oob1ybxp/
If working with dynamically generated content, it is best to use event delegation concept like below:
// document here can be replaced with closest parent which
// created/ existed without dynamic load
// provided context parameter to on function
$(document).on('keyup','#searchInput', function (e) {
var a = $(".autoSelect").val();
var myDDL = $('.autoSelect');
myDDL[0].selectedIndex = 0;
});
Read this .on() also.
Keep your code in the form something like
$('someStaticSelector').on('keyup', 'DynamicAddedSelector', function (e) {
var a = $(".autoSelect").val();
var myDDL = $('.autoSelect');
myDDL[0].selectedIndex = 0;
});

How to select an option via jquery

I have a select form that looks kind of like this:
<select multiple="multiple" id="id_color_id" name="color_id"">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Brown</option>
</select>
What I want to do is select the item above via javascript. This is actually part of a hidden form, so all I'm trying to do is leverage the serialize part of the form. I'm thinking it will just be easier to hack that after the serialize then to add this as well, but I also want to deselect any options that have already been selected.
So two questions:
How to select an option via javascript. All I will know is "Red", "Blue" or "Brown". I also have a look up dictionary that can get me the values as well.
How to deselect all options previous to selecting one of the above.
This is related to: Selecting options in a select via JQuery
Native Javascript:
var textToFind = 'Red';
var dd = document.getElementById('id_color_id');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
break;
}
}
or with jQuery:
$('#id_color_id option:contains('Blue')').prop('selected',true);
with variable:
var blue = "Blue";
$('#id_color_id option:contains(' + blue + ')').prop('selected',true);
And to deselect all selected options:
Native Javascript:
var elements = document.getElementById("id_color_id").options;
for(var i = 0; i < elements.length; i++){
if(elements[i].selected)
elements[i].selected = false;
}
jQuery:
$("#id_color_id option:selected").removeAttr("selected");
To select an option by it's content (considering what you posted is what you have)
$("#id_color_id option:contains('Red')").prop('selected',true);
jsFiddle Demo
You can set the value on the select box using the .val() method. Running this will reset any previously selected values, so you don't need to do anything specific to accomplish that part. You can also use an array to select multiple values, which may be of interest, since you are using a multi select.
$("#id_color_id").val(['1','2']);

jQuery onChange prop a value to inputs

I have a <select> drop down that I'm inserting into my HTML via jQuery. I don't have control over the HTML but I do have control over the JavaScript.
I'm trying to prop a value to an <input> element when you select an option. Basically, I have a <select> element with <option id="1"> and <option id="2"> onChange of this <select> element;
If you select option#1 it should prop the value dummy1 to input[name="Check_Config_PaymentGateway_CreditCards_Login1"] and the value dummy2 to input[name="Check_Config_PaymentGateway_CreditCards_Password"]
If you select option#2 it should prop the value dummy3 to input[name="Check_Config_PaymentGateway_CreditCards_Login1"] and the value dummy4 to input[name="Check_Config_PaymentGateway_CreditCards_Password"]
I've been working on this jsFiddle.
I'm pretty new at JavaScript in general, let alone jQuery. This is way to sophisticated for my skill... If you can help me, I'd really appreciate it.
Here you go: http://jsfiddle.net/VW9N6/6/
This binds to the change event of the <select> element to detect when its value changes, and then updates the value of the <input> elements.
Try something like below,
Edit: Cached input text boxes.
DEMO
var dummyValues = [['dummy1', 'dummy2'], ['dummy3', 'dummy4']];
var $loginInput = $('input[name=Check_Config_PaymentGateway_CreditCards_Login1]');
var $pwdInput = $('input[name=Check_Config_PaymentGateway_CreditCards_Password]');
$('#paymentDD').change(function () {
var selectedVal = parseInt($(this).val(), 10) - 1;
$loginInput.val(dummyValues [selectedVal][0]);
$pwdInput.val(dummyValues [selectedVal][1]);
});
Updated dummyValues var as you add move options to the drop down.
I'm a fan of caching elements whenever possible, so that's what I do. I also saw that you were using the latest jQuery (1.7.2) in your jsFiddle, so why not use the recommended .on() method and then call an immediate .change() to populate on load?
You could try something like this:
var $span = $('span#print_pagename'),
$login = $('input[name="Check_Config_PaymentGateway_CreditCards_Login1"]'),
$password = $('input[name="Check_Config_PaymentGateway_CreditCards_Password"]'),
$select = $('<select><option id="1">1</option><option id="2">2</option></select>');
$span.after($select);
$select.on('change', function() {
var $this = $(this);
if ($this.val() === '1') {
$login.val('dummy1');
$password.val('dummy2');
} else if ($this.val() === '2') {
$login.val('dummy3');
$password.val('dummy4');
}
}).change();

How to get Dropdown selected value on client side onchange event?

I have written a code for dropdown selected index changed event at client side using onchange event and create one JavaScript function.
Now, I want to retrieve selected values in this function. How can I get this value?
$("#DropDownlist:selected").val();
This will give you selected text.
$("#mydropdownid option:selected").text();
This will give you selected value
$('#mydropdownid').val();
HTML :
<select id="mySelect" class="myClass">
<option value='1'>One</option>
</select>
jQuery :
Now for getting selected value you can use the one of the following:
ONE :
var selected_value = $("#mySelect").val();
TWO :
var selected_value = $(".myClass").val();
THREE :
var dropdown = $("#mySelect option:selected");
var selected_value = dropdown.val();
The simplest, inside the event handler:
$('#elementID').change(function(event) {
event.target.value;
};
event is the event object sent to the handler, target is the object in the DOM from which the event generated, and value it's the DOM element current value. In the case of a select box this will work perfectly to get your selected value.
As you have tagged jQuery, I assume that's what you are using.
Simply use jQuery val()
var v = $("#yourSelectID").val();
alert("The value is: " + v);
You should also be able to use plain javascript:
var e = document.getElementById("yourSelectID");
var v = e.options[e.selectedIndex].value;
alert("The value is: " + v);

How do I access the "displayed" text of a select box option from the DOM?

Given the following HTML:
<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>
How do I grab the string "displayed text 1" using Javascript/the DOM?
var sel = document.getElementById("my_dropdown");
//get the selected option
var selectedText = sel.options[sel.selectedIndex].text;
//or get the first option
var optionText = sel.options[0].text;
//or get the option with value="1"
for(var i=0; i<sel.options.length; i++){
if(sel.options[i].value == "1"){
var valueIsOneText = sel.options[i].text;
}
}
var mySelect = document.forms["my_form"].my_dropdown;
// or if you select has a id
var mySelect = document.getElementById("my_dropdown");
var text = mySelect.options[mySelect.selectedIndex].text;
Assuming you want the selected option's text:
var select = document.getElementById('my_dropdown');
for(var i = 0; i < select.options.length; i++) {
if(select.options[i].selected) {
break;
}
}
var selectText = select.options[i].text;
In Prototype:
var selectText = $$('#my_dropdown option[selected]')[0].text;
Edit: And jQuery for completeness' sake (assuming jQuery's CSS selector support is roughly equivalent to that of Prototype's):
var selectText = $('#my_dropdown option[selected]').get(0).text;
The displayed text is a child node of the option node. You can use:
myOptionNode.childNodes[0];
to access it, assuming the text node is the only thing inside the option (and not other tags).
EDIT: Oh yeah, as others mentioned, I completely forgot about:
myOptionNode.text;
Assuming you modified your code a bit to have an id / class on the and were using jQuery you could have something like the following. It will pop up an alert for each option with the text of the option. You probably won't want to alert for all the text, but it illustrates how to get at the text in the first place:
$('select#id option').each(function() {
alert($(this).text());
});
If you use a class instead of an id, then you'd just have to change the 'select#id' to 'select.class'. If you didn't want to add a class/id there are other ways to get at the select.
I leave figuring those ways out if you want to go that route as an activity for the reader.
If you were using Prototype, you could get at it like this:
$$('#my_dropdown option[value=1]').each( function(elem){
alert(elem.text);
});
The above is using a CSS selector that says find all option tags with value="1" that are inside the element that has id="my_dropdown".

Categories

Resources