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;
});
Related
I'm new to JQuery and I noticed this line $('#DivID [type=checkbox]') and I was wondering if I can also find the select or option tags using the same method.
Update: I have a div that has more than more tag, I'm trying to get the DropDownList/Select that it's value's just changed.
Update2 I'm using InstaFilta a JQuery plugin that filter the content based on a customized attribute appended to my content tags. Below is a snippet for the function that do the same when working with CheckBoxes, and I'm trying to edit it to work with DropDownLists/Select controls.
var $ex10Checkboxes = $('#ex10 [type=checkbox]');
$ex10Checkboxes.on('change', function() {
var checkedCategories = [];
$ex10Checkboxes.each(function() {
if ($(this).prop('checked')) {
checkedCategories.push($(this).val());
}
});
ex10.filterCategory(checkedCategories, true);
});
You would find the option tags as follows:
$("#DivID option")
Likewise the select tags:
$("#DivID select")
You can then iterate over the returned objects to inspect the individual elements:
var foo = $("#DivID option");
var i;
for (i = 0; i < foo.length; i += 1) {
console.log(foo[i].val()); //or whatever
}
To find the selected element you could check out this question:
$("#DivID option:selected")
I would suggest checking out the JQuery page on Selectors JQuery Selectors
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 :)
I want to have on my html-site an combobox like on the following img. I want to get the selected values and print in out. How can I create this comboBox?? I have tried the Google API Visualization CategoryFilter Control. But you can not customize the google control.
Thank you
I just mocked up a combo-box like you described: http://jsfiddle.net/twwGM/
Basically, you need to use JS to capture the onchange event of the select box, and then append its value to some target area with specific styling by generating an HTML string from your function. Keep styles out of the JS and instead style it through the use of a CSS class.
HTML Markup:
<form>
<select id="selector">
<option>Magic</option>
<option>Canaries</option>
<option>Unicorns</option>
</select>
</form>
<div id="target-area"></div>
JS Code
(function () {
document.getElementById("selector").addEventListener("change", function () {
var val = this.options[this.selectedIndex].value;
var genId = val + "-close";
if (!document.getElementById(genId)) {
var htmlstr = "<div class='pasted-option'>" + val + "<span id='" + genId + "'>x</span></div>";
var targetArea = document.getElementById("target-area");
targetArea.innerHTML += htmlstr;
var closeButton = document.getElementById(genId);
closeButton.addEventListener("click", function () {
var parent = this.parentNode;
parent.parentNode.removeChild(parent);
});
}
});
}(window));
As you can see within the code, we also generate an id for the span based on the item's name so that we can make a call to it later for removal from the list. It also gives us the ability to check and make certain the value doesn't already exist within the list.
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();
I have written a script that will load a series of products into a div tag.
I now want to be able to filter those products using a series of checkboxes.
jquery makes a $post to an ASP page that returns an XML dataset. The first element of the data set contains a list of manufacturers in this format ara|dai|sid|alp etc. The second element contains the manufacturer names of the codes above.
I then use this script to build a list of checkboxes into a div tag.
var mc = new Array();
mc = $("manCodes",xml).text().split(",");
var manTitles = new Array();
manTitles = $("manTitles",xml).text().split(",");
for ( var i=0, len=mc.length; i<len; ++i ){
m += '<span><input type="checkbox" value="' + mc[i] + '" name="man[]" id="man_'+i+'" />' + manTitles[i] +'</span>'//mc[i];
}
manufacturers = '<div id="filter" class="man">FILTER<br />' + m + '</div>';
$(".formSelect").append(manufacturers);
This works a treat and then in the Document Ready section I have a code segment that looks for any click on a checkbox:
$(document).ready( function() {
$("input:checkbox").click(function() {
loadXML($("#sortOrder option:selected").val(),$("#limitBy option:selected").val(),$("#productGroup").val());
});
});
This is where my code falls over because any click on any checkbox is not working. Its almost like JQuery cannot see these checkboxes that it has created.
Can anybody please help how to resolve this problem please?
Cheers
Graham
You need event delegation, otherwise the event handler will not fire for dynamically inserted/removed elements. .live or .delegate are two options.
$("input:checkbox").live("click", function() {
// implementation
});
or better:
$("form").delegate("input:checkbox", "click", function() {
// implementation
});
use jQuery.live() to capture events from dynamically added elements.
Attach a handler to the event for all
elements which match the current
selector, now and in the future.
$("input:checkbox").live("click", function() {
loadXML($("#sortOrder option:selected").val(),$("#limitBy option:selected").val(),$("#productGroup").val());
});
Try:
$(document).ready( function() {
$("input:checkbox").live("click",function() {
loadXML($("#sortOrder option:selected").val(),$("#limitBy option:selected").val(),$("#productGroup").val());
});
});