jquery moving up/down in loop - javascript

I am trying to move the elements in the div up/down. Once its moved the item.position has to be swapped with the previous one. Below is the code. Can someone please suggest how to pass the newly assigned position and associated data seq into an array so they can passed to controller and inserted to database
<c:forEach var="item" items="${entry.value }" >
<ul>
<li> <div class="rows">
<a id='${item.position}' data-seq='${attr.id}' class="noDownloadFormat" href="/files/${item.value}" target="_blank"><c:out value="${item.title}" /></a>
<div style="float:right;margin-top:-15px;">
<input type="button" class="btn" value="UP" />
</div>
</div>
</li>
<ul>
</c:forEach>
Jquery:
$(document).ready(function () {
$(".btn1").click(function(){
var $current = $(this).closest('li')
var currentval =$(this).closest('li').children().find("a").prop("id");
var prevVal=$current.prev('li').children().find("a").prop("id");
var $previous = $current.prev('li');
if($previous.length !== 0){
$current.insertBefore($previous);
$(this).closest('li').children().find("a").prop("id",prevVal);
$current.prev('li').children().find("a").prop("id")==currentval ;
}
return false;
});
});
thanks
I modified the jquery and now I am able move up and down but not able to swap the position

I done just up button...
Tweak it online.
<html>
<body>
<ul>
<li>
<div class="rows">
<a id='position1' data-seq='id1' class="noDownloadFormat" href="#" target="_blank">title1</a>
<div style="float:right;margin-top:-15px;">
<input type="button" class="btn" value="UP 1">
</div>
</div>
</li>
<li>
<div class="rows">
<a id='position2' data-seq='id2' class="noDownloadFormat" href="#" target="_blank">title2</a>
<div style="float:right;margin-top:-15px;">
<input type="button" class="btn" value="UP 2">
</div>
</div>
</li>
<li>
<div class="rows">
<a id='position3' data-seq='id3' class="noDownloadFormat" href="#" target="_blank">title3</a>
<div style="float:right;margin-top:-15px;">
<input type="button" class="btn" value="UP 3">
</div>
</div>
</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var handler = function (e) {
$li = $(e.target).parent().parent().parent();
// Avoid delete element if it's at top of list.
if ($li.prev().size() !== 0) {
// Move element.
$li.prev().before($li.remove());
// Bind click handler to new button.
$('.btn', $($li)).click(handler);
}
};
$('.btn').on('click', handler);
</script>
</body>
</html>

Related

JavaScript How to Print A Label in a DIV?

I have 4 boxes labeled a1, a2, a3, a4 as an example. And when someone clicks on 2 boxes, I want the label (a1, a2 as an example) to print on html output. I just spent over an hour and the best I can come up was printing undefined and null.
Sorry, here is my code
HTML
<div class="container">
<div class="row">
<div class="col-md-3" label="a1">
<a class="btn btn-primary" href="#" role="button">Button 01</a>
<div class="output"></div>
</div>
<div class="col-md-3" label="a2">
<a class="btn btn-primary" href="#" role="button">Button 02</a>
<div class="output"></div>
</div>
<div class="col-md-3" label="a3">
<a class="btn btn-primary" href="#" role="button">Button 03</a>
<div class="output"></div>
</div>
<div class="col-md-3" label="a4">
<a class="btn btn-primary" href="#" role="button">Button 04</a>
<div class="output"></div>
</div>
</div>
</div>
const button = document.querySelector('.btn');
button.addEventListener('click', printLabel);
function printLabel(){
const name = document.querySelector('label');
const print = document.querySelector('.output');
print.innerText = name;
}
label isn't really a standard attribute of the <div> tag. You could try id if you're just looking for a quick solution. Also, you're accessing everything in a pretty strange way.
You should change label to id. The id attribute is pretty much universal to all HTML elements (that I know of) and will allow you to uniquely identify that element.
<div class="container">
<div class="row">
<div class="col-md-3" id="a1">
<a class="btn btn-primary" href="#" role="button">Button 01</a>
<div class="output"></div>
</div>
<div class="col-md-3" id="a2">
<a class="btn btn-primary" href="#" role="button">Button 02</a>
<div class="output"></div>
</div>
<div class="col-md-3" id="a3">
<a class="btn btn-primary" href="#" role="button">Button 03</a>
<div class="output"></div>
</div>
<div class="col-md-3" id="a4">
<a class="btn btn-primary" href="#" role="button">Button 04</a>
<div class="output"></div>
</div>
</div>
</div>
Add a unique id to all of the div elements that are meant to be your "output". This will allow your code to direct the "output" to the right element.
<div class="container">
<div class="row">
<div class="col-md-3" id="a1">
<a class="btn btn-primary" href="#" role="button">Button 01</a>
<div class="output" id="a1-output"></div>
</div>
<div class="col-md-3" id="a2">
<a class="btn btn-primary" href="#" role="button">Button 02</a>
<div class="output" id="a2-output"></div>
</div>
<div class="col-md-3" id="a3">
<a class="btn btn-primary" href="#" role="button">Button 03</a>
<div class="output" id="a3-output"></div>
</div>
<div class="col-md-3" id="a4">
<a class="btn btn-primary" href="#" role="button">Button 04</a>
<div class="output" id="a4-output"></div>
</div>
</div>
</div>
Finally, a couple of changes to your JavaScript. The first change you'll see is that I changed document.querySelector('.btn') to document.querySelectorAll('.btn'). The difference between these methods is that the first one selects ONLY the first element it finds that matches the selector, but the second one selects all elements that match the selector and creates an array.
Next, we loop through that array to add an event listener for each element.
After that, we add a parameter e (for event) to the printLabel() function because addEventListener() passes an event object in the callback function (printLabel). This object gives information about the target element related to the event.
Next, we get the target element of the event and that's your button. Then we get the parentElement of your button because your id or "label" is on the parent element. Then, you can get the name from the id of the parent element.
As a note, remember that id attributes CANNOT have spaces or . or # or really most special characters besides _.
Finally, we need to select your "output" element, and we'll use the id to do that.
document.querySelector('#' + name + '-output'); will get the element that has an id with the given name + -output. For example, if you click button a1 this will get the element with the id of a1-output. The # signifies that you're searching for an id.
Now that we stored this element in a variable print, we can place the text in it using the innerHTML property.
const button = document.querySelectorAll('.btn');
for(var i=0; i < button.length; i++) {
button[i].addEventListener('click', printLabel);
}
function printLabel(e) {
var target = e.target;
var parent = target.parentElement;
const name = parent.id;
const print = document.querySelector('#' + name + '-output');
print.innerHTML = name;
}
I created a JSFiddle to help you.
If you have any questions, please let me know.
<script>
function printDiv(divName){
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
<h1> do not print this </h1>
<div id='printMe'>
Print this only
</div>
<button onclick="printDiv('printMe')">Print only the above div</button>
We can use event bubbling and data attributes to our advantage here. Replace your label attribute which is non-standard with a data attribute. Also, don't use a if it is not a navigation element, use button instead.
//Get the divs
let divs = document.querySelectorAll("[data-label]")
for(var i = 0; i < divs.length; i++){
//Add the event listener to the DIVs, yes the divs
divs[i].addEventListener("click", function(event){
//Did a button fire the event?
if(event.target.tagName === "BUTTON"){
//update the output div in the clicked div
this.querySelector(".output").innerText = this.dataset.label;
}
});
}
<div class="container">
<div class="row">
<div class="col-md-3" data-label="a1">
<button class="btn btn-primary" role="button">Button 01</button>
<div class="output"></div>
</div>
<div class="col-md-3" data-label="a2">
<button class="btn btn-primary"role="button">Button 02</button>
<div class="output"></div>
</div>
<div class="col-md-3" data-label="a3">
<button class="btn btn-primary" role="button">Button 03</button>
<div class="output"></div>
</div>
<div class="col-md-3" data-label="a4">
<button class="btn btn-primary" role="button">Button 04</button>
<div class="output"></div>
</div>
</div>
</div>
just change your script part to the following to make it work without changing HTML
<script>
//getting all buttons
var buttons = document.getElementsByClassName("btn");
//adding event listner to all buttons
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", printLabel, false);
}
function printLabel() {
const outputDiv = this.parentElement.querySelector(".output"); // this will select only closet div with given class
outputDiv.innerText = this.parentElement.getAttribute("label");
}
</script>

How to disable jQuery blur event on certain selector

I have the following jQuery and HTML which hide the search result when the focus on the input has been lost.
This code hides my div with id #searchResult when the elements on #searchResult are clicked. I want to disable blur when elements on #searchResult div are clicked. Basically, I want to hide <div id="searchResult"> when the focus is lost and show when it's on focus. How can I achieve that?
$(document).on("blur", "#txtSearchTerm", function () {
$('#searchResult').hide();
});
$(document).on("focus", "#txtSearchTerm", function () {
$('#searchResult').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="txtSearchTerm" type="text">
<div id="searchResult">
<ul>
<li>
<a href="http://www.google.com">
<div class="title">Google.com</div>
<div class="content">Click here</div>
</a>
</li>
<li>
<a href="http://www.google.com">
<div class="title">Google.com</div>
<div class="content">Click here</div>
</a>
</li>
</ul>
</div>
<div id="searchResult"> will be hidden on every click of elements inside it.
You can simply turn off your blur event with the following code.
$(document).off("blur", "#txtSearchTerm");
You dont need blur event to achieve that:
$(document).click(function(e) {
if ($(e.target).is("div") && $(e.target).has("ul > li")){
$('#searchResult').show()
}
else $('#searchResult').hide()
if ($(e.target).is(':focus')){
$('#searchResult').show()
}
})
#searchResult{
margin-top: 50px;
border: 2px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="txtSearchTerm" type="text">
Click out the input to hide div
<div id="searchResult">
<ul>
<li>
<a href="http://www.google.com">
<div class="title">Google.com</div>
<div class="content">click here</div>
</a>
</li>
<li>
<a href="http://www.google.com">
<div class="title">Google.com</div>
<div class="content">click here</div>
</a>
</li>
</ul>
</div>
You can't do that, because the blur is fired before the click on the child.
So you would need to add an event handler on the document which closes the results. You cancel that event when someone clicks the results. Something like this:
$('#txtSearchTerm').click(function(e) {
$('#searchResult').show();
e.stopPropagation();
});
$(document).click(function(e) {
$('#searchResult').hide();
});
$('#searchResult').click(function(e) {
e.stopPropagation();
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="txtSearchTerm" type="text">
<div id="searchResult">
<ul>
<li>
<a href="http://www.google.com">
<div class="title">Google.com</div>
<div class="content">Click here</div>
</a>
</li>
<li>
<a href="http://www.google.com">
<div class="title">Google.com</div>
<div class="content">Click here</div>
</a>
</li>
</ul>
</div>
My advise it to check relatedTarget and kill blur only if user clicks on certain elements.
$(document).on("blur", "#txtSearchTerm", function (e) {
if ($(e.relatedTarget).hasClass("no-blur")){
}else{
$('#searchResult').hide();
}
});
$(document).on("focus", "#txtSearchTerm", function () {
$('#searchResult').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="txtSearchTerm" type="text">
<div id="searchResult">
<ul>
<li>
<a href="http://www.google.com">
<div class="title">Google.com</div>
<div class="content">click here</div>
</a>
</li>
<li>
<a href="http://www.google.com">
<div class="title">Google.com</div>
<div class="content">click here</div>
</a>
</li>
</ul>
</div>

increment class onclick javascript

i would like to know how i can increment class on click my class="item" i want to change on click every time to item1 item2 item3 exc how can i do this? this is what i want to incrament
<div href="#" class="item" data-bind="draggable:true,droppable:true">
<div class="item">
<textarea data-bind="value:textContent1" Placeholder="Type text to append"></textarea>
</div>
<button data-bind="click:addNew">Generate New Div</button>
<div href="#" class="item" data-bind="draggable:true,droppable:true">
<span data-bind="click:$parent.remove">X</span>
<br/>
<br/>
<center>
<span class="text i" data-bind="text:$data"></span><input class="edit_text"/></center>
</div>
HTML
<button onclick="addNew()">Generate New Div</button>
<div id="my_div" class="item1"></div>
JavaScript
var i = 1;
function addNew() {
document.getElementById("my_div").classList.remove("item" + i++);
document.getElementById("my_div").classList.add("item" + i);
}
This will increment the class name each time the button is clicked.

Getting clicked button values jquery

I am trying to find clicked button value.here is my htmlcode,I am not able to get but always getting first one.
<div id="addSentiment" class="dialogs">
<div id="1" class="dialogs">
<div class="itemdiv dialogdiv">
<div class="user">
<img src="assets/avatars/avatar1.png" alt="Alexas Avatar">
</div>
<div class="body">
<div class="time"> <i class="ace-icon fa fa-clock-o"></i>
<span class="green">Date : 10/01/2014</span>
</div>
<div class="name"> ki#n.com
</div>
<div id="cat_1" class="text">category : Scheduling
<br>
</div>
<div id="op_1" class="text">ddd word/phrase : providing solutions
<br>
</div>
<div id="feature_1" class="text">ddd word/phrase : listen to
<br>
</div>
<div class="text">
<input type="hidden" value="1" name="hd">
</div>
<div class="tools"> <a id="edit_1" class="btn acebtn btn-minier btn-info" href="#">
<i class="icon-only ace-icon fa fa-share"></i>
</a>
</div>
</div>
</div>
</div>
<div id="2" class="dialogs">
<div class="itemdiv dialogdiv">
<div class="user">
<img src="assets/avatars/avatar1.png" alt="Alexas Avatar">
</div>
<div class="body">
<div class="time"> <i class="ace-icon fa fa-clock-o"></i>
<span class="green">Date : 10/01/2014</span>
</div>
<div class="name"> tc#n.com
</div>
<div id="cat_2" class="text">category : Scheduling
<br>
</div>
<div id="op_2" class="text">dddd : providing solutions
<br>
</div>
<div id="feature_2" class="text">ddddddde : listen to
<br>
</div>
<div class="text">
<input type="hidden" value="2" name="hd">
</div>
<div class="tools"> <a id="edit_2" class="btn acebtn btn-minier btn-info" href="#">
<i class="icon-only ace-icon fa fa-share"></i>
</a>
</div>
</div>
</div>
</div>
<div id="3" class="dialogs">
<div class="itemdiv dialogdiv">
<div class="user">
<img src="assets/avatars/avatar1.png" alt="Alexas Avatar">
</div>
<div class="body">
<div class="time"> <i class="ace-icon fa fa-clock-o"></i>
<span class="green">Date : 10/01/2014</span>
</div>
<div class="name"> tn#nn.com
</div>
<div id="cat_3" class="text">category : Scheduling
<br>
</div>
<div id="op_3" class="text">Opinion word/phrase : providing solutions
<br>
</div>
<div id="feature_3" class="text">Feature word/phrase : listen to
<br>
</div>
<div class="text">
<input type="hidden" value="3" name="hd">
</div>
<div class="tools"> <a id="edit_3" class="btn acebtn btn-minier btn-info" href="#">
<i class="icon-only ace-icon fa fa-share"></i>
</a>
</div>
</div>
</div>
</div>
</div>
I tried following code in jquery
$(".dialogs .itemdiv .tools").live("click",function(e){
e.preventDefault();
alert('clicked on edit');
var n = $('.dialogs .itemdiv .tools a').attr('id');
alert(n);
});
I use live here because I am getting above html by using append method in jquery.
live is deprecated in later versions of jQuery - but to solve your issue you need to use an instance of this
$("#addSentiment").on("click", ".dialogs .itemdiv .tools", function(e){
e.preventDefault();
alert('clicked on edit');
var n = $("a", this).attr('id');
alert(n);
});
jQuery selectors catch the first match of their content.
To catch the n-th match, you need to use the n-th child selector, like this:
$(".dialogs .itemdiv .tools:nth-child(2)")
I am not familiar with the live method, but you should be able to do something like the following:
function addHandlers() {
$(".dialogs .itemdiv .tools a").each(function() {
$(this).click(function() {
alert('clicked on edit');
);
});
}
function yourAppendFunction() {
//your append code
//add call to a function that will create your event handlers
addHandlers();
}
The .each method runs through each and every item that fits the selection criteria, and then we use the this keyword within the function to reference what we are working on. Putting it in a function that we don't call until after you append the items ensures the html exists when you try to add the handlers you need.
API references:
each method: http://api.jquery.com/each/
click method: http://api.jquery.com/click/

Exclude element with specific class using jquery

I am trying to get product name in alert box when either image or link is clicked on product page. But there is also one buy now button available which is also currently giving the popup alert if it is clicked. I want to exclude it using jquery. Here is what I am going
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(".item").click(function (event) {
var href = $('a', this).attr("href");
var target = $('a', this).attr("target");
var text = $(this).find('.product-name').text();
event.preventDefault();
alert(text);
setTimeout(function () {
window.open(href, (!target ? "_self" : target));
}, 300);
});
});
</script>
<li class="item">
<a href="product1.php" title="Sample Product Name" class="product-image">
<span class="sale-item">Sale!</span>
<div class="cat-mouseover"></div>
<img src="/images/product1.png" alt="Sample Product Name">
</a>
<h2 class="product-name">Sample Product Name</h2>
<div class="price-box">
<p class="old-price">
<span class="price-label">For:</span>
<span class="price" id="old-price-426"> 199,-</span>
</p>
<p class="special-price">
<span class="price-label"></span>
<span class="price" id="product-price-426"> Now 139,- </span>
</p>
</div>
<div class="actions">
<button type="button" title="Buy Now" class="button btn-cart" onclick="setLocation('/checkout/cart/add/uenc/aHR0cDovL3d3dy52aXRhLm5vLw,,/product/426/')"><span><span>Buy</span></span>
</button>
</div>
</li>
<li class="item">
<a href="product1.php" title="Sample Product Name" class="product-image">
<span class="sale-item">Sale!</span>
<div class="cat-mouseover"></div>
<img src="/images/product1.png" alt="Sample Product Name">
</a>
<h2 class="product-name">Sample Product Name</h2>
<div class="price-box">
<p class="old-price">
<span class="price-label">For:</span>
<span class="price" id="old-price-426"> 199,- </span>
</p>
<p class="special-price">
<span class="price-label"></span>
<span class="price" id="product-price-426"> Now 139,- </span>
</p>
</div>
<div class="actions">
<button type="button" title="Buy Now" class="button btn-cart" onclick="setLocation('/checkout/cart/add/uenc/aHR0cDovL3d3dy52aXRhLm5vLw,,/product/426/')"><span><span>Buy</span></span>
</button>
</div>
</li>
http://jsfiddle.net/585BC/
Please advise.
Put this at the top of your callback:
if ($(event.target).hasClass("btn-cart") || $(event.target).parents(".btn-cart").length !== 0) {
return;
}
Now if the "event.target" (= where the click occured) has the class "btn-cart" or is a child of this "btn-cart", then the execution of your callback returns.
See updated fiddle: http://jsfiddle.net/585BC/2/
Just exit the event handler if you click the button:
if(($(event.target).is('.button.btn-cart')) return;
// rest of your code goes here

Categories

Resources