can you please tell me how to check element id preset in dom ?I am able to check that.But I need to use "continue" function . If the id is already present it increase the id till get that id which is not present in dom ?
In my Example:
"tc_1" is present Now when user press "test" but it check "tc_2" present if not it add .same in tc_3 and tc_4 .can we do that ?
if it id is exit
http://jsfiddle.net/2dLrw/4/
$(function(){
$('#test').click(function(){
var id;
if (typeof ($("#app li:last").attr('id')) == 'undefined') {
id = "tc_1";
} else {
id = $("#app li:last").attr('id');
if(!$("#" + id).length == 0) {
//not exist
}
var index = id.indexOf("_");
var count = id.substring(index + 1, id.length);
count = parseInt(count);
id = id.substring(0, index) + "_" + parseInt(count + 1);
}
var html = '<li id="'+id+'">'+id+'</li>';
$('#app').append(html);
});
});
when user press button it add go for check that id present on dom .if it is present it increase the value of id.if increase value also present then again it increase id.it increase untill it not find new id.
It is some like recursively check if id present in dom or not
Modify your javascript
$(function(){
$('#test').click(function(){
var id=0;
for(;id<10;id++){
if(!document.getElementById("tc_"+id)){
var html = '<li id="tc_'+id+'">'+"tc_"+id+'</li>';
$('#app').append(html);break;
}
}
});
});
Try this L http://jsfiddle.net/lotusgodkk/2dLrw/6/
$(function () {
$('#test').click(function () {
var m = 0;
var ul = $('#app');
$('#app li').each(function () {
var id = parseInt($(this).attr('id').split('_')[1]);
if (id > m) m = id;
});
m++;
var li = $('<li></li>');
ul.append(li);
li.attr('id','tc_'+m).text('tc_'+m);
});
});
HTML:
<ul id="app">
<li id="tc_1">tc_1</li>
<li id="tc_4">tc_4</li>
<li id="tc_9">tc_9</li>
</ul>
<button id="test">test</button>
Note: Make sure all li have Id. Or just add a check in the JS for it.
Related
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();
});
}
});
I'm running a function on an interval. I need to get element by class name, use the id of each and pass it into a function as a variable.
I've tried looping through each class name and passing the id to php but it passes an array (i think) or maybe an html index which i cant separate.
$(".eachUnread").each(function() {
var newId = this.id;
$(".eachUnread").load("../php/unreadEach.php?id="+newId);
console.log(newId);
});
I also tried..
var x = document.getElementsByClassName("eachUnread");
var i;
for (i = 0; i < x.length; i++) {
var newId = x[i].id;
console.log(newId);
$(".eachUnread").load("../php/unreadEach.php?id="+newId);
}
When the .eachUnread div loads its cycles through all the id's. How do I get it to load only the correct id?
simply this...
$(".eachUnread").each(function() {
$(this).load("../php/unreadEach.php?id="+this.id);
});
You need add param for each function(index, item) method and use attr for get id var newId = $(item).attr('id');
$(".eachUnread").each(function(index, item) {
var newId = $(item).attr('id');
$(".eachUnread").load("../php/unreadEach.php?id="+newId);
console.log(newId);
});
$(".eachUnread").each(function(index, item) {
var newId = $(item).attr('id');
$(".eachUnread").load("../php/unreadEach.php?id="+newId);
console.log(newId);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='eachUnread' id='test1'>A</div>
<div class='eachUnread' id='test2'>B</div>
<div class='eachUnread' id='test3'>C</div>
I created a function that creates a HTML chunk of code. Its ids are created dynamically with a tag variable collected from a form. Code:
$(function() {
$("#addTag").click(function() {
var tag = $("#tag").val();
$('section').append('<div id="galleryContainer' + tag + '"><div class=".gallery-header"><h1 >Tag:' + tag + '</h1><div class=".gallery-sort"><p>Sort by:</p><button onclick="sortImagesByPublishedDate()" >Data published</button><button onclick="sortImagesByTakenDate()">Data taken</button><div data-tag="' + tag + '" class="gallery component" id="' + tag + '"></div></div></div></div>');
mainFunction(tag);
});
});
Then I want to use sortImagesByPublishedDate() and sortImagesByTakenDate() by clicking a button, but I want them to sort images only in this particular gallery and not in all galleries. If I have one gallery, it works fine. Problems begin when I add more galleries. How should I select the variable $gallery in the following functions?
function sortImagesByPublishedDate() {
var $gallery = $('div.gallery'),
$galleryA = $gallery.children('a');
$galleryA.sort(function(a, b) {
var an = a.getAttribute('data-published'),
bn = b.getAttribute('data-published');
if (an > bn) {
return 1;
}
if (an < bn) {
return -1;
}
return 0;
});
$galleryA.detach().appendTo($gallery);
}
Use the .siblings method to select elements that are siblings of another element. So in your case you can just call
var $gallery = $(buttonElement).siblings(".gallery");
Since you are using inline JS to call the sort functions you need to modify it to pass this to your functions that way you can get a reference to the button that was clicked, ie:
Modified html
<button onclick="sortImagesByPublishedDate(this)">Date published</button>
JS
function sortImagesByPublishedDate(ele){
var $gallery = $(ele).siblings(".gallery"),
Demo
$(function(){
$("#addTag").click(function(){
var tag=$("#tag").val();
$('section').append('<div id="galleryContainer'+tag+'"><div class=".gallery-header"><h1 >Tag:'+tag+'</h1><div class=".gallery-sort"><p>Sort by:</p><button onclick="sortImagesByPublishedDate(this)" >Data published</button><button onclick="sortImagesByTakenDate(this)">Data taken</button><div data-tag="'+tag+'" class="gallery component" id="'+tag+'"></div></div></div></div>');
//mainFunction(tag);
});
});
function sortImagesByPublishedDate(ele){
var $gallery = $(ele).siblings(".gallery"),
$galleryA = $gallery.children('a');
alert($gallery[0].id);
$galleryA.sort(function(a,b){
var an = a.getAttribute('data-published'),
bn = b.getAttribute('data-published');
if(an > bn) {
return 1;
}
if(an < bn) {
return -1;
}
return 0;
});
$galleryA.detach().appendTo($gallery);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="tag">
<button id="addTag">Add</button>
<section>
</section>
Instead of inline js you could use delegated event handling to have listeners setup for your buttons:
Modified html
<button class="sortButton" data-sort="date">Data published</button>
<button class="sortButton" data-sort="taken">Data taken</button>
JS
$("section").on("click",".sortButton",function(){
//'this' will be the button clicked
var $gallery = $(this).siblings(".gallery");
var sortBy = $(this).data("sort");
if(sortBy == "date"){
//do date sort
} else if(sortBy == "taken"){
//do taken sort
}
//... rest of code
});
$(function() {
$("#addTag").click(function() {
var tag = $("#tag").val();
$('section').append('<div id="galleryContainer' + tag + '"><div class=".gallery-header"><h1 >Tag:' + tag + '</h1><div class=".gallery-sort"><p>Sort by:</p><button onclick="sortImagesByPublishedDate()" >Data published</button><button onclick="sortImagesByTakenDate()">Data taken</button><div data-tag="' + tag + '" class="gallery component" id="' + tag + '"></div></div></div></div>');
sortImagesByPublishedDate(tag); **// call the function and pass param tag**
mainFunction(tag);
});
});
function sortImagesByPublishedDate(tag) {
**// instead of class select id**
var $gallery = $('div#galleryContainer'+tag),
$galleryA = $gallery.children('a');
$galleryA.sort(function(a, b) {
var an = a.getAttribute('data-published'),
bn = b.getAttribute('data-published');
if (an > bn) {
return 1;
}
if (an < bn) {
return -1;
}
return 0;
});
$galleryA.detach().appendTo($gallery);
}
// hope this helps
Not tested but I think this will worl:
HTML:
sortImagesByPublishedDate(this)//pass this
JS:
function sortImagesByPublishedDate() {
var $gallery = $(this).siblings('.gallery'),
$galleryA = $gallery.children('a');
.
.
Pass this to sortImagesByPublishedDate(this) in your html of append
so your code is
function sortImagesByPublishedDate(thisObj) {
and then do
var $gallery = $(thisObj).siblings(".gallery");
I need to have buttons for moving up and down table rows with input's inside.
On move I need to guarantee that the input's name's and id's are changed
regarding to their new position
I've tried around on JSFiddle but couldn't get it to work: http://jsfiddle.net/vaDkF/1194/
For example I've the first row is moved down there are four changes:
<input type="text" id="id_1" name="id_1"/>
<input type="text" id="test_1" name="test_1"/>
needs to become
<input type="text" id="id_2" name="id_2"/>
<input type="text" id="test_2" name="test_2"/>
but the values need's to stay the same just need the id/name to change.
This is just a test example, in production environment I have like 20 inputs
per row.
Hope someone can help.
Try this : after rearranging the rows, call a function which will reassigne id and name to the input fields
$(document).ready(function(){
$(".up,.down").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
reAssignIdAndName();
});
reAssignIdAndName = function(){
$('table tr').each(function(index){
$(this).find('td:eq(2) input').each(function(){
//id of input element
var id = $(this).attr('id');
//get index of underscrore
var underScoreIndex = id.indexOf('_');
//take id till underscore and append your index+1 value
id = id.substring(0,underScoreIndex+1)+(parseInt(index)+1);
//assigne new id and name
$(this).attr('id',id);
$(this).attr('name',id);
});
});
};
});
Demo
This works and reAssign the position only for the 2 rows that moved :
jQuery(document).ready(function($){
$(".up,.down").click(function(){
var $this = $(this),
row = $this.parents("tr:first");
if ($this.is(".up")) {
if (row.parent().find("tr:first").get(0) !== row.get(0)) {
reAssignPosition(row.prev().find('input'));
row.insertBefore(row.prev());
reAssignPosition(row.find('input'), true);
}
} else {
if (row.parent().find("tr:last").get(0) !== row.get(0)) {
reAssignPosition(row.next().find('input'), true);
row.insertAfter(row.next());
reAssignPosition(row.find('input'));
}
}
});
function reAssignPosition($elt, up) {
var $row = $elt.parents("tr:first"),
oldPosition = parseInt($row.find('input').attr('id').replace(/(id|test)_/, '')),
newPosition, newId, newName, input = $row.find('input');
if (up) newPosition = oldPosition - 1;
else newPosition = oldPosition + 1;
$elt.each(function() {
this.id = this.id.replace(/(id|test)_(.*)/, "$1_" + (newPosition));
this.name = this.name.replace(/(id|test)_(.*)/, "$1_" + (newPosition));
});
}
});
Some refactoring can be done, I am sure, though.
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.