How to use it on multiple ids such that when #more1 is clicked , #details1 will appear. And when #more2 is clicked , #details2 will appear?
Note that I want it only using one function.
Thank U.
$(document).ready(function () {
$('#more1,#more2').click(function () {
$('#details1,#details2').slideToggle();
});
});
You can use a more general selector: $('[id^="more"]').
This will select all items that have an id that starts with "more", and will have a click event tied to them.
Then you can use the number in the id property and use it to build the id of the target.
$('[id^="more"]').click(function()
{
let id = $(this).attr('id');
let num = /\d+/.exec(id)[0];
$('#details' + num).slideToggle();
});
$(document).ready(function()
{
$('[id^="more"]').click(function()
{
let id = $(this).attr('id');
let num = /\d+/.exec(id)[0];
$('#details' + num).slideToggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button id="more1">One</button>
<span id="details1">Each Section</span>
</div>
<div>
<button id="more2">Two</button>
<span id="details2">Is Independent</span>
</div>
<div>...</div>
<div>
<button id="more25">Twenty Five</button>
<span id="details25">Of all the others</span>
</div>
You can check the id of the current item and act accordingly:
if($(this).attr('id') == 'more1') $('#details1').slideToggle();
A more elegant solution would be:
$('#details' + $(this).attr('id')[$(this).attr('id').length - 1]).slideToggle();
The last one uses the fact that the numbering in the ids is similar, and if you have less than 10 such ids it will work properly.
You can use for loop
$(document).ready(function()
{
var length = 9; // any number you need
for (var i = 0; i < length; i++ ) {
$('#more' + i).click(function()
{
$('#details' + i).slideToggle();
});
}
});
Related
I have try to create Dynamic Input group
My expected is
dynamic selection box[length in config var parameter] with...
Non-duplicate select option --> I check when click ,remove and append
Can click to add/remove input group
limited by var parameter
So now My actual result is
not hide will be select option in new select of previous select on append
delete select can't check the repeating after remove
But After i click some where will back to normal as i expect a little because item what i click still no update
So here for long code
Thank for viewing
var parameter =[
"A"
,"B"
,"C"
,"D"
];
$(document).ready(function(e){
$('div.multiselect').append('<div class="selectlist"></div>');
$('div.multiselect').append('<button class="btn btn-outline-light addlist">add search parameter</button>');
$('div.multiselect').append('<button class="btn btn-success search">search</button>');
addSelect();//Create first
$('div.multiselect .addlist').click(function(){
addSelect();
});
});
(function($) {
var origAppend = $.fn.append;
$.fn.append = function () {
return origAppend.apply(this, arguments).trigger("append");
};
})(jQuery);
var selectblock = function (){
var outside = $(document.createElement("div")).addClass('input-group');
var inside = $(document.createElement("select")).addClass('custom-select').on("click append",checkRepeat);
var selVal=[];
$("div.multiselect .selectlist div.input-group").each(function(){
selVal.push($(this).find("select").val());
});
if(selVal.length == parameter.length){
alert("Can't add more parameter");
return;
}
for (var i =0 ; i < parameter.length ; i++){
var option = $(document.createElement("option")).val(parameter[i]).text(parameter[i]);
if($.inArray(parameter[i], selVal) > -1){
option.attr("disabled","disabled").hide();
}
inside.append(option);
}
outside.append(inside);
outside.append($(document.createElement("input")).attr('Type','Text').addClass('form-control'));
var delbtn = $(document.createElement("button")).text("X").addClass('btn btn-danger input-group-append dellist');
delbtn.click(function(){
$(this).parent().remove();
checkRepeat;
});
outside.append(delbtn);
return outside;
};
function addSelect(){
$('div.multiselect .selectlist').append(selectblock);
checkRepeat;
}
var checkRepeat = function (){
//console.log('trigger');
var selVal=[];
$("div.multiselect .selectlist div.input-group").each(function(){
selVal.push($(this).find("select").val());
});
$(this).parent().siblings("div.multiselect .selectlist div.input-group").find("select").find("option").removeAttr("disabled").show().filter(function(){
var a=$(this).parent("select").val();
return (($.inArray(this.value, selVal) > -1) && (this.value!=a));
}).attr("disabled","disabled").hide();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="multiselect">
Is there any way to check if two divs are having same ids?
I have created divs dynamically and I am finding it difficult to remove the div having a duplicate id, can anyone help here?
I do not know what you are trying to achieve here , but generally you should not have two elements with the same id . But if you have some reason to do this maybe you are building a validator or someting like this you can do the following to count the number of elements
var count = document.querySelectorAll('#test').length;
console.log(count);
then you can loop through them and remove them using
document.querySelectorAll('#test')[1].remove();
Try it with:
$('[id]').each(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
You have to loop all the elements as helpers like getElementById() won't work well when their aren't unique.
Example, no need for jQuery. Alerts the duplicate ID.
var idMap = {};
var all = document.getElementsByTagName("*");
for (var i=0; i < all.length; i++) {
// Do something with the element here
var elem = all[i];
if(elem.id != ""){ //skip without id
if(idMap[elem.id]){
alert("'" + elem.id + "' is not unique")
}
idMap[elem.id] = true;
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<div id="id1"></div>
<div id="id2"></div>
<div id="id3"></div>
<div id="id4"></div>
<div id="id5"></div>
<div id="id1"></div>
</body>
</html>
var idList = [];
$('*[id]').each(function(){
var id = $(this).attr('id');
if($.inArray(id, idList)){
alert('the id ' + id + ' is already set!');
} else {
idList.push(id);
}
});
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if (ids.length>1 && ids[0]==this){
$("#"+this.id).remove();
}
});
above function use jquery to create array of all IDs with in the document and remove duplicated id
Something like this should do what you want
$('[id]').each(function (i) {
$('[id="' + this.id + '"]').slice(1).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "1">
ola
</div>
<div id = "2">
ole
</div>
<div id = "1">
ola
</div>
<div id = "3">
olo
</div>
<div id = "1">
ola
</div>
<div id = "3">
olo
</div>
Example based on the link: jQuery: Finding duplicate ID's and removing all but the first
Can you not just control + F and search for the id's? Also if you are using an editor like atom, you can delete every other duplicate in one go after the search.
I have a list with about 10 000 customers on a web page and need to be able to search within this list for matching input. It works with some delay and I'm looking for the ways how to improve performance. Here is simplified example of HTML and JavaScript I use:
<input id="filter" type="text" />
<input id="search" type="button" value="Search" />
<div id="customers">
<div class='customer-wrapper'>
<div class='customer-info'>
...
</div>
</div>
...
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#search").on("click", function() {
var filter = $("#filter").val().trim().toLowerCase();
FilterCustomers(filter);
});
});
function FilterCustomers(filter) {
if (filter == "") {
$(".customer-wrapper").show();
return;
}
$(".customer-info").each(function() {
if ($(this).html().toLowerCase().indexOf(filter) >= 0) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
}
</script>
The problem is that when I click on Search button, there is a quite long delay until I get list with matched results. Are there some better ways to filter list?
1) DOM manipulation is usually slow, especially when you're appending new elements. Put all your html into a variable and append it, that results in one DOM operation and is much faster than do it for each element
function LoadCustomers() {
var count = 10000;
var customerHtml = "";
for (var i = 0; i < count; i++) {
var name = GetRandomName() + " " + GetRandomName();
customerHtml += "<div class='customer-info'>" + name + "</div>";
}
$("#customers").append(customerHtml);
}
2) jQuery.each() is slow, use for loop instead
function FilterCustomers(filter) {
var customers = $('.customer-info').get();
var length = customers.length;
var customer = null;
var i = 0;
var applyFilter = false;
if (filter.length > 0) {
applyFilter = true;
}
for (i; i < length; i++) {
customer = customers[i];
if (applyFilter && customer.innerHTML.toLowerCase().indexOf(filter) < 0) {
$(customer).addClass('hidden');
} else {
$(customer).removeClass('hidden');
}
}
}
Example: http://jsfiddle.net/29ubpjgk/
Thanks to all your answers and comments, I've come at least to solution with satisfied results of performance. I've cleaned up redundant wrappers and made grouped showing/hiding of elements in a list instead of doing separately for each element. Here is how filtering looks now:
function FilterCustomers(filter) {
if (filter == "") {
$(".customer-info").show();
} else {
$(".customer-info").hide();
$(".customer-info").removeClass("visible");
$(".customer-info").each(function() {
if ($(this).html().toLowerCase().indexOf(filter) >= 0) {
$(this).addClass("visible");
}
});
$(".customer-info.visible").show();
}
}
And an test example http://jsfiddle.net/vtds899r/
The problem is that you are iterating the records, and having 10000 it can be very slow, so my suggestion is to change slightly the structure, so you won't have to iterate:
Define all the css features of the list on customer-wrapper
class and make it the parent div of all the list elements.
When your ajax request add an element, create a variable containing the name replacing spaces for underscores, let's call it underscore_name.
Add the name to the list as:
var customerHtml = "<div id='"+underscore_name+'>" + name + "</div>";
Each element of the list will have an unique id that will be "almost" the same as the name, and all the elements of the list will be on the same level under customer-wrapper class.
For the search you can take the user input replace spaces for underscores and put in in a variable, for example searchable_id, and using Jquery:
$('#'+searchable_id).siblings().hide();
siblings will hide the other elements on the same level as searchable_id.
The only problem that it could have is if there is a case of two or more repeated names, because it will try to create two or more divs with the same id.
You can check a simple implementation on http://jsfiddle.net/mqpsppxm/
I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.
I've just created an dynamic HTML form and two of its fields are of type date. Those two fields are posting their data into two arrays. I have 2 issues:
a) The array data are not printed when I press the button.
b) Since I created the arrays to store the data, my dynamic form doesn't seem to be fully functional. It only produces new fields when I press the first "Save entry" button on the form. It also doesn't delete any fields.
My code is:
$(document).ready(function () {
$('#btnAdd').click(function () {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
newElem.children('div').each(function (i) {
this.id = 'input' + (newNum * 10 + i);
});
newElem.find('input').each(function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$('#btnDel').click(function () {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
$(function () {
$("#datepicker1").datepicker({
dateFormat: "yy-mm-dd"
}).datepicker("setDate", "0");
});
var startDateArray = new Array();
var endDateArray = new Array();
function intertDates() {
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
startDateArray[startDateArray.length] = inputs;
endDateArray[endDateArray.length] = inputsend;
window.alert("Entries added!");
}
function show() {
var content = "<b>Elements of the arrays:</b><br>";
for (var i = 0; i < startDateArray.length; i++) {
content += startDateArray[i] + "<br>";
}
for (var i = 0; i < endDateArray.length; i++) {
content += endDateArray[i] + "<br>";
}
}
JSFIDDLE
Any ideas? Thanks.
On your button you are using element ID's several times, this is so wrong, IDs must be unique for each element, for example:
<button id="btnAdd" onclick="insertDates()">Save entry</button>
</div>
</div>
<button id="btnAdd">Add Address</button>
<button id="btnDel">Delete Address</button>
jQuery will attach the $('#btnAdd') event only on the first #btnAdd it finds.
You need to use classes to attach similar events to multiple elements, and in addition to that simply change all the .click handlers to .on('click', because the on() directive appends the function to present and future elements where as .click() only does on the existing elements when the page is loaded.
For example:
<button id="btnDel">Delete Address</button>
$('#btnDel').click(function () {
[...]
});
Becomes:
<button class="btnDel">Delete Address</button>
$('.btnDel').on('click', function () {
[...]
});
Try this : I know its not answer but it's wrong to get element value using id
Replace
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
With
var inputs = document.getElementById('datepicker1').value;
var inputsend = document.getElementById('datepicker2').value;
You are using jQuery so i will strongly recommend you to stick with the jQuery selector,
var inputs = $('#datepicker1').val();
var inputsend = $('#datepicker2').val();
where # is used for ID selector.