change div id on drop with jquery - javascript

I have a bit of code that lets me drag and drop elements. The problem is that i don't know how to change the id of the element when it's dropped. It needs to stay a list with the right numbers.
<div class="container">
<div class="block">
<div id="draggables">
<div id="dragbox1" class="stepbox">
<label>Step 1</label>
<input type='text' placeholder="Omschrijving" name="textbox1">
</div>
<div id="dragbox2" class="stepbox">
<label>Step 2</label>
<input type='text' placeholder="Omschrijving" name="textbox2">
</div>
<div id="dragbox3" class="stepbox">
<label>Step 3</label>
<input type='text' placeholder="Omschrijving" name="textbox3">
</div>
</div>
</div>
</div>
When i drag a div (for example the div with id dragbox1 down under the div with id dragbox3) i want the jquery to rename the div id's so that it stays in the same order from 1,2,3 and not 2,3,1.
I'm thinking it should be sometging like the folowing:
var divClass = /*div class name*/;
var divId = /*static div id name*/;
var checkDivOrder = function(){
if(/*check for divs with the name of the divClass*/) {
if (divId === /*static div id name*/) {
divId = /*divIdName*/ + 1;
} else {
divId = /*divIdName*/ + /*previous div id number*/ + 1;
}
}
};
//recall function
if(/*div being dropped*/){
checkDivOrder(/*prev div number + 1*/);
}
Could someone help me with this as my jquery and javascript skills are not that great.

According to my understanding you want you div in order top to down like dragbox1,dragbox2,dragbox3 in sequence.
you can do like this.
$('.stepbox').each(function(ind,obj){
$(this).prop('id','dragbox'+(ind+1));
});

Related

html checkbox list that shows and hides links when filtered

I have written code that creates a checkbox list where when i click the checkbox below my list of options i would like a link to show underneath that the user can click (show/hide) I cannot figure out why my code will not work. If the user unchecked the box the link disappears but nothing happens when i click my check boxes. I would like to do this fix in JQuery
<!DOCTYPE html>
<html>
<div class ="container">
<head></head>
<body>
<input id="grp1" type="checkbox" value="group_1" onClick="http://google.com" />
<label for="grp1"> group 1 </label>
<div>
<input id="grp2" type="checkbox" value="group_2" onClick="http://google.com" >
group_2</label>
</div>
</body>
</html>
You'll have to use javascript to hide/show the wanted elements in html. There are many approaches to this. The most basic one would be something like
<!DOCTYPE html>
<html>
<body>
<div id="container">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
<!--hidden elements using css-->
Link for group_1
<br>
Link for group_2
</div>
<script>
//listen to the click event on the whole container
document.getElementById("container").onclick = function (e) {
//check every box if it's checked
if (document.getElementById('grp1').checked) {
document.getElementById('url1').style.display = 'block';
} else {
document.getElementById('url1').style.display = 'none';
}
if (document.getElementById('grp2').checked) {
document.getElementById('url2').style.display = 'block';
} else {
document.getElementById('url2').style.display = 'none';
}
}
</script>
</body>
</html>
Of course you can use different approaches like creating the element in javascript then adding it to the html if you don't like the idea if existing hidden elements. You might also use loops to loop through checkbox element and simply show/hide the url accordingly. And more to make the code flexible on any number of boxes. Something like this
<!DOCTYPE html>
<html>
<body>
<div id="container">
<div id="checkBoxContainer">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
</div>
<!--hidden elements using css-->
Link for group_1
<br>
Link for group_2
</div>
<script>
//listen to the click event on the whole container
document.getElementById("checkBoxContainer").onclick = function (e) {
var linkNumber = 1; //This is number of the first url element with ud url1
var containerChildren = document.getElementById("checkBoxContainer").children;
//loop through the children elements
for (var i = 0; i < containerChildren.length; i++) {
var oneChild = containerChildren[i]; //catch only one child in a variable
//simply filter the input elements which are of type checkbox
if(oneChild.tagName === "INPUT" && oneChild.type === "checkbox"){
//Show or hide the url accordingly.
if (oneChild.checked) {
document.getElementById('url' + linkNumber++).style.display = 'block';
} else {
document.getElementById('url' + linkNumber++).style.display = 'none';
}
}
}
}
</script>
</body>
</html>
The onclick HTML attribute doesn't work that way. The attribute value is executed as javascript. You can make a js function to show/hide the link.
Hi you want to try this:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.group-link{
display: block;
}
.hidden{
display: none;
}
</style>
</head>
<body>
<div class="jsParent">
<label for="grp1">
<input id="grp1" type="checkbox" value="group_1" onchange="showLink(this)"/> group 1
</label>
<a class="group-link hidden jsLink" href="https://www.animalplanet.com/tv-shows/dogs-101/videos/the-doberman">Group 1 Link</a>
</div>
<div class="jsParent">
<label for="grp2">
<input id="grp2" type="checkbox" value="group_2" onchange="showLink(this)"/> group_2
</label>
<a class="group-link hidden jsLink" href="https://www.animalplanet.com/tv-shows/cats-101/videos/ragdoll">Group 2Link </a>
</div>
<script type="text/javascript">
function showLink(el){
var parent = el.parentElement.parentElement;
var linkEl = getAnchorEl(parent);
if(linkEl){
if(el.checked){
linkEl.classList = linkEl.classList.value.replace('hidden', '');
}else{
linkEl.classList = linkEl.classList.value + ' hidden';
}
}
}
function getAnchorEl(parent){
var childrens = parent.children;
var linkEl = null;
for (var i = 0; i < childrens.length; i++) {
var childEl = childrens[i];
if(childEl.classList.value.indexOf('jsLink') > -1){
linkEl = childEl;
break;
}
}
return linkEl;
}
</script>
</body>
</html>
Your question is undoubtedly a duplicate but I am answering because I would like to help you identify issues with the code you posted.
I notice you have a <div>tag between your tag and tag. Why? This is a bit of an over simplification but as a general rule never put anything between your <html> and <head> tag and only place <div> tags inside your <body> tag. Also be mindful of how you nest your elements. That tag starts after and before .
Even if that were correct placement you close the before you close your div arbitrarily in the middle of your body tag. you should never have
<div>
<p>
</div>
</p>
Instead it should look like this
<div>
<p>
</p>
</div>
In your onClick attribute you have a random URL. That will not open a new window. You new too put some javascript in there.
<input onClick="window.open('http://google.com')">
Also your second label tag does not have an opening, just a </label> close tag
To answer your question - I suggest you look at the jQuery toggle function.
<input type="checkbox" id="displayLink" />
Google
<script type="text/javascript">
$("#displayLink").click(function(){
$("#googleLink").toggle();
});
</script>
As a general rule you should favor event handlers (such as the $("").click() posted above) to handle events (like clicking) as opposed to html attributes such as onClick.

How to Direct url When All ID on DIV click

I want make mini game but stuck with logic code.
Try see my code below,,,
I want to direct after click all div ID wrong1, wrong2, wrong3, then wrong4 (the last) its value for direct. Something add class maybe.
I want before the last click ID wrong4, The ID wrong4 its addclass rightAnswers. Because class rightAnswers have attribute html5 data-current-game="5" data-next-game="finish" for next result page.
I have try make it and helping by https://stackoverflow.com/users/2025923/tushar
Helping by Tushar, How to show last ID when All ID on DIV click,
But now i want different logic.
Thank you
Note :
I have try edit like this,
But the class rightAnswers not function ...
divs.splice(divs.indexOf($(this).prop("id")), 1)
if (divs.length == 0) {
$('#wrong1, #wrong2, #wrong3, #wrong4').addClass('rightAnswers');
}
And add script url direction like this :
But the class rightAnswers still not function
$(".rightAnswers").click(function() {
window.location = "/game/result";
});
Code From How to show last ID when All ID on DIV click
$(function () {
var divs = ["wrong1", "wrong2", "wrong3", "wrong4"];
$('#wrong1, #wrong2, #wrong3, #wrong4').click(function () {
$(this).animate({
opacity: 0,
top: 100,
}, 500);
divs.splice(divs.indexOf($(this).prop("id")),1)
if(divs.length == 0){
$('#wrong-gameOne').eq(0).hide();
$('#correct-gameOne').eq(0).show();
}
});
});
<img id="correct-gameOne" class="rightAnswer" src="http://authentic-scandinavia.com/system/images/tours/photos/10/thumbnail.jpg" data-current-game="1" data-next-game="2" style="display:none;" />
<img id="wrong-gameOne" class="wrongAnswer" src="http://authentic-scandinavia.com/system/images/tours/photos/125/thumbnail.jpg" data-current-game="1" data-next-game="2" />
<div id="wrong1" class="no-bottom">
<label>TEXT 1</label>
</div>
<div id="wrong2" class="no-bottom">
<label>TEXT 2</label>
</div>
<div id="wrong3" class="no-bottom">
<label>TEXT 3</label>
</div>
<div id="wrong4" class="no-bottom">
<label>TEXT 4</label>
</div>

How to toggle `<div>` items upon click of another div?

I have <div> structure like this
<!-- Parent -->
<div id="parentCategory" >
<input type="image" src="a.jpg" onClick="showNextCat('nextCategory1', 'block', 'nextCategory2', 'nextCategory3')" />
<input type="image" src="b.jpg" onClick="showNextCat('nextCategory2', 'block', 'nextCategory1', 'nextCategory3')" />
<input type="image" src="c.jpg" onClick="showNextCat('nextCategory3', 'block', 'nextCategory1', 'nextCategory2')" />
...
</div>
<!-- 1st Child -->
<div id="nextCategory1" style="display: none;">
<input type="image" src="1a.jpg" />
<input type="image" src="1b.jpg" />
</div>
<!-- 2nd Child -->
<div id="nextCategory2" style="display: none;">
<input type="image" src="2a.jpg" />
<input type="image" src="2b.jpg" />
</div>
<!-- 3rd Child -->
<div id="nextCategory3" style="display: none;">
<input type="image" src="3a.jpg" />
<input type="image" src="3b.jpg" />
</div>
My JS
function showNextCat(id, visibility, h1, h2) {
var item = document.getElementById(id);
document.getElementById(h1).style.display = "none";
document.getElementById(h2).style.display = "none";
if (item.style.display !== "none") {
item.style.display = "none";
}
else {
item.style.display = visibility;
}
}
I don't want to hardcode the showNextCat() method to hide non-selected <div>
Please Improvise the JS method.
There are 2 possible option either if you are using jquery
then it will be easier.
Let's see first jQuery's solution
Apply class="category" to all the element which you want to manipulate dynamically.
put value in html want to show like data-show="nextCategory1"
apply css
.category{
display:none;
}
Put this JS function
$('#parentCategory input').on('click',function(e){
$('.category').hide();
$('#'+$(this).data('show')).show();
});
View Fiddle
Now Let's see Javascript solution which is also bit of simillar
function showNextCat(id) {
var item = document.getElementById(id);
var elem = document.querySelectorAll(".category")
var i;
for (i = 0; i < elem.length; i++) {
elem[i].style.display='none';
}
item.style.display='block';
}
View Fiddle2
using jQuery you can make this easy. first thing to do, remove all the onClick events from your buttons. then, you have to define a css class for the selected divs :
.selected {
display : block;
}
then on the buttons, specify the id of the category concerned, for example
<input type="image" src="a.jpg" select-category="nextCategory1" />
all you need to do now, is to define the click event for all the buttons
$("[select-category]").click(function () {
$("#" + $(this).attr("select-category")).toggleClass("selected");
});
Note : this is not the only solutions.

How to use localstorage to remember appended items

Here's an Example in which images and hidden inputs get added to the div container #area on click. I want to use localstorage to remember the appended items on page load, but it isn't working with this line
localStorage.setItem("imagecookie",$('#area').find('div:empty:first').append(img).append(input));
...
localStorage.getItem("imagecookie");
Could anyone show me how to get it to work?
HTML:
<div class="box">
<img data-term="A" src="http://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/Crystal_Clear_action_run.png/40px-Crystal_Clear_action_run.png"/>
<input data-term="A" class="compare" type="checkbox"/>
</div>
<div class="box">
<img data-term="B" src="http://upload.wikimedia.org/wikipedia/en/thumb/9/99/Question_book-new.svg/50px-Question_book-new.svg.png"/>
<input data-term="B" class="compare" type="checkbox"/>
</div>
<div class="box">
<img data-term="C" src="http://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/30px-Commons-logo.svg.png"/>
<input data-term="C" class="compare" type="checkbox"/>
</div>
<div id="area"><div></div><div></div><div></div></div>
Code:
$('.compare').change(function(){
if($(this).is(':checked')){
var img = $('<img>'),
findimg = $(this).closest('.box').find('img'),
data_term = findimg.data('term');
img.attr('src', findimg.attr('src'));
img.attr('data-term',data_term);
var input = '<input type="hidden" name="imagecompare" value="'+data_term+'">';
localStorage.setItem("imagecookie",$('#area').find('div:empty:first').append(img).append(input));
}
else{
var term = $(this).data('term'),
findboximage = $('#area > div > img[data-term='+term+']')
findboximage.parent('div').empty();
}
});
$(document).on('click','#area > div',function(){
$(this).empty();
localStorage.clear();
});
localStorage.getItem("imagecookie");
Demo Fiddle : Store the contents; Retrieve back on page reload.
Demo : Just store the contents - Check the console to verify.
Storing HTML content would be a better option.
$('#area').find('div:empty:first').append(img).append(input)
localStorage.setItem("imagecookie",$('#area').html());

find the id of the next element present in next div-jquery

My form has number of input elements. When i looping through some elements i need to find the id of the next element which is in next div.
The whole code is in jsfiddle
$(":text[name^=sedan]").each(function(i){
var curTxtBox = $(this);
var curId = this.id;
alert(curId);
//var nextTextFieldId = $(this).closest('div').find('.number').attr("id"); // gives undefined
var nextTextFieldId = $('#'+curId).next('div:input[type=text]').attr("id"); // gives undefined
alert(nextTextFieldId )
});
this is not working. nextTextFieldId gives value undefined.
html
<div class="first">
<div class="second">
<input type="text" class ="myClass" name="sedan1" id = "sedan1" value="1" />
</div>
<div class="third">
<input type="text" class ="yourClass" name="suv1" id ="suv1" value="2"/>
</div>
</div>
<div class="first">
<div class="second">
<input type="text" class ="myClass" name="sedan2" id = "sedan2" value="3" />
</div>
<div class="third">
<input type="text" class ="yourClass" name="suv2" id = "suv2" value="" />
</div>
</div>
var nextTextFieldId = $(this).parent().next().find(':text').attr("id");
Expanding my comment (summary: don't do this, simply iterate over the jQuery object with for and be happy) into an answer:
$(document).ready(function(){
var $textBoxes = $(":text[name^=sedan]");
for(var i = 0; i < $textBoxes.length; ++i) {
var $curTxtBox = $textBoxes.eq(i);
alert($curTxtBox.attr("id"));
if (i < $textBoxes.length - 1) {
var nextTextBoxId = $textBoxes.eq(i + 1).attr("id");
alert(nextTextBoxId);
}
else {
// This was the last one, there is no "next" textbox
}
}
});
Note that:
Doing things this way does not require walking the DOM tree all the time like naive approaches using each (which end up searching the tree for the same element multiple times).
This approach will work correctly as long as you keep the sedanXX ids. Approaches that re-walk the DOM tree will break as soon as there is any significant change to your HTML.
If all you want is the id's, and they are incrementing integers, even this is overkill.
Try changing to this line:
var nextTextFieldId = $('#'+curId).parent().next('div:input[type=text]').attr("id"); // gives undefined
Your line expects the input tag to have a sibling div tag.

Categories

Resources