jquery mutiple div with a single definition script - javascript

i have this jQuery code:
$(document).ready(function () {
$("#hide").click(function () {
$("div1").hide();
});
$("#show").click(function () {
$("div1").show();
});
});
and this jsp/html
for{int=0;i<V_loopnumber;i++)
{
%>
<button id='show' height:10px>showit</button>
<div1>
something
<button id='hide' height:10px>hideit</button>
</div1>
<%
}
For example if I have 3 elements, it produces 3 divs. However,if I push the button all the divs will be showed or hided cause they got the same name.
how can I differentiate the button with the respective divs?

Your markup has a few problems. You can not assign the same ID twice. Also div1 is not a valid tag name.
Perhaps you can restructure your markup along the lines of the following example:
<div class="container">
<button class="show">showit</button>
<div class="inner">
something
<button class="hide">hideit</button>
</div>
</div>
I assigned the buttons classes instead of ids and got rid of the div1 elements.
Now you can listen for a click event on the buttons and hide the related elements using the .closest() (http://api.jquery.com/closest/) method like this:
$(".hide").click(function () {
$(this).closest(".inner").hide();
});
$(this).closest(".inner") will retrieve the the closest element with the class inner up in the dom tree.
$(".show").click(function () {
$(this).parent().find(".inner").show();
});
$(this).parent().find(".inner") will go up one level in the dom tree and find the element with the class inner.
http://jsfiddle.net/KGk7B/

First, element ids must be unique. Use a class instead. Second, <div1> isn't a valid tag. Use a div with a class instead. Third, use traversal functions to find the specific element to toggle.
$(document).ready(function () {
$(".hide").click(function () {
$(this).closest('.show-hide-container').hide();
});
$(".show").click(function () {
$(this).next('.show-hide-container').show();
});
});
for{int=0;i<V_loopnumber;i++)
{
%>
<button class='show' height:10px>showit</button>
<div class="show-hide-container">
something
<button class='hide' height:10px>hideit</button>
</div>
<%
}

id must be unique on your page, use class
<button class='show' height:10px>showit</button>
and use $(this) in event callback function instead of using selector
$(".hide").click(function(){
$(this).parent().hide(); // this is hard select of your div1, i wrote only for your html
});
IMPORTANT: Use div instead of div1, div1 tag is undefined.

Related

How to dynamically remove elements in javascript?

Is there a way to dynamically remove elements with javascript or jquery. Suppose I have a function createElements() which creates new element and another function removeElement() which is suppose to remove the corresponding element. You will notice that when you run the snippet that when you click on the remove button all the element is gone! How could I implement this code? Isn't there a jquery selector where i could simply use removeElement(this) or somenething like that? Any suggestions are most welcome :) thank you.
function createElements() {
const boom = document.getElementById('boom');
boom.insertAdjacentHTML(
'beforeend', '<div class="newElem"><p >new element created dynamically yay!</p><button onclick="removeElement()">remove</button></div>'
);
}
function removeElement() {
alert('element removed dynamically boOoOoOoOooo!')
$('.newElem').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boom">
</div>
<br>
<button onclick="createElements()">Create new element</button>
You can do it like this:
function createElements() {
const boom = document.getElementById('boom');
boom.insertAdjacentHTML(
'beforeend', '<div class="newElem"><p >new element created dynamically yay!</p><button onclick="removeElement(this)">remove</button></div>'
);
}
function removeElement(element) {
alert('element removed dynamically boOoOoOoOooo!')
$(element).parent(".newElem").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boom">
</div>
<br>
<button onclick="createElements()">Create new element</button>
You just need to follow one single API. Use either pure JavaScript or jQuery. I would also suggest you to use unobstructive approach. Also, the way you remove the elements is wrong. You are removing everything.
See this way:
$(function() {
$("button#add").click(function() {
$("#boom").after('<div class="newElem"><p >new element created dynamically yay!</p><button class="remove">remove</button></div>');
});
$(document).on("click", ".remove", function() {
alert('element removed dynamically boOoOoOoOooo!')
$(this).closest(".newElem").remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boom">
</div>
<button id="add">Create new element</button>
To be able to always delete the div that encompasses the remove button, you have to traverse the DOM tree. There are lots of jQuery goodies for this: http://api.jquery.com/category/traversing/
In this particular case, I would do the following:
var elementCounter = 0;
function createElements() {
const boom = document.getElementById('boom');
boom.insertAdjacentHTML(
'beforeend', '<div class="newElem"><p >'+elementCounter+': new element created dynamically yay!</p><button onclick="removeElement(event)">remove</button></div>'
);
elementCounter++;
}
function removeElement(event) {
alert('element removed dynamically boOoOoOoOooo!')
$(event.target).closest('.newElem').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boom">
</div>
<br>
<button onclick="createElements()">Create new element</button>
So you pass on the click event to the function as a parameter, and then with event.target you find out which button was clicked. $(event.target).closest(".newElem") will get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Apply javascript function to same ids

I just want to ask let say if we have multiple divs with same id how can we display none them using javascript ?
I tried:
<script>
function filterfunc() {
if(document.getElementById('filter_deductible').value == 'id_50'){
document.getElementById('id_0').style.display = 'none';
document.getElementById('id_50').style.display = 'block';
}
}
</script>
And here is my html divs with same ids:
<div id="id_0">0</div>
<div id="id_0">0</div>
<div id="id_50">50</div>
But its hidding only one div of id id_0 instead of all div having id_0
Any suggestions please
Id must be unique, you should use class like,
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
And to hide all id_0 use
function filterfunc() {
if($('#filter_deductible').val() == 'id_50'){
$('div.id_0').hide();
$('div.id_50').show();
}
}
It simple using jQuery like
HTML
<select name="filter_deductible" id="filter_deductible">
<option value="id_0">0</option>
<option value="id_50">50</option>
</select>
<div id="id_0">0</div>
<div id="id_0">0</div>
<div id="id_50">50</div>
jQuery
$("#filter_deductible").change(function(){
if($(this).val()=="id_50")
{
$('[id="id_0"]').hide();
}
});
Demo
you should use a class in case there are multiple elements. Or use different ids.
Ids are meant to be unique.
<script>
function filterfunc() {
if(document.getElementById('filter_deductible').value == 'id_50'){
$('.id_0').css("display","none")
$('.id_50').css("display","block")
}
}
</script>
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
Or
<script>
function filterfunc() {
if(document.getElementById('filter_deductible').value == 'id_50'){
$('.id_0').hide()
$('.id_50').css("display","block")
}
}
</script>
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
Do not do this. Having multiple elements with the same ids leads to undefined behaviour. If you need to attach information to your dome nodes use data attributes or classes.
Notice how getElementById is singular form? It only ever expects to select and return one element.
That being said, you can probably get away with
document.querySelectorAll("#id_0")
if you want to use javascript functions on dom elements you have to use class not id attribute.
id attribute is unique in whole html document.
try to use jquery.
$.(document).ready(function(){
$("#filter_deductible").change(function(){
var $this = $(this); //instance of element where was changed value
if($this.val() == 'id_50'){
$(".id_0").hide();
$(".id_50").show();
}
});
});
your document html should looks like.
<div class="id_0">0</div>
<div class="id_0">0</div>
<div class="id_50">50</div>
this will works only if you will include jquery library inside tags. And your dom element #filter_deductible allows change event trigger.
hope i helped you
Use classes in this case ID is unique.
<div class="zero">0</div>
<div class="zero">0</div>
<div class="class_50">50</div>
you can use jQuery:
$('.zero').hide();
$('.class_50').show();
The HTML spec requires that the ID attribute to be unique in a page:
If you want to have several elements with the same ID your code will not work as the method getElementByID only ever returns one value and ID's need to be unique. If you have two ID's with the same value then your HTML is invalid.
What you would want to do is use div class="id_0" and use the method getElementsByClassName as this returns an Array of elements
function filterFunc() {
var n = document.getElementsByClassName("id_0");
var a = [];
var i;
while(n) {
// Do whatever you want to do with the Element
// This returns as many Elements that exist with this class name so `enter code here`you can set each value as visible.
}
}

how to recode my jquery/javascript function to be more generic and not require unique identifiers?

I've created a function that works great but it causes me to have a lot more messy html code where I have to initialize it. I would like to see if I can make it more generic where when an object is clicked, the javascript/jquery grabs the href and executes the rest of the function without the need for a unique ID on each object that's clicked.
code that works currently:
<script type="text/javascript">
function linkPrepend(element){
var divelement = document.getElementById(element);
var href=$(divelement).attr('href');
$.get(href,function (hdisplayed) {
$("#content").empty()
.prepend(hdisplayed);
});
}
</script>
html:
<button id="test1" href="page1.html" onclick="linkPrepend('test1')">testButton1</button>
<button id="test2" href="page2.html" onclick="linkPrepend('test2')">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
I'd like to end up having html that looks something like this:
<button href="page1.html" onclick="linkPrepend()">testButton1</button>
<button href="page2.html" onclick="linkPrepend()">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
If there is even a simpler way of doing it please do tell. Maybe there could be a more generic way where the javascript/jquery is using an event handler and listening for a click request? Then I wouldn't even need a onclick html markup?
I would prefer if we could use pure jquery if possible.
I would suggest setting up the click event in JavaScript (during onload or onready) instead of in your markup. Put a common class on the buttons you want to apply this click event to. For example:
<button class="prepend-btn" href="page2.html">testButton1</button>
<script>
$(document).ready(function() {
//Specify click event handler for every element containing the ".prepend-btn" class
$(".prepend-btn").click(function() {
var href = $(this).attr('href'); //this references the element that was clicked
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
});
});
</script>
You can pass this instead of an ID.
<button data-href="page2.html" onclick="linkPrepend(this)">testButton1</button>
and then use
function linkPrepend(element) {
var href = $(this).data('href');
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
}
NOTE: You might have noticed that I changed href to data-href. This is because href is an invalid attribute for button so you should be using the HTML 5 data-* attributes.
But if you are using jQuery you should leave aside inline click handlers and use the jQuery handlers
<button data-href="page2.html">testButton1</button>
$(function () {
$('#someparent button').click(function () {
var href = $(this).data('href');
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
});
});
$('#someparent button') here you can use CSS selectors to find the right buttons, or you can append an extra class to them.
href is not a valid attribute for the button element. You can instead use the data attribute to store custom properties. Your markup could then look like this
<button data-href="page1.html">Test Button 1</button>
<button data-href="page2.html">Test Button 1</button>
<div id="content">
</div>
From there you can use the Has Attribute selector to get all the buttons that have the data-href attribute. jQuery has a function called .load() that will get content and load it into a target for you. So your script will look like
$('button[data-href]').on('click',function(){
$('#content').load($(this).data('href'));
});
looking over the other responses this kinda combines them.
<button data-href="page2.html" class="show">testButton1</button>
<li data-href="page1.html" class="show"></li>
class gives you ability to put this specific javascript function on whatever you choose.
$(".show").click( function(){
var href = $(this).attr("data-href");
$.get(href,function (hdisplayed) {
$("#content").html( hdisplayed );
});
});
This is easily accomplished with some jQuery:
$("button.prepend").click( function(){
var href = $(this).attr("href");
$.get(href,function (hdisplayed) {
$("#content").html( hdisplayed );
});
});
And small HTML modifications (adding prepend class):
<button href="page1.html" class="prepend">testButton1</button>
<button href="page2.html" class="prepend">testButton2</button>
<div id="content"></div>
HTML code
<button href="page1.html" class="showContent">testButton1</button>
<button href="page2.html"class="showContent">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
JS code
<script type="text/javascript">
$('.showContent').click(function(){
var $this = $(this),
$href = $this.attr('href');
$.get($href,function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
}
});
</script>
Hope it helps.

JS Events not attaching to elements created after load

Problem: Creating an Element on a button click then attaching a click event to the new element.
I've had this issue several times and I always seem to find a work around but never get to the root of the issue. Take a look a the code:
HTML:
<select>
<option>567</option>
<option>789</option>
</select>
<input id="Add" value="Add" type="button"> <input id="remove" value="Remove" type="button">
<div id="container">
<span class="item">123</span>
<br/>
<span class="item">456</span>
<br/>
</div>
JavaScript
$(".item").click(function () {
if ($("#container span").hasClass("selected")) {
$(".selected").removeClass("selected");
}
$(this).addClass("selected");
});
$("add").click(function() {
//Finds Selected option from the Select
var newSpan = document.createElement("SPAN");
newSpan.innerHTML = choice;//Value from Option
newSpan.className = "item";
var divList = $("#container");
divList.appendChild(newSpan);//I've tried using Jquery's Add method with no success
//Deletes the selected option from the select
})
Here are some methods I've already tried:
Standard jQuery click on elements with class "item"
Including using the `live()` and `on()` methods
Setting inline `onclick` event after element creation
jQuery change event on the `#Container` that uses Bind method to bind click event handler
Caveat: I can not create another select list because we are using MVC and have had issues retrieving multiple values from a list box. So there are hidden elements that are generated that MVC is actually tied to.
Use $.on instead of your standard $.click in this case:
$("#container").on("click", ".item", function(){
if ( $("#container span").hasClass("selected") ) {
$(".selected").removeClass("selected");
}
$(this).addClass("selected");
});
It looks to me like you want to move the .selected class around between .item elements. If this is the case, I would suggest doing this instead:
$("#container").on("click", ".item", function(){
$(this)
.addClass("selected")
.siblings()
.removeClass("selected");
});
Also note your $("add") should be $("#add") if you wish to bind to the element with the "add" ID. This section could also be re-written:
$("#add").click(function() {
$("<span>", { html: $("select").val() })
.addClass("item")
.appendTo("#container");
});

select the #targetElem siblings(div class="content") animate

the html is
<a class="minimize" href="#targetElem" >Min</a>
<div id="targetElem">
<p class="handler"></p>
<div class="content">
content area
</div>
</div>
the javascript is the following code
$(document).ready(function(){
$('a.minimize').click(function() {
$($(this).attr('href')).siblings(".content").slideToggle("slow");
});
});
what i want is when click on the a href class minimize , the target of the href (#targetElem)no change, but select the #targetElem siblings(div class="content") animate, bcos i want to use them over and over,i don't want to add a lot of code to the .js file like the following code:
$(document).ready(function(){
$('a.minimize').click(function() {
$('#targetElem').siblings(".content").slideToggle("slow");
});
$('a.minimize1').click(function() {
$('#targetElem1').siblings(".content").slideToggle("slow");
});
$('a.minimize2').click(function() {
$('#targetElem2').siblings(".content").slideToggle("slow");
});
$('a.minimize3').click(function() {
$('#targetElem3').siblings(".content").slideToggle("slow");
});
});
so how can i do this???
Youre doing right, except that .content is not a sibling to the targetElem, but a child:
$(document).ready(function(){
$('a.minimize').click(function() {
$($(this).attr('href')).children(".content").slideToggle("slow");
});
});
sibling are all the element at the same level (brothers), and the children ar all the element inside the surrent element, but just one level depth (direct childs).
if you want go down all the hierarchy of an element you have to you the find method

Categories

Resources