jQuery onChange prop a value to inputs - javascript

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();

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;
});

Onchange event for multiple dropdowns issue

I have a list like this:
<form>
<select id="List_22" >
<option value="default">Default</option>
<option value="1">Oil</option>
<option value="2">Gas</option>
<option value="3">Power</option>
</select>
<form>
I want to launch a function upon dropdown change, so this works fine:
document.getElementById("List_22").onchange = function() {...
I however have multiple dropdowns that should all use the same function. I have tried to use the below wildcard but it does not work
document.getElementById("[id^=L]").onchange = function() {
What am I doing wrong? I am going slightly barmy. Thank you all for your time.
The issue is document.getElementById looks for an exact ID match for a single element, so it doesn't support attribute selectors and nor does it return multiple elements.
In plain old JavaScript you can use document.querySelectorAll which supports CSS selectors, and the attribute selector. Note that this isn't supported before IE8.
var list = document.querySelectorAll('[id^=L]');
for(var i=0; i<list.length; i++){
list[i].onchange = function(){
// do something on change....
};
}
Or since you have jQuery tagged, a jQuery version:
$('[id^=L]').change(function(){
// do something on change....
});
Side note: In both cases, I would prefer to make the attribute selector more specific such as select[id^=List_].
$('form select').on('change', function(){
// Your code here
});
In plain javascript, you could do this generic search which should work in every browser and no need to regular expressions.
var dropdowns = document.getElementsByTagName("select"),
item;
for (var i = 0, count = dropdowns.length; i < count; i++) {
item = dropdowns[i];
if (item.id && item.id.indexOf("List_") == 0) {
item.onchange = function () {
alert(this.options[this.selectedIndex].text);
};
}
}
Working example: http://jsfiddle.net/Rq9nb/
Best procedure for cases like this would be, to add a common class to all the dropdowns for which you want to call the function on change. For ex: add 'trigger-change' class for all your required dropdowns. Then below bind event should work perfect for you.
$('form select.trigger-change').on('change', function(){
// Your code here
});
This way, you can choose the dropdowns for which you want to trigger a change event funciton and you can also have dropdowns which are not triggering the change event functions.
Hope this helps :)

Selected value on a cloned item not working as expected

Fiddle is here, containing this code: http://jsfiddle.net/enp2T/6/
<select id="aList">
<option value="0">0</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="300">300</option>
</select>
<div id="newListContainer"></div>
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
var listHtml = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
I thought that my selected value of 300 would be maintained, but listHtml just contains a clone of the original list. I'm in a situation where it would be painful to try to re-find the object and set its value after it gets drawn (passing it to another external libraries function defers rendering till later, no complete callback unless I modify that library directly which I'm trying to avoid).
So am I doing something horribly wrong? Missing a quirk?
Clarification: I need to pass the HTML as a string, as the library that is using it is expecting a string.
There's no reason to make a round-trip to markup for this, and I suspect that's the problem, as jQuery's val sets the selectedIndex of the select element, which doesn't get serialized.
Just use the cloned element:
var wrappedList = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent();
// Note: Not doing `.html()` at the end
// html(...) would empty the container and then add the HTML, so
// we empty the container and then append the wrapped, cloned list
$('#newListContainer').empty().append(wrappedList);
Updated working fiddle
jQuery clones the list with whatever you have selected - the problem here is that you don't have anything selected, so you're cloning a dropdown without a selected value (see here).
For an updated version of that script, check this updated jsFiddle.
Code:
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
clonedList.find('option[value="' + value + '"]').attr('selected', 'selected');
var listHtml = clonedList
.removeAttr('id')
.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
See this link. You can't set value to the select, you must set selected attribute to item with value=300.
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
clonedList.find('option[value="' + value + '"]').attr("selected", true);
var listHtml = clonedList
.removeAttr('id')
//.val(value)
.wrap('<div/>')
.parent()
.html();
$('#newListContainer').html(listHtml);
//$('#newListContainer>select').val(value);
});
I have a mistake. #T.J. Crowder is right. jQuery can set value of select by .val(value) function. link
$(function() {
var value = 300;
var clonedList = $('#aList').clone();
var holderCloned = clonedList.removeAttr('id').val(value).wrap('<div/>').parent();
$('#newListContainer').empty().append(holderCloned);
});

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