For example if i have a list item like all,a,b,c,d. if i click all means it should not allow to choose other items, if i am not choosing all means it should allow to choose mulitle item from list
<script type="text/javascript">
var creatLimit = 5;
var fCount = 0;
function addFileElement()
{
if(fCount < creatLimit)
{
var fObject = document.getElementById("name");
var addButton = document.createElement("select");
addButton.type = "select";
addButton.name = "List["+fCount+"]";
addButton.setAttribute("class", "normal");
addButton.style.width = "250px";
addButton.onkeydown = function(){
blur();
};
var o2 = document.createElement("br");
var o3 = document.createElement("br");
fObject.appendChild(addButton);
fObject.appendChild(o2);
fObject.appendChild(o3);
fCount++;
}
}
</script>
You are confusing your terminologies here slightly - JavaScript itself doesn't show any UI, it is the HTML (or the XUL or something completely different) which shows the UI.
Assuming that you are talking about html, the way to create a drop down list is simply to write the corresponding html for the drop down list to wherever it is in the document that you wish the drop down list to be placed, for example:
<div id="myDiv"></div>
<script type="text/javascript">
myDiv = document.getElementById("myDiv");
myDiv.innerHtml = "<select><option>a</option><option>b</option><option>c</option><option>d</option>";
</script>
Most likely you will be dynamically writing the HTML based on an existing list of items, but I don't want to go into that in too much detail because that will completely depend on your specific requirements and because jQuery will make this a lot easier.
EDIT: Typo fix in variable names.
Related
I need to dynamically add a couple of things like container then find it in DOM and fill with a list of numbers. Here is the way I do it but I feel like it is redundant and maybe I should do it another way. The only issue is that I have to do it all with javascript and cant hard code any container. That is why first I add it and then try to find it.
JS Bin working example http://jsbin.com/okikohu/1/
The code:
<script>
$(function(){
var obj = $('form'),
total = 6;
obj.before('<div class="container"/>');
var container = $('body').find('.container');
for (var i = 0, limit = total; i < limit; i++) {
container.append('-<span class="step" id="is'+(i+1)+'">'+(i+1)+'</span>-');
}
});
</script>
<form>some form</form>
obj.before('<div class="container"/>');
var container = $('body').find('.container');
Instead of using before() and then a DOM query, you could create the element with the jQuery(html) constructor and simply insertBefore() it somewhere while still holding the reference:
var total = 6,
container = $('<div class="container"/>').insertBefore('form');
I'm creating a form and would like to be able to duplicate certain DIVs as needed using javascript. However, I need to replace multiple instances of a certain piece of text. Something like this with the comment replaced by functional code:
<body>
<div id="duplicate">
<p>Section_1 of form</p>
Add A Section
</div>
<script type="text/javascript">
<!--
var num_sections = 1;
function add_section()
{
var orig_div=document.getElementById("duplicate")
var copy_div=orig_div.cloneNode(true);
//Change every "Section_1" in copy_div to "Section_"+num_sections
footer = document.getElementById("footer");
document.body.insertBefore(copy_div,footer);
}
//-->
</script>
<div id="footer"></div>
</body>
Using JavaScript, what is an elegant way to replace every instance of Section_1 when these instances are in every input tag within the section ?
I'm working within the confines of a CMS so I can't implement it using a more powerful processing language.
You can call getElementsByTagName on a DOM node to fetch some elements group identified by the tag.
var num_sections = 1;
window.add_section = function() {
var orig_div=document.getElementById("duplicate")
var copy_div=orig_div.cloneNode(true);
//Change every "Section_1" in copy_div to "Section_"+num_sections
num_sections++;
var p = copy_div.getElementsByTagName('p')[0];
p.innerHTML = p.innerHTML.replace('Section_1', 'Section_' + num_sections);
var footer = document.getElementById("footer");
document.body.insertBefore(copy_div,footer);
};
Here's jsFiddle
Is it possible for this jQuery code to run as a standalone javascript? This is the only javascript I'd like to use in my project so I'd prefer not to load the entire jquery library just for this 1k script.
//chris coyier's little dropdown select-->
$(document).ready(function() {
//build dropdown
$("<select />").appendTo("nav.primary");
// Create default option "Go to..."
$("<option />", {
"selected": "selected",
"value" : "",
"text" : "Go to..."
}).appendTo("nav select");
// Populate dropdowns with the first menu items
$("div#brdmenu ul li a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("nav.primary select");
});
//make responsive dropdown menu actually work
$("nav.primary select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
I've tried to find previous answers but most questions are for converting to jquery and not vice-versa :)
It is obviously possible to do those things in straight javascript, but there is no way (that I am aware of) to automatically do that conversion. You will have to go through line by line and do the conversion yourself.
Here is something similar to market's answer. I'm assuming you want to get all the links in UL elements inside the brdmenu element. If you only want the first link on the LI elements, just adjust the loop that gets them.
Also, this is not a good idea. Using select elements for links went out of fashion a long time ago, users much prefer real links. Also, when navigating the options using cursor keys in IE, a change event is dispatched every time a different option is selected so users will only get to select the next option before being whisked away to that location. Much better to add a "Go" button that they press after selecting a location.
The main change is to use an ID to get the nav.primary element, which I assume is a single element that you should be getting by ID already.
function doStuff() {
function getText(el) {
return el.textContent || el.innerText;
}
var div, link, links, uls;
// Use an ID to get the nav.primary element
var navPrimary = document.getElementById('navPrimary');
// Create select element and add listener
var sel = document.createElement('select');
sel.onchange = function() {
if (this.selectedIndex > 0) { // -1 for none selected, 0 is default
window.location = this.value;
}
};
// Create default option and append to select
sel.options[0] = new Option('Go to...','');
sel.options[0].setAttribute('selected','');
// Create options for the links inside #brdmenu
div = document.getElementById('brdmenu');
uls = div.getElementsByTagName('ul');
for (var i=0, iLen=uls.length; i<iLen; i++) {
links = uls[i].getElementsByTagName('a');
for (var j=0, jLen=links.length; j<jLen; j++) {
link = links[j];
sel.appendChild(new Option(getText(link), link.href));
}
}
// Add select to page if found navPrimary element
if (navPrimary) {
navPrimary.appendChild(sel);
}
}
window.onload = doStuff;
It's only 28 lines of actual code, which is only 10 more than the original, doesn't require any supporting library and should work in any browser in use (and most that aren't).
Have a go with this.
The one thing I'm leaving out is $(document).ready, but there are a number of solutions for that available on stackoverflow. It's a surprisingly large amount of code!
But the other functionality:
// build the dropdown
var selectElement = document.createElement('select');
var primary = document.getElementsByClassName('primary')[0];
// create a default option and append it.
var opt = document.createElement('option');
var defaultOpt = opt.cloneNode(false);
defaultOpt.selected = true;
defaultOpt.value = "";
defaultOpt.text = "Go to...";
selectElement.appendChild(defaultOpt);
// populate the dropdown
var brdmenuUl = document.getElementById('brdmenu').getElementsByTagName('ul')[0];
var listItems = brdmenuUl.getElementsByTagName('li');
for(var i=0; i<listItems.length; i++){
var li = listItems[i];
var a = li.getElementsByTagName('a')[0];
var newOpt = opt.cloneNode(false);
newOpt.value = a.href;
newOpt.text = a.innerHTML;
selectElement.appendChild(newOpt);
}
// now listen for changes
if(selectElement.addEventListener){
selectElement.addEventListener('change', selectJump, false);
}
else if(selectElement.attachEvent){
selectElement.attachEvent('change', selectJump);
}
function selectJump(evt){
window.location = evt.value;
}
primary.appendChild(selectElement);
some notes!
We're not looking specifically for nav.primary, we're just finding the first occurrence of something with class .primary. For best performance, you should add an ID to that element and use getElementById instead.
Similarly with the lists in #brdmenu, we look for the first UL, and the first A inside each LI. This isn't exactly what the jQuery does, if you are going to need to iterate more than one UL inside #brdmenu you can use another for loop.
I think that should all work though, there's a fiddle here
I have been able to successfully get another elements onclick function by doing this:
document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')
This gives me the exact text that I want to put into a different elements onchange event, so I thought I could do this:
<select onchange="document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')">
This does not work though. Does anyone have any ideas, I am stumped?
You can't just dump a function into an attribute like that. I recommend that you start writing unobtrusive JavaScript.
HTML
<select id="mySelect">
<!-- snip -->
</select>
JavaScript
var select = document.getElementById('mySelect');
select.onchange = function () {
var id = this.options[this.selectedIndex].text,
clickHandler = document.getElementById(id).onclick;
clickHandler.apply(this);
};
Demo →
Edit re: OP's comment
"Is there an easy way to apply this to all the selects on the page?"
Of course there is! But you need to be careful about not creating functions in a loop (it won't work).
var selects = document.getElementsByTagName('select'),
numSelects = selects.length,
i;
function setClickHandler(element) {
element.onchange = function () {
var id = this.options[this.selectedIndex].text,
clickHandler = document.getElementById(id).onclick;
clickHandler.apply(this);
}
}
for (i=0; i<numSelects; i++) {
setClickHandler(selects[i]);
}
I haven't tested this, but perhaps:
var handler = document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick');
var selectEl = document.getElementsByTagName('select')[indexOfSelect];
selectEl.setAttribute('onClick',handler);
The following works (more or less the same as above, except using the 'onFocus' attribute on the select element):
var handler = document.getElementById('first').getAttribute('onclick');
var selectEl = document.getElementsByTagName('select')[0];
selectEl.setAttribute('onfocus',handler);
JS Fiddle demo
This is not recommended but the simplest fix that would work,
<select onchange="function() {document.getElementById(this.options[this.selectedIndex].text).getAttribute('onclick')();}">
I designed an ascx control (I refer to it in this question as customControl). The control is just a series of drop downs with text values in each drop down. The drop downs are inside a panel.
Here it is below:
I then place a few of them on a page that also has a textbox (I refer to it here as textbox)
Here it is below:
So what I need to develop, is Javascript that when any of the drop downs in any of the customControls have a selected drop down index changed event, to find all the values in all the boxes of all the controls of type customControl on the page and simply put that text in the textbox.
Do I need to define my control to have a class so JS can find all of them easily and then have the JS function take in the textbox as control so it knows what to output and where?
Set all your drop downs with a css class of "customControlDropDown" or whatever and your textbox with a css class name of "bigTextBox" or whatever and use some jQuery.
<script type='text/javascript'>
$(document).ready(function(){
$("select.customControlDropDown").change(function(){ //change event for all drop downs with customControlDropDown as its css class name
var collectiveText = "";
$("select.customControlDropDown option:selected").each(function(i){ //get all selected options in all the drop downs with customControlDropDown as its css class name
collectiveText = collectiveText + $(this).text(); //append the item's text to a string variable
});
$(".bigTextBox").val(collectiveText); //set the textbox with css class name of bigTextBox with value of the string variable from above
});
});
</script>
I haven't tested this, but it SHOULD work. Let us know.
in yours ascx control, must have the class "myClass".
window.onload = function(){
function getElementsByClass(containerId, class)
{
container = document.getElementById(containerId);
var all = container.all¦¦container.getElementsByTagName('*') ;
var arr = []
for(var k=0;k<all.length;k++)
if(all[k].getAttribute("class").indexOf("class") != -1)
arr[arr.length] = all[k];
return arr;
}
var arrEl = getElementsByClass("container", "myClass");
var xOnChange = function()
{
//this
}
for (var ind = 0; ind < arEL.length; ind++)
{
arrEl[ind].onchange = xOnChange;
}
}
in html or aspx:
<div id="container>
<!-- aspx controls -->
</div>