I have a chunk of jQuery that isn't quite behaving the way I expect.
I'm taking the selected value from an HTML dropdown and storing it in a variable. The variable is then used to select an HTML element ID.
Here's the <select> I'm using for the dropdown:
<select id="bubble-tea-flavor" class="" name="attribute_bubble-tea-flavor" data-attribute_name="attribute_bubble-tea-flavor" data-show_option_none="yes">
<option value="">Choose an option</option>
<option value="Kiwi Apple" >Kiwi Apple</option>
<option value="Peach Mango" >Peach Mango</option>
<option value="Pineapple Peach" >Pineapple Peach</option>
</select>
Here are the HTML tags I am trying to target:
<rs-slides>
<rs-slide data-key="rs-1" data-title="pineapplepeach" data-anim="ms:1000ms;" data-in="o:0;" data-out="a:false;" class="pineapplepeach" id="pineapplepeach">
...
</rs-slide>
<rs-slide data-key="rs-3" data-title="peachmango" data-in="o:0;" data-out="a:false;" class="peachmango" id="peachmango">
...
</rs-slide>
<rs-slide data-key="rs-4" data-title="kiwiapple" data-anim="ms:1000ms;" data-in="o:0;" data-out="a:false;" class="kiwiapple" id="kiwiapple">
...
</rs-slide>
</rs-slides>
Here is the jQuery snippet:
jQuery(function($) {
$( "#bubble-tea-flavor" ).change( function() {
var slide = $(this).children("option:selected").val();
console.log(slide);
var selectedFlavorID = slide.replace(/\s+/g, '').toLowerCase();
console.log(selectedFlavorID);
revapi1.revcallslidewithid(selectedFlavorID);
});
});
It definitely works to some extent. The console log shows the value is being captured and modified correctly:
JQMIGRATE: Migrate is installed, version 3.3.2
(index):290 Peach Mango
(index):292 peachmango
(index):290 Pineapple Peach
(index):292 pineapplepeach
(index):290 Kiwi Apple
(index):292 kiwiapple
But then... nothing happens. What am I doing wrong?
Or, since this is for Revolution Slider and is probably more complicated than I'm thinking about it, how do I use Chrome to see what's happening when revapi1.revcallslidewithid(selectedFlavorID); is called?
For reference, here is the entire <script> tag where my snip comes from:
<script type="text/javascript">
setREVStartSize({c: 'rev_slider_1_1',rl:[1240,1024,778,480],el:[900],gw:[1240],gh:[900],type:'standard',justify:'',layout:'fullscreen',offsetContainer:'',offset:'',mh:"0"});
var revapi1,
tpj;
function revinit_revslider11() {
jQuery(function() {
tpj = jQuery;
revapi1 = tpj("#rev_slider_1_1");
if(revapi1==undefined || revapi1.revolution == undefined){
revslider_showDoubleJqueryError("rev_slider_1_1");
}else{
revapi1.revolution({
sliderLayout:"fullscreen",
visibilityLevels:"1240,1024,778,480",
gridwidth:1240,
gridheight:900,
enableUpscaling:true,
perspective:600,
perspectiveType:"global",
editorheight:"900,768,960,720",
responsiveLevels:"1240,1024,778,480",
progressBar: {
style:"vertical",
horizontal:"center",
vertical:"top",
size:5
},
navigation: {
onHoverStop:false
},
fallbacks: {
allowHTML5AutoPlayOnAndroid:true
},
});
jQuery(function($) {
$( "#bubble-tea-flavor" ).change( function() {
var slide = $(this).children("option:selected").val();
console.log(slide);
var selectedFlavorID = slide.replace(/\s+/g, '').toLowerCase();
console.log(selectedFlavorID);
revapi1.revcallslidewithid(selectedFlavorID);
});
});
}
});
} // End of RevInitScript
var once_revslider11 = false;
if (document.readyState === "loading") {document.addEventListener('readystatechange',function() { if((document.readyState === "interactive" || document.readyState === "complete") && !once_revslider11 ) { once_revslider11 = true; revinit_revslider11();}});} else {once_revslider11 = true; revinit_revslider11();}
</script>
Related
I want to have a <select> without using the options binding, and nest the <option> element under an if binding.
The following is what I did (here's also a fiddle), which displays a behavior I wasn't expecting: The if seems to fire for each option selection, whereas what I expected is that it would fire only when adding the options elements to DOM.
Thus, when an option is chosen, it doesn't displayed. Only when choosing the same option again, it renders as it should.
What did I do wrong?
var DogHouseViewModel = function() {
var self = this;
self.allowedNames = ["A", "B", "C"];
self.puppies = ko.observableArray([]);
self.createPuppy = function () {
self.puppies.push(new DogViewModel());
}
self.isNameAlreadyTaken = function (puppyName) {
var puppies = self.puppies();
for (var i = 0; i < puppies.length; i++) {
if (puppies[i].dogName() == puppyName) {
return true;
}
}
return false;
}
self.printPuppiesName = function () {
self.puppies().forEach(function (puppy) {
alert(puppy.dogName())
})
}
}
var DogViewModel = function (dogName) {
var self = this;
self.dogName = ko.observable();
}
vm = new DogHouseViewModel()
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js"></script>
<div>
<button data-bind="text: 'create a puppy', click: createPuppy"></button>
<button data-bind="text: 'print puppies names', click: printPuppiesName"></button>
<div data-bind="foreach: puppies">
<select data-bind="value: dogName">
<!-- ko foreach: $parent.allowedNames -->
<!-- ko if: !($root.isNameAlreadyTaken($data)) -->
<option data-bind="value: $data, text: $data"></option>
<!-- /ko -->
<!-- /ko -->
</select>
</div>
</div>
I believe this is what you are trying to do. The problem is that your allowedNames are the values of the options do you can't just remove them from the array. But you can clone the parent array and as it changes compute the array by returning a list of not used values.
I also added a check to make sure we don't accidentally add a puppy object to the puppies array when no names are available.
var DogHouseViewModel = function() {
var self = this;
self.allowedNames = ["A", "B", "C"];
self.puppies = ko.observableArray([]);
self.createPuppy = function() {
var newPuppy = new DogViewModel(self);
if(newPuppy.allowedNames().length > 0) { // Check to see if there are any names left.
self.puppies.push(newPuppy);
}
}
self.removePuppy = function(obj) {
self.puppies.remove(obj);
}
self.printPuppiesName = function() {
self.puppies().forEach(function(puppy) {
alert(puppy.dogName())
})
}
}
var DogViewModel = function(parent) {
var self = this;
self.dogName = ko.observable();
self.allowedNames = ko.computed(function() {
var allowedNamesClone = parent.allowedNames.slice(0);
var usedNames = parent.puppies().filter(function(pup) { // get all pups who have a name
return pup.dogName() !== '' && pup.dogName() !== self.dogName();
})
usedNames.forEach(function(pup) {
var index = allowedNamesClone.indexOf(pup.dogName());
if (index > -1) {
allowedNamesClone.splice(index, 1); // remove name from cloned array
}
})
return allowedNamesClone; // return new array
})
}
vm = new DogHouseViewModel()
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div>
<button data-bind="text: 'create a puppy', click: createPuppy"></button>
<button data-bind="text: 'print puppies names', click: printPuppiesName"></button>
<div data-bind="foreach: puppies">
<!-- ko if: allowedNames().length > 0 -->
<select data-bind="options: allowedNames, value: dogName"></select>
<button data-bind="click: $root.removePuppy">x</button>
<!-- /ko -->
</div>
</div>
I'am new to angularjs, I'm creating an application of attendance. When i check the checkall checkbox all the checkbox of name is also check and What i really wanted to achieve is to get the value of checked checkboxes. I'm done with checking all checkboxes. I just want to store all the value of checkboxes in an array. I can only get data when i check those checkboxes one by one. Thank you in advance.
In my html here is my code.
<ion-checkbox ng-model="Selected" ng-click="checkAll()">
<div class="wew">
Check All Checkbox
</div></ion-checkbox>
</label></div>
<table><tr><th><center>
List of Names
</center></th>
<th colspan="3">
Actions
</th></tr><tr><td><label>
<ion-checkbox ng-repeat="role in roles" ng-model="isChecked" ng-
change="format(isChecked,role,$index)"><div class="wew">
{{role}}
</div></ion-checkbox>
</label></td>
And in my controllers code. First this is my code where i get the list of names.
$http.post(link1, {section: section}).success(function(attendance){
for(a = 0; a<attendance.length; a++){
$scope.roles = [
attendance[0].Full_Name,
attendance[1].Full_Name,
attendance[2].Full_Name,
attendance[3].Full_Name,
attendance[4].Full_Name,
attendance[5].Full_Name,
attendance[6].Full_Name,
attendance[7].Full_Name,
attendance[8].Full_Name,
attendance[9].Full_Name,
]
}
})
.error(function(err) {
console.log(err)
})
And this is my code where i wanted to execute the checkall and automatically store the data in $scope.selected = []; if i click the check all checkbox..
$scope.checkAll = function () {
if ($scope.Selected) {
$scope.Selected = false;
} else {
$scope.Selected = true;
}
$scope.isChecked= $scope.Selected;
$scope.selected = [];
$scope.format = function (isChecked, role, $index) {
if (isChecked == true) {
$scope.selected.push(role);
}
else {
var _index = $scope.selected.indexOf(role);
$scope.selected.splice(_index, 1);
}
var students = $scope.selected;
console.log(students);
}
}
try this code
<script>
$(function(){
var numbers = $("input[type='checkbox']:checked").map(function(_, el) {
return $(el).val();
}).get();
});
</script>
I'm using a <datalist>
<datalist id="items"></datalist>
And using AJAX to populate the list
function callServer (input) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
//return the JSON object
console.log(xmlhttp.responseText);
var arr = JSON.parse(xmlhttp.responseText);
var parentDiv = document.getElementById('items');
parentDiv.innerHTML = "";
//fill the options in the document
for(var x = 0; x < arr.length; x++) {
var option = document.createElement('option');
option.value = arr[x][0];
option.innerHTML = arr[x][1];
//add each autocomplete option to the 'list'
option.addEventListener("click", function() {
console.log("Test");
});
parentDiv.appendChild(option);
};
}
}
xmlhttp.open("GET", "incl/search.php?value="+input.value, true);
xmlhttp.send();
}
However I can't get it to perform an action when I click on a selection in the datalist, for example if I type in "Ref F" and the item "Ref flowers" comes up, if I click on it I need to execute an event.
How can I do this?
option.addEventListener("click", function() {
option.addEventListener("onclick", function() {
option.addEventListener("change", function() {
Sorry for digging up this question, but I've had a similar problem and have a solution, that should work for you, too.
function onInput() {
var val = document.getElementById("input").value;
var opts = document.getElementById('dlist').childNodes;
for (var i = 0; i < opts.length; i++) {
if (opts[i].value === val) {
// An item was selected from the list!
// yourCallbackHere()
alert(opts[i].value);
break;
}
}
}
<input type='text' oninput='onInput()' id='input' list='dlist' />
<datalist id='dlist'>
<option value='Value1'>Text1</option>
<option value='Value2'>Text2</option>
</datalist>
This solution is derived from Stephan Mullers solution. It should work with a dynamically populated datalist as well.
Unfortunaltely there is no way to tell whether the user clicked on an item from the datalist or selected it by pressing the tab-key or typed the whole string by hand.
Due to the lack of events available for <datalist> elements, there is no way to a selection from the suggestions other than watching the input's events (change, input, etc). Also see my answer here: Determine if an element was selected from HTML 5 datalist by pressing enter key
To check if a selection was picked from the list, you should compare each change to the available options. This means the event will also fire when a user enters an exact value manually, there is no way to stop this.
document.querySelector('input[list="items"]').addEventListener('input', onInput);
function onInput(e) {
var input = e.target,
val = input.value;
list = input.getAttribute('list'),
options = document.getElementById(list).childNodes;
for(var i = 0; i < options.length; i++) {
if(options[i].innerText === val) {
// An item was selected from the list!
// yourCallbackHere()
alert('item selected: ' + val);
break;
}
}
}
<input list="items" type="text" />
<datalist id="items">
<option>item 1</option>
<option>item 2</option>
</datalist>
Use keydown
Contrary to the other answers, it is possible to detect whether an option was typed or selected from the list.
Both typing and <datalist> clicks trigger the input's keydown listener, but only keyboard events have a key property. So if a keydown is triggered having no key property, you know it was a click from the list
Demo:
const opts = document.getElementById('dlist').childNodes;
const dinput = document.getElementById('dinput');
let eventSource = null;
let value = '';
dinput.addEventListener('keydown', (e) => {
eventSource = e.key ? 'input' : 'list';
});
dinput.addEventListener('input', (e) => {
value = e.target.value;
if (eventSource === 'list') {
alert('CLICKED! ' + value);
}
});
<input type="text" id="dinput" list="dlist" />
<datalist id="dlist">
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
</datalist>
Notice it doesn't alert if the value being clicked is already in the box, but that's probably desirable. (This could also be added by using an extra tracking variable that will be toggled in the keydown listener.)
Datalist actually don't have an event (not all browsers), but you can detect if a datalist option is selected in this way:
<input type="text" list="datalist" />
<datalist id="datalist">
<option value="item 1" />
<option value="item 2" />
</datalist>
window.addEventListener('input', function (e) {
let event = e.inputType ? 'input' : 'option selected'
console.log(event);
}, false);
demo
Shob's answer is the only one which can detect when an option gets clicked as well as not trigger if an intermediary written text matches an option (e.g.: if someone types "Text1" to see the options "Text11", "Text12", etc. it would not trigger even if "Text1" is inside the datalist).
The original answer however did not seem to work on newer versions of Firefox as the keydown event does not trigger on clicks so I adapted it.
let keypress = false;
document.getElementById("dinput").addEventListener("keydown", (e) => {
if(e.key) {
keypress = true;
}
});
document.getElementById("dinput").addEventListener('input', (e) => {
let value = e.target.value;
if (keypress === false) {
// Clicked on option!
console.debug("Value: " + value);
}
keypress = false;
});
<input type="text" id="dinput" list="dlist" />
<datalist id="dlist">
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
</datalist>
Datalist don't support click listener and OnInput is very costly, checking everytime all the list if anything change.
What I did was using:
document.querySelector('#inputName').addEventListener("focusout", onInput);
FocusOut will be triggered everytime a client click the input text and than click anywhere else. If they clicked the text, than clicked somewhere else I assume they put the value they wanted.
To check if the value is valid you do the same as the input:
function onInput(e) {
var val = document.querySelector('#inputName').value;
options = document.getElementById('datalist').childNodes;
for(var i = 0; i < options.length; i++) {
if(options[i].innerText === val) {
console.log(val);
break;
}
}
}
<input type="text" id="buscar" list="lalista"/>
<datalist id="lalista">
<option value="valor1">texto1</option>
<option value="valor2">texto2</option>
<option value="valor3">texto3</option>
</datalist>
//0 if event raised from datalist; 1 from keyboard
let idTimeFuekey = 0;
buscar.oninput = function(){
if(buscar.value && idTimeFuekey==0) {
alert('Chévere! vino desde la lista')
}
};
buscar.onkeydown = function(event){
if(event.key){ //<-- for modern & non IE browser, more direct solution
window.clearInterval(idTimeFuekey);
idTimeFuekey = window.setInterval(function(){ //onkeydown --> idTimeFuekey++ (non 0)
window.clearInterval(idTimeFuekey);
idTimeFuekey = 0 //after 500ms onkeydown --> 0 (could work 500, 50, .. 1)
}, 500)
}
}
Well, at least in Firefox the onselect event works on the input tag
<input type="text" id="dinput" list="dlist" onselect="alert(this.value)"/>
<datalist id="dlist">
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
</datalist>
After having this problem and not finding a suitable solution, I gave it a shot.
What I did was look at the "inputType" of the given input event on top of the event toggle variable from above, like so:
eventSource = false;
const selector = document.getElementById("yourElementID");
selector.addEventListener('input', function(evt) {
if(!eventSource) {
if(evt.inputType === "insertReplacementText") {
console.log(selector.value);
}
}
});
selector.addEventListener('keydown', function(evt) {
eventSource = !evt.key;
});
This works if you want to allow the user to search a field but only hit a specific function/event on selection from the datalist itself. Hope it helps!
Edit: Forgot to mention this was done through Firefox and has not been tested on other browsers.
I have a small issue, the placeholder attribute for input boxes is not supported in IE 8-9.
What is the best way to make this support in my project (ASP Net). I am using jQuery.
Need I use some other external tools for it?
Is http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html a good solution?
You could use this jQuery plugin:
https://github.com/mathiasbynens/jquery-placeholder
But your link seems to be also a good solution.
You can use any one of these polyfills:
https://github.com/jamesallardice/Placeholders.js (doesn't support password fields)
https://github.com/chemerisuk/better-placeholder-polyfill
These scripts will add support for the placeholder attribute in browsers that do not support it, and they do not require jQuery!
the $.Browser.msie is not on the latest JQuery anymore...
you have to use the $.support
like below:
<script>
(function ($) {
$.support.placeholder = ('placeholder' in document.createElement('input'));
})(jQuery);
//fix for IE7 and IE8
$(function () {
if (!$.support.placeholder) {
$("[placeholder]").focus(function () {
if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
}).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function () {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
});
});
}
});
</script>
if you use jquery you can do like this. from this site Placeholder with Jquery
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
these are the alternate links
Placeholder jquery library
HTML5 polyfills -- go for placeholder section
I had compatibility issues with several plugins I tried, this seems to me to be the simplest way of supporting placeholders on text inputs:
function placeholders(){
//On Focus
$(":text").focus(function(){
//Check to see if the user has modified the input, if not then remove the placeholder text
if($(this).val() == $(this).attr("placeholder")){
$(this).val("");
}
});
//On Blur
$(":text").blur(function(){
//Check to see if the use has modified the input, if not then populate the placeholder back into the input
if( $(this).val() == ""){
$(this).val($(this).attr("placeholder"));
}
});
}
$(function(){
if($.browser.msie && $.browser.version <= 9){
$("[placeholder]").focus(function(){
if($(this).val()==$(this).attr("placeholder")) $(this).val("");
}).blur(function(){
if($(this).val()=="") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function() {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
})
});
}
});
try this
I use thisone, it's only Javascript.
I simply have an input element with a value, and when the user clicks on the input element, it changes it to an input element without a value.
You can easily change the color of the text using CSS. The color of the placeholder is the color in the id #IEinput, and the color your typed text will be is the color in the id #email. Don't use getElementsByClassName, because the versions of IE that don't support a placeholder, don't support getElementsByClassName either!
You can use a placeholder in a password input by setting the type of the original password input to text.
Tinker: http://tinker.io/4f7c5/1
- JSfiddle servers are down!
*sorry for my bad english
JAVASCRIPT
function removeValue() {
document.getElementById('mailcontainer')
.innerHTML = "<input id=\"email\" type=\"text\" name=\"mail\">";
document.getElementById('email').focus(); }
HTML
<span id="mailcontainer">
<input id="IEinput" onfocus="removeValue()" type="text" name="mail" value="mail">
</span>
For others landing here. This is what worked for me:
//jquery polyfill for showing place holders in IE9
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
Just add this in you script.js file.
Courtesy of http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
Since most solutions uses jQuery or are not this satisfying as I wished it to be I wrote a snippet for myself for mootools.
function fix_placeholder(container){
if(container == null) container = document.body;
if(!('placeholder' in document.createElement('input'))){
var inputs = container.getElements('input');
Array.each(inputs, function(input){
var type = input.get('type');
if(type == 'text' || type == 'password'){
var placeholder = input.get('placeholder');
input.set('value', placeholder);
input.addClass('__placeholder');
if(!input.hasEvent('focus', placeholder_focus)){
input.addEvent('focus', placeholder_focus);
}
if(!input.hasEvent('blur', placeholder_blur)){
input.addEvent('blur', placeholder_blur);
}
}
});
}
}
function placeholder_focus(){
var input = $(this);
if(input.get('class').contains('__placeholder') || input.get('value') == ''){
input.removeClass('__placeholder');
input.set('value', '');
}
}
function placeholder_blur(){
var input = $(this);
if(input.get('value') == ''){
input.addClass('__placeholder');
input.set('value', input.get('placeholder'));
}
}
I confess that it looks a bit more MORE than others but it works fine.
__placeholder is a ccs-class to make the color of the placeholder text fancy.
I used the fix_placeholder in window.addEvent('domready', ... and for any additinally added code like popups.
Hope you like it.
Kind regards.
I used the code of this link
http://dipaksblogonline.blogspot.com/2012/02/html5-placeholder-in-ie7-and-ie8-fixed.html
But in browser detection I used:
if (navigator.userAgent.indexOf('MSIE') > -1) {
//Your placeholder support code here...
}
<input type="text" name="Name" value="Name" onfocus="this.value = ''" onblur=" if(this.value = '') { value = 'Name'}" />
Add the below code and it will be done.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="https://code.google.com/p/jquery-placeholder-js/source/browse/trunk/jquery.placeholder.1.3.min.js?r=6"></script>
<script type="text/javascript">
// Mock client code for testing purpose
$(function(){
// Client should be able to add another change event to the textfield
$("input[name='input1']").blur(function(){ alert("Custom event triggered."); });
// Client should be able to set the field's styles, without affecting place holder
$("textarea[name='input4']").css("color", "red");
// Initialize placeholder
$.Placeholder.init();
// or try initialize with parameter
//$.Placeholder.init({ color : 'rgb(255, 255, 0)' });
// call this before form submit if you are submitting by JS
//$.Placeholder.cleanBeforeSubmit();
});
</script>
Download the full code and demo from https://code.google.com/p/jquery-placeholder-js/downloads/detail?name=jquery.placeholder.1.3.zip
Here is a javascript function that will create placeholders for IE 8 and below and it works for passwords as well:
/* Function to add placeholders to form elements on IE 8 and below */
function add_placeholders(fm) {
for (var e = 0; e < document.fm.elements.length; e++) {
if (fm.elements[e].placeholder != undefined &&
document.createElement("input").placeholder == undefined) { // IE 8 and below
fm.elements[e].style.background = "transparent";
var el = document.createElement("span");
el.innerHTML = fm.elements[e].placeholder;
el.style.position = "absolute";
el.style.padding = "2px;";
el.style.zIndex = "-1";
el.style.color = "#999999";
fm.elements[e].parentNode.insertBefore(el, fm.elements[e]);
fm.elements[e].onfocus = function() {
this.style.background = "yellow";
}
fm.elements[e].onblur = function() {
if (this.value == "") this.style.background = "transparent";
else this.style.background = "white";
}
}
}
}
add_placeholders(document.getElementById('fm'))
<form id="fm">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<textarea name="description" placeholder="Description"></textarea>
</form>
<script>
if ($.browser.msie) {
$('input[placeholder]').each(function() {
var input = $(this);
$(input).val(input.attr('placeholder'));
$(input).focus(function() {
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
$(input).blur(function() {
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.val(input.attr('placeholder'));
}
});
});
}
;
</script>
I have 3 dropdown menu. and all 3 are interlinked. ie, if i select the values of 1st dropdown, depending on that the second dropdown should display values. depending on the selection of 2nd dropdown, 3rd dropdown should populate the values. have done for 1st and 2nd. but depending on the values of 2nd drop down am not able to populate the values of 3rd dropdown. can anyone plaz help me. i know something like this will be in JFIDDLE.com. but not able to fine the exact name to search that!
You have to use AJAX if you want that. it will be easy.
<select name="ID"
id="ID"
onchange="DoYourTaskHere(this);">
<option value="select" selected="selected">Select</option>
<c:forEach items="${A.List}" var="Variable">
<option value="${ID}">
<c:out value="${ID}" />
</option>
</c:forEach>
</select>
And in the script you write the code as follows.
function loadValue(ID) {
if (ID.value != "select") {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
// Safari
ValueXmlHttpReq = new XMLHttpRequest();
} else {// code for IE6, IE5
ValueXmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
ValueXmlHttpReq.onreadystatechange = processLoadValues;
ValueXmlHttpReq.open("POST", "getValue.htm?ID="
+ ID.value, true);
ValueXmlHttpReq.send();
} else {
var objSelect = document.getElementById("ValueId");
var currentValueListLength = objSelect.options.length;
while (currentValueListLength > 0) {
objSelect.remove(1);
currentValueListLength--;
}
var objSelect = document.getElementById("2ndDropDownWhereYouWantToPopulate");
var currentSecondValueListLength = objSelect.options.length;
while (currentSecondValueListLength > 0) {
objSelect.remove(1);
currentSecondValueListLength--;
}
}
}
Allright , here something to get you started :
<form name='cars'>
<select name='brand'></select>
<select name='model'></select>
</form>
and the javascript (i'm using jQuery ) :
var application_model = [
{
name: "General motors",
models: [
"model1", "model2", "model3"
]},
{
name: "Mercedes",
models: [
"model4", "model5", "model6"
]},
{
name: "Fiat",
models: [
"model7", "model8", "model9"
]}
];
var selectedBrandIndex = 0
var selectedModelIndex = 0
function render() {
// render the first combo
$('select[name=brand]').empty();
$.each(application_model, function(index, object) {
var selected = "";
if (index == selectedBrandIndex) {
selected = "selected";
}
console.log(this);
$('select[name=brand]').append("<option value='" + index + "' " + selected + ">" + object.name + "</option>");
})
// render the second combo
$('select[name=model]').empty();
$.each(application_model[selectedBrandIndex].models, function(index, object) {
var selected = "";
if (index == selectedModelIndex) {
selected = "selected";
}
console.log(this);
$('select[name=model]').append("<option value='" + index + "' " + selected + ">" + object + "</option>");
});
}
function main() {
$("select[name=brand]").bind("change", function(event) {
console.log(event.currentTarget.value);
selectedBrandIndex = event.currentTarget.value;
render();
});
render();
}
main();
check the fiddle here :
http://jsfiddle.net/camus/MAgza/2/
cheers
you can try related combobox
You can easily setup any number of combobox instances on a single page. They can interact with each other based on certain client or server side events.
This example shows how the comboboxes can interact with each other using client-side methods and requesting the items on demand. To request the items on demand at the client-side, the requestItems() method is used.
The ViewState of the dependent comboboxes is disabled because the data required for their proper operation in this example is maintained in their ClientState.
refer http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/multiplecomboboxes/defaultcs.aspx