Create drop-down list using JavaScript instead of HTML - javascript

I have the following code that creates and deletes text boxes using javascript:
http://jsfiddle.net/JpYGg/8/
What I am aiming to do is infact create a set of three drop-down lists using this functionality instead of creating a textbox.
The code for the three drop-downs is shown here:
http://jsfiddle.net/MWH99/
I am a bit stuck as to how to achieve this. I added in the "dropdown" div and what I was thinking is to get the innerHTML of this div in order to use that to create the three lists every time?
The other question I have is how to have it so that these are generated by the javascript instead of an HTML one AND a JavaScript version.
Thank you for any help.
Martin
EDIT
I have the buttons working to create the next row of 3 drop-downs but they do not function the way that the original does, the parent drop-downs use javascript to identify the selection in the first drop-down in order to update the other two whereas the cloned ones lose this functionality.
Code cna be found here:
http://pastebin.com/pt1wef76
Original drop downs use dropdown.js which is http://pastebin.com/bDLpFWJY

Why not use a javascript library like jQuery for example. Would make this and many other things much easier. Could achieve what you want like this:
$('body').append('<!-- ANY HTML GOES HERE -->')

There's two basic approaches; create all of the elements in JavaScript, or copy a part of the DOM (some HTML) over and over.
People often put HTML in script tags (see jQuery Templating, for example), and then get the innerHTML of the tag and use that. For example,
<script type="text/plain" id="template">
<!-- HTML that you want to duplicate in here -->
</script>
<div id="contentcontainer">
</div>
...
<script type="text/javascript">
var addAnother = function( ) {
$("#contentcontainer").append(
$("#template").html()
);
};
</script>
This example makes use of jQuery primarily because jQuery is a lot less verbose and easier to read, but you certainly don't have to use jQuery. Here, the addAnother function will copy the HTML from #template and append it into #contentcontainer.
In your attempt above, you probably meant $('body').append($('#dropdown')); '#dropdown' is just a string, $('#dropdown') returns the element (or elements) with id="dropdown".

Related

jQuery append text formatting

This question is not related to coding issues but how we write our codes. For example take the append function. When we use jQuery append to insert long divs, it is easy to lose track of it's correctness. Example:
$('#someDiv').append('<div><span><div> .............. hundreds of div here ..... </div></span></div>');
Is it possible to convert this to a readable format, for example using multi-lines. I tried
$('#someDiv').append('<div>'+
+'<span>'+
+'<div> ...... and you get the point')
This doesn't seem to work. This question may be easy for some but it is not so obvious for me. Also although I minify js files at the end, it would be nice not to lose track of the elements while writing the code.
If you have to add the HTML inline style I would suggest the following format.
var html =
'<div class="somediv">\
<div class="otherdiv">\
.
..
...
</div>\
</div>';
$('#somediv').append(html);
You can do it this way -
$('#someDiv').append($('<div>').append($('<span>'))
.append($('<div>'))
.append($('<div>'))
.append($('<div>'))
.append($('<div>'))
)
You can also add css styles, add class, change html while appending these html elements (wrapped in jQuery object)
$('<div>').css('color','red')
$('<div>').addClass('someClass')
$('<div>').html("and you get the point")
My solution would be to create all these elements
div1 = $(document.createElement('div'));
div1.attr(..);
div1.css(..);
container.append(..)
This means a lot of code but you can outsource it, can easily change attributes and its good readable...

about script tags inside form tags

i have added a script tag in side a select tag which creates options dynamically. The function works fine but the W3C validator gives me 4 errors regarding this syntax. It will be helpful if you guys could find me a solution for this problem.
These are the 2 errors that repeat 2 times.
1. document type does not allow element "script" here
2. year_option(); end tag for "select" which is not finished
1) the only tags that <select> can have are <option> and <optgroup> tags
the validator is complaining because <script> is not one of those things -- the browser is doing its best to take your invalid markup and turn it into something valid, so despite the fact that it works, that's why you get the error, if you're actually putting <script> tags inside of a <select>
2) your script tags should be at the bottom of your page, and instead of using document.write to put option tags there, use DOM methods to add options to the select element after the fact
<select name="select-box"></select>
<!-- ...rest of page... -->
<script src="external-script.js"></script>
/* contents of external-script.js */
var select_box = document.querySelector("select[name=select-box]"),
bob_opt = document.createElement("option"),
doug_opt = document.createElement("option");
bob_opt.value = "Bob";
doug_opt.value = "Doug";
bob_opt.appendChild(document.createTextNode("Bob"));
doug_opt.appendChild(document.createTextNode("Doug"));
select_box.appendChild(bob_opt);
select_box.appendChild(doug_opt);
There are faster and neater, or more-elaborate or more flexible ways of doing this, but this is closer to the "right way" than something like:
<select>
<script>document.write("<option value=\"" + i + "\">one</option>");</script>
</select>
Or whatever you might currently have there.
JS is not meant to be templated like that, without using/writing a templating library for that purpose.
1) Script tags should be located in head, or perhaps elsewhere in the document, but not inside select tags
2) Looks like you are missing a tag, or perhaps its having problems finding it because of the first error.
You can put your JavaScript out side the select tag, and you can append option tags later, when select tag is rendered on the page, after page load using $(document).ready.
You can standardize your code by placing JavaScript in separate file, there you can do like
$(document).ready(function(){
//Your code to init all things,
//e.g. load options in select box etc..
//so It will be easy later to maintain the code, all init code will go here
});
Or if you are not using jquery, you can use below code
function your_function(){
//your init code will go here
}
document.getElementsByTagName("body")[0].onLoad = your_function;
that's it, place your code in your_function()

sharepoint 2010. Include javascript in code for all item display forms

I have javascript which can hide empty fields from sharepoint display form.
http://sharepointjavascript.wordpress.com/2009/10/15/hide-empty-rows-in-dispform/
I need to add programmatically this javascript to all display forms.
I dont know how to do it. Any ideas?
.each loops through all elements which matches a specific selector. If the code below is not sufficient, change the selector ("td.ms-formbody") such that your desired elements are matched.
$("td.ms-formbody").each(function(){ /* Should walk through all elements */
var val = $(this).text().replace(/\s|\xA0/g,'');
if($(this).parents().html().match('FieldName="#H#')==null){
if(val.length==0){
$(this).parents('tr:first').hide();
}
}
});
If you're still stuck, provide your HTML code, so that a more specific answer can be offered.
You can add a custom template file, overriding the ordinary DefaultTemplates.ascx (under ControlTemplates).
Create _NewTemplates.ascx file (empty). It should go under ControlTemplates as well
Copy all the Register stuff from the original ASCX
Add the ListForm template copied from DefaultTemplates.ascx (you might need to add a couple more template, depending on the list types you want to support)
Now edit the rendering template to add your JS
<SharePoint:RenderingTemplate ID="ListForm" runat="server"">
<Template>
--> add your code here
<script language="javascript">add functions or hook up enternal JS file</script>
--> continue original markup from this point
Save the file and run IISRESET, that's it

What is the fastest Javascript (jquery) method to select elements that have certain pieces of data

I have a set of results (a list of cars) which are displayed in div's. I want to use jquery to allow me to filter these results e.g. I want a checkbox that says 'Air Conditioning' that when checked hides all of the 'Non-aircon cars'.
There are several attributes that each car has:
air
trans
group
etc.
I have thought of 3 methods which I can add this data to the page in a selectable fashion, which one will be the fastest? i.e. is there a clear winner?
1. Add classes to each result:
<div class="air_0 trans_1 group_3">Car</div>
and use jquery like:
$('.air_1').hide();
2. Each result has a uniue id which is referenced in a js array
Var tags = new array();
tags['air_1'] = 'unique_id_1';
tags['trans_0']['unique_id_1'] = true;
and use jquery like:
$.each(Tags['air_1'], function(i, result)
{
$('#'+result).hide();
});
3. Add some extra attributes to the HTML (invalidating it)
<div air=”1” fuel=”3”></div>
and use jquery like:
$('div[air=1]').hide();
Adding classes is the way to go.
Although, I don't think that you need true/false classes (air_0, air_1, etc). You should just add the classes of what a car doesn't have to it (for example <div classes="air">Car</div> doesn't have air conditioning). This is definitely the best way to do this because generating all of the data is quite simple, and it's really easy to manage the results with jQuery's .show()/.hide() functions. It also requires very little code, which makes it extremely fast. I've written lots of functions that require divs, inside divs, inside divs (mild exaggeration), lots of data and regex, but it's all just seems a bit too complicated compared to a few classes and some .show()/.hide() use.

Create new (not change) stylesheets using jQuery

We've got a little tool that I built where you can edit a jQuery template in one field and JSON data in another and then hit a button to see the results immediately within the browser.
I really need to expand this though so the designer can edit a full CSS stylesheet within another field and when we render the template, it will have the CSS applied to it. The idea being that once we've got good results we can take the contents of these three fields, put them in files and use them in our project.
I found the jQuery.cssRule plugin but it looks like it's basically abandoned (all the links go nowhere and there's been no development in three years). Is there something better or is it the only game in town?
Note: We're looking for something where someone types traditional CSS stylesheet data in here and that is used immediately for rendering within the page and that can be edited and changed at will with the old rules going away and new ones used in their stead. I'm not looking for something where the designer has to learn jQuery syntax and enter in individual .css("attribute", "value") type calls to jQuery.
Sure, just append a style tag to the head:
$("head").append("<style>p { color: blue; }</style>");
See it in action here.
You can replace the text in a dynamically added style tag using something like this:
$("head").append("<style id='dynamicStylesheet'></style>");
$("#dynamicStylesheet").text(newStyleTextGoesHere);
See this in action here.
The cleanest way to achieve this is by sandboxing your user-generated content into an <iframe>. This way, changes to the CSS won't affect the editor. (For example, input { display:none; } can't break your page.)
Just render out your HTML (including the CSS in the document's <head>, and write it into the <iframe>.
Example:
<iframe id="preview" src="about:blank">
var i = $('#preview')[0];
var doc = i.contentWindow || i.contentDocument;
if (doc.document) doc = doc.document;
doc.open('text/html',true);
doc.write('<!DOCTYPE html><html>...</html>');
doc.close();
If the user should be able to edit a whole stylesheet, not only single style attributes, then you can store the entered stylesheet in a temporary file and load it into your html document using
$('head').append('<link rel="stylesheet" href="temp.css" type="text/css" />');
sounds like you want to write an interpreter for the css? if it is entered by hand in text, then using it later would be as simple as copy and pasting it into a css file.
so if you have a textarea on your page to type in css and want to apply those rules when you press the button, you could use something like this (only pseudocode, needs work):
//for each css id in the text area
$.each($('textarea[name=cssTextArea]').html().split('#'), function({
//now get each property
$.each($(this).split(';'), function(){
$(elem).css({property:value});
});
});
then you could write something to go through each element that your designer typed in, and get the current css rules for it (including those that you applied using some code like the snippet above) and create a css string from that which could then be output or saved in a db. It's a pain and much faffing around with substrings but unfortunately I don't know of a faster or more efficient way.
Hope this atleast gives you some ideas

Categories