What Is The Error In JavaScript code - javascript

I am trying to click on links to add it to select with checking if there is the item was not in list before menu but It seems loop part has some issue.
JavaScript code
$(document).ready(function() {
$('.link').click(function(event) {
var this_item_was_not_in_list = true;
var item =$(this).text();
for (var i = 0; i < $('#list').length; i++) {
if ($('#list').options[i].text == item) { this_item_was_not_in_list = false; break;};
};
if (this_item_was_not_in_list) {$('#list').append('<option>' + item + '</option>')};
});
});
HTML Code
Bread
Suger
Tea
<select id="list">
</select>

There are numerous ways to simplify this using jQuery methods.
One example:
$('.link').click(function(event) {
var item = $(this).text();
if(!$('#list option[value=' + item +']').length){
$('#list').append('<option value="' + item +'">' + item + '</option>');
}
});
Instead of using your for loop can easily iterate over a collection of elements using each() which exposes the index and the element

Where you are doing:
for (var i = 0; i < $('#list').length; i++) {
You should be doing:
for (var i = 0; i < $('#list option').length; i++) {

if ($('#list').options[i].text == item)
Aren't some parenthesis missing?
if ($('#list').options[i].text() == item)

The problen is here:
$('#list').options[i].text == item
That is not the way to get option elements from the select element.
Try this:
$('#list').find('options:nth(' + i + ')')).text() == item

Use the following code. Here's the jsfiddle for this.
$(document).ready(function() {
$('.link').click(function(event) {
var this_item_was_not_in_list = true;
var clickedItemName =$(this).text();
var listLength = $('#list option').length;
for (i=0; i<listLength ; i++)
{
if ($('#list option')[i].value == clickedItemName)
{
this_item_was_not_in_list = false;
break;
}
}
if (this_item_was_not_in_list)
{
$('#list').append('<option>' + clickedItemName + '</option>');
}
});
});
<html>
Bread
Sugar
Tea
<select id="list"></select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</html>

Related

Add certain values from JSON object to javascript array

Update: I've tried the suggestions in the comments and it's still not working. I really have no idea why. I've consolidated it to a single loop and fixed the syntax errors noted. Here's the code as it looks now:
$(function() {
$("#json-one").change(function() {
var $dropdown = $(this);
$.getJSON("washroutines.json", function(data) {
var vals = [];
var $jsontwo = $("#json-two");
$jsontwo.empty();
for (var i = 0; i < data.length; i++){
if (data[i].make === $dropdown.val()) {
$jsontwo.append("<option value=\"" + data[i].model + "\">" + data[i].model + "</option>");
}
}
});
});
});
Any additional help would be much appreciated!
Original question:
I'm trying to create dependent drop down menus using a json object, and I'm having trouble getting the second menu to populate based on the first. When the first menu changes, the second goes to a bunch of "undefined"s.
$.getJSON("washroutines.json", function(data) {
var vals = [];
for (i = 0; i < data.length; i++){
if (data.make = $dropdown.val()) {
vals.push(data.model);
}
}
var $jsontwo = $("#json-two");
$jsontwo.empty();
for (i = 0; i < vals.length; i++){
$jsontwo.append("<option value\"" + vals[i] + "\">" + vals[i] + "</option>");
}
Please use small words when explaining things to me, I'm new at this!
contents of the JSON:
[{"make":"Maytag","model":"Bravos","prewashCycle":"Whitest Whites"},
{"make":"Maytag","model":"Awesome","prewashCycle":"Awesome Whitest Whites"},
{"make":"Whirlpool","model":"Cabrio","prewashCycle":"Extra Heavy"},
{"make":"Kenmore","model":"Elite","prewashCycle":"Awesome"}]
Try changing your for loop for this
for (var i = 0; i < data.length; i++){
if (data[i].make === $dropdown.val()) {
vals.push(data[i].model);
}
}

how to Delete duplicate items on asp:dropdownlist, Sharepoint Designer 2013

I have used asp:drowdownlist on dataviewwebpart and is bind with source spdatasource1.
It have multiple duplicate items. How could I delete those duplicate item
asp:DropDownList runat="server" id="DropDownList1" DataValueField="ID" DataTextField="ProgramMaster" DataSourceID="spdatasource1" AutoPostBack="False" AppendDataBoundItems="True" ToolTip="Select a Program from the list"/>
Also, It is showing items in following formation ID;#ProgramName. How can I get programName only.
Well I use JQuery to remove duplicates item from asp:dropdownlist and here's the code if in-case somebody might need it. The code works in four part, Get the value from Dropdown, strip off the Duplicates and get the value in usable form, Remove the existing value from Dropdown and last set or append the values back to the dropdown list.
<script type="text/javascript">
$(document).ready(function(){
var handles= [];
$('#DropDownList1 option').each(function() {
var Prog1 = $(this).attr('text');
if(Prog1 != 'All'){
var Prog2 = Prog1.split(';#');
handles.push('All');
handles.push(Prog2[1]);
}
//Remove The existed Dropdownlist value
$("select#DropDownList1 option[value='" + $(this).val() + "']").remove();
//$(this).val().remove();
});
//Removing the Duplicates
var individual = [];
for (var i = 0; i<handles.length; i++) {
if((jQuery.inArray(handles[i], individual )) == -1)
{
individual .push(handles[i]);
}
}
//Inserting or setting the value from array individual to the dropdownlist.
var sel = document.getElementById('DropDownList1');
for(var i = 0; i < individual.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = individual[i];
opt.value = individual[i];
sel.appendChild(opt);
}
});
</script>
P.S if the given ID didn't work fine for dropdown, get the ID from IE debugging tool which will be in form ctl00_PlaceHolderMain_g_a0a2fb36_2203_4d2e_bcd4_6f42243b880f_DropDownList1
you can do this with jquery
var usedNames = {};
$("select[name='company'] > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
or with server side code try this
void RemoveDuplicateItems(DropDownList ddl)
{
for (int i = 0; i < ddl.Items.Count; i++)
{
ddl.SelectedIndex = i;
string str = ddl.SelectedItem.ToString();
for (int counter = i + 1; counter < ddl.Items.Count; counter++)
{
ddl.SelectedIndex = counter;
string compareStr = ddl.SelectedItem.ToString();
if (str == compareStr)
{
ddl.Items.RemoveAt(counter);
counter = counter - 1;
}
} } }

loop for select box value

I want to create loop in select box. But I want one code for different select.
I am able create for one select but I want for multiple .
for single: with id
I want to change this code according class or for multiple select.
My code for this:
<select class="foo"></select><select class="foo"></select>
and:
$(document).ready(function() {
var elm = document.getElementByClass('foo'),
df = document.createDocumentFragment();
for (var i = 0; i <= 60; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode(" " + i));
df.appendChild(option);
}
elm.appendChild(df);
});
I think what you want is
document.getElementsByClassName('foo');
http://jsfiddle.net/5J29g/48/
Since you are using jQuery, so you could do like:
The demo.
$('.foo').each(function() {
for (var i = 0; i <= 60; i++) {
$('<option />').val(i).html('#option ' + i).appendTo($(this));
}
});
You can use class selector along with .append() and .clone()
$(document).ready(function () {
var df = document.createDocumentFragment();
for (var i = 0; i <= 60; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode(" " + i));
df.appendChild(option);
}
$('.foo').append(function () {
return $(df).clone()
})
});
Demo: Fiddle
I just updated your jsfiddle adding this:
(function() {
var foos=document.querySelectorAll(".foo");
for(var j=0;j<foos.length;j++){
var elm = foos[j],
df = document.createDocumentFragment();
for (var i = 1; i <= 42; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode("option #" + i));
df.appendChild(option);
}
elm.appendChild(df);
}
}());
sample check that out, DEMO
Try this:
$('.foo').each(function(){
// call your code create option element here with $(this).append()
});

getElementsByClassName IE resolution issue

I am having issues figuring out how to resolve the getElementsByClassName issue in IE. How would I best implement the robert nyman (can't post the link to it since my rep is only 1) resolution into my code? Or would a jquery resolution be better? my code is
function showDesc(name) {
var e = document.getElementById(name);
//Get a list of elements that have a class name of service selected
var list = document.getElementsByClassName("description show");
//Loop through those items
for (var i = 0; i < list.length; ++i) {
//Reset all class names to description
list[i].className = "description";
}
if (e.className == "description"){
//Set the css class for the clicked element
e.className += " show";
}
else{
if (e.className == "description show"){
return;
}
}}
and I am using it on this page dev.msmnet.com/services/practice-management to show/hide the description for each service (works in Chrome and FF). Any tips would be greatly appreciated.
I was curious to see what a jQuery version of your function would look like, so I came up with this:
function showDesc(name) {
var e = $("#" + name);
$(".description.show").removeClass("show");
if(e.attr("class") == "description") {
e.addClass("show");
} else if(e.hasClass("description") && e.hasClass("show")) {
return;
}
}
This should support multiple classes.
function getElementsByClassName(findClass, parent) {
parent = parent || document;
var elements = parent.getElementsByTagName('*');
var matching = [];
for(var i = 0, elementsLength = elements.length; i < elementsLength; i++){
if ((' ' + elements[i].className + ' ').indexOf(findClass) > -1) {
matching.push(elements[i]);
}
}
return matching;
}
You can pass in a parent too, to make its searching the DOM a bit faster.
If you want getElementsByClassName('a c') to match HTML <div class="a b c" /> then try changing it like so...
var elementClasses = elements[i].className.split(/\s+/),
matchClasses = findClass.split(/\s+/), // Do this out of the loop :)
found = 0;
for (var j = 0, elementClassesLength = elementClasses.length; j < elementClassesLength; j++) {
if (matchClasses.indexOf(elementClasses[j]) > -1) {
found++;
}
}
if (found == matchClasses.length) {
// Push onto matching array
}
If you want this function to only be available if it doesn't already exist, wrap its definition with
if (typeof document.getElementsByClassName != 'function') { }
Even easier jQuery solution:
$('.service').click( function() {
var id = "#" + $(this).attr('id') + 'rt';
$('.description').not(id).hide();
$( id ).show();
}
Why bother with a show class if you are using jQuery?
Heres one I put together, reliable and possibly the fastest. Should work in any situation.
function $class(className) {
var children = document.getElementsByTagName('*') || document.all;
var i = children.length, e = [];
while (i--) {
var classNames = children[i].className.split(' ');
var j = classNames.length;
while (j--) {
if (classNames[j] == className) {
e.push(children[i]);
break;
}
}
}
return e;
}
I used to implement HTMLElement.getElementByClassName(), but at least Firefox and Chrome, only find the half of the elements when those elements are a lot, instead I use something like (actually it is a larger function):
getElmByClass(clm, parent){
// clm: Array of classes
if(typeof clm == "string"){ clm = [clm] }
var i, m = [], bcl, re, rm;
if (document.evaluate) { // Non MSIE browsers
v = "";
for(i=0; i < clm.length; i++){
v += "[contains(concat(' ', #"+clc+", ' '), ' " + base[i] + " ')]";
}
c = document.evaluate("./"+"/"+"*" + v, parent, null, 5, null);
while ((node = c.iterateNext())) {
m.push(node);
}
}else{ // MSIE which doesn't understand XPATH
v = elm.getElementsByTagName('*');
bcl = "";
for(i=0; i < clm.length; i++){
bcl += (i)? "|":"";
bcl += "\\b"+clm[i]+"\\b";
}
re = new RegExp(bcl, "gi");
for(i = 0; i < v.length; i++){
if(v.className){
rm = v[i].className.match(bcl);
if(rm && rm.length){ // sometimes .match returns an empty array so you cannot use just 'if(rm)'
m.push(v[i])
}
}
}
}
return m;
}
I think there would be a faster way to iterate without XPATH, because RegExp are slow (perhaps a function with .indexOf, it shuld be tested), but it is working well
You can replace getElementsByClassName() with the following:
function getbyclass(n){
var elements = document.getElementsByTagName("*");
var result = [];
for(z=0;z<elements.length;z++){
if(elements[z].getAttribute("class") == n){
result.push(elements[z]);
}
}
return result;
}
Then you can use it like this:
getbyclass("description") // Instead of document.getElementsByClassName("description")

jquery remove duplicate li

<ul id="myid">
<li>microsoft</li>
<li>microsoft</li>
<li>apple</li>
<li>apple</li>
</ul>
I want to remove duplicates from li by using jquery.
How can I do that?
example
I find that the script is faster
var liText = '', liList = $('#myid li'), listForRemove = [];
$(liList).each(function () {
var text = $(this).text();
if (liText.indexOf('|'+ text + '|') == -1)
liText += '|'+ text + '|';
else
listForRemove.push($(this));
})​;
$(listForRemove).each(function () { $(this).remove(); });
uniqueLi = {};
$("#myid li").each(function () {
var thisVal = $(this).text();
if ( !(thisVal in uniqueLi) ) {
uniqueLi[thisVal] = "";
} else {
$(this).remove();
}
})
This build an index (an object) of unique values. For your example, uniqueLi will look like this afterwards:
{
"microsoft": "",
"apple": ""
}
So whenever a value is encountered that has been added to the index before, the associated <li> gets removed.
You could use
var inner = [];
$('li').each( function(index, Element){
if (jQuery.inArray(this.innerHTML, inner) == -1){
inner.push(this.innerHTML);
}
else {
$(this).remove();
}
});
Here's a function that will do it, a slightly different way:
function removeDuplicateItems(id) {
var ul = $('#' + id);
$('li', ul).each(function() {
if($('li:contains("' + $(this).text() + '")', ul).length > 1)
$(this).remove();
});
}
Call with removeDuplicateItems('myid');
I have used #Thariama solution in the past, but I have compatibility problems with IE6 (I still needs to support this dinosaur).
If the item repeats, so remove it from ul. It works with dynamic added li.
var seen = {};
$("ul#emails_exclusion_list").find("li").each(function(index, html_obj) {
txt = $(this).text().toLowerCase();
if(seen[txt]) {
$(this).remove();
} else {
seen[txt] = true;
}
});

Categories