jQuery - hover works only on every 2nd div - javascript

I have a problem. I'm creating a divs from input form, but when I hover my mouse with .hover function, it works only on every second div element (first, third, 5th, 7th...). How do I solve that? What's wrong with JS function?
Thanks for answers.
JS:
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val(); //string z inputa
if (query !== "") {
var trashButton = "<button class='trash'>DEL</button>"
var registry = "<div class='drag'>" + "<p>" + query + "</p>" + trashButton + "</div>"
$("#list").append(registry); //add div with query and ubbton
$("#list").sortable({
//axis: "y",
});
$(".drag").hover(function() {
$(this).toggleClass("mousehover")
});
$("#entry").val(""); //clear value
return false; //also stops refreshing
console.log(registry);
}
})
HTML:
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
CSS:
body {
font-size: 14px;
}
form {
float:right;
}
.container {
min-width:300px;
width:20%;
margin: 0 auto;
margin-top:5px;
}
.drag {
margin-top:5px;
background-color:lemonchiffon;
display:inline-flex;
width:100%;
}
.trash {
position:absolute;
margin-left:190px;
}
.mousehover {
opacity:0.5;
}

The problem is that you are adding the hover event multiple times. It is better to do it only once, using $(document).on().
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val(); //string z inputa
if (query !== "") {
var trashButton = "<button class='trash'>DEL</button>"
var registry = "<div class='drag'>" + "<p>" + query + "</p>" + trashButton + "</div>"
$("#list").append(registry); //add div with query and ubbton
$("#list").sortable({
//axis: "y",
});
$("#entry").val(""); //clear value
return false; //also stops refreshing
console.log(registry);
}
});
$(document).on("mouseenter mouseleave", ".drag", function() {
$(this).toggleClass("mousehover");
});
body {
font-size: 14px;
}
form {
float:right;
}
.container {
min-width:300px;
width:20%;
margin: 0 auto;
margin-top:5px;
}
.drag {
margin-top:5px;
background-color:lemonchiffon;
display:inline-flex;
width:100%;
}
.trash {
position:absolute;
margin-left:190px;
}
.mousehover {
opacity:0.5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>

Here you go with a solution https://jsfiddle.net/wcu4w1mn/
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val(); //string z inputa
if (query !== "") {
var trashButton = "<button class='trash'>DEL</button>"
var registry = "<div class='drag'>" + "<p>" + query + "</p>" + trashButton + "</div>"
$("#list").append(registry); //add div with query and ubbton
$("#list").sortable({
//axis: "y",
});
$(".drag").last().hover(function() {
$(this).toggleClass("mousehover")
});
$("#entry").val(""); //clear value
return false; //also stops refreshing
console.log(registry);
}
})
body {
font-size: 14px;
}
form {
float:right;
}
.container {
min-width:300px;
width:20%;
margin: 0 auto;
margin-top:5px;
}
.drag {
margin-top:5px;
background-color:lemonchiffon;
display:inline-flex;
width:100%;
}
.trash {
position:absolute;
margin-left:190px;
}
.mousehover {
opacity:0.5;
}
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
Only changed code
Add hover event to only last added element.
$(".drag").last().hover(function() {
$(this).toggleClass("mousehover")
});
Hope this will help you.

Related

Button did not trigger JS function

I create a button, then the button is supposed to triggered a JS function that will call another JS function. I tried to put Alert function in JS to test if it triggered, but it didn't. Anyone can help me?
Why it didn't get triggered?
$(document).ready(function() {
$("#btnProcess3").attr("disabled", "disabled");
alert("hi")
jsProcess(0);
$("#btnProcess3").click(function() {
alert("hi")
$(this).attr("disabled", "disabled");
jsProcess(1);
});
});
function jsProcess(action) {
var page;
var sDate;
var sBizDate;
sDate = $('#txtDate').val();
if ($('#chkuseBizDate').is(':checked')) {
sBizDate = $('#txtBizDate').val();
} else {
sBizDate = sDate;
}
page = "LoadPPSFile_details01.asp?TaskId=<%=sTaskId %>&txtDate=" + (sDate) + "&RunProcess=" + action + "&txtBizDate=" + (sBizDate);
document.getElementById("IProcess").src = page;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<input type="button" name="btnProcess" id="btnProcess3" value="Start - Services" width="250" style="VISIBILITY:show; WIDTH: 150px; HEIGHT: 22px; Background-Color:#1E90FF; Border-Color:white; Color:white; Font-Weight:bold;Font-family:Verdana;Cursor:hand; "
/>
Your code is missing some code that the jsProcess() is looking for, but the Button performs as excepted, when you remove the Disabling part.
$(document).ready(function() {
// $("#btnProcess3").attr("disabled", "disabled");
// alert("hi")
// jsProcess(0);
$("#btnProcess3").click(function() {
alert("I'm triggered!")
$(this).attr("disabled", "disabled");
// jsProcess(1);
});
});
function jsProcess(action) {
var page;
var sDate;
var sBizDate;
sDate = $('#txtDate').val();
if ($('#chkuseBizDate').is(':checked')) {
sBizDate = $('#txtBizDate').val();
} else {
sBizDate = sDate;
}
page = "LoadPPSFile_details01.asp?TaskId=<%=sTaskId %>&txtDate=" + (sDate) + "&RunProcess=" + action + "&txtBizDate=" + (sBizDate);
document.getElementById("IProcess").src = page;
}
#btnProcess3 {
VISIBILITY: show;
WIDTH: 150px;
HEIGHT: 22px;
Background-Color: #1E90FF;
Border-Color: white;
Color: white;
Font-Weight: bold;
Font-family: Verdana;
Cursor: hand;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<input type="button" name="btnProcess" id="btnProcess3" value="Start - Services" width="250">

Create multiple divs with different content

The problem is when duplicate multiple div but with different data-type, it still running a same content, i want correct all div will have the different content following the different data-type.
Is there a way to do this?
$(function() {
// document
'use strict';
var cp = $('div.box');
// unique id
var idCp = 0;
for (var i = 0; i < cp.length; i++) {
idCp++;
cp[i].id = "cp_" + idCp;
}
// diffrent type
if (cp.data('type') == "c1") {
cp.addClass('red').css({
"background: 'red',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c1-title' + '</div>');
} else if (cp.data('type') == "c2") {
cp.addClass('green').css({
"background": 'green',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c2-title' + '</div>');
} else {
return false;
}
}); //end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<! it should be like this>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c2 title</div>
</div>
<! currently wrong output>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c1 title</div>
</div>
The problem in your code is that you are not looping inside the div's. You have to use the .each() function while looping inside all the elements
$(function() {
var cp = $('div.box');
cp.each(function() {
var _cp = $(this);
var text = _cp.attr("data-type") + "-title"; //Generate the text dynamically
var cls = _cp.attr("data-class"); //Get the class dynamically
_cp.addClass(cls).append('<div class="cp-title">' + text + '</div>'); //Add the class and append the text to the parent div
});
}); //end
.box{
padding: 20px;
display: table;
}
.red{
background: red;
}
.green{
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1" data-class="red"></div>
<div class="box" data-type="c2" data-class="green"></div>
Probably you're searching for something like this.
// document.ready
$(function() {
'use strict';
$('.box').each(function(i,elem){
var ref = +$(elem).attr("data-type").match(/\d/)[0], addClass = 'default';
switch(true) {
case ref === 1:
addClass = 'red';
break;
case ref === 2:
addClass = 'green';
break;
}
$(this)
.addClass(addClass)
.append('<div class="cp-title">c'+ref+' title</div>');
});
}); //end
.red{
background: red;
padding: 20px;
display: table;
}.green{
background: green;
padding: 20px;
display: table;
}.default {
background: #2d2d2d;
color: #f6f6f6;
padding: 20px;
display: table;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1"></div><div class="box" data-type="c2"></div>

jQuery how to auto adjust the number list when 1 of the list is removed?

I want to automatically adjust the number list that was created using .append(). Example, if there are 4 items added on the list which will numbered from 2-4 respectively and if I removed item number 3, the item number 4 will automatically be number 3 and if I add a new item, it will be the last on the list. Here's my code below.
$('#display').click(function() {
$('#show').show();
});
var c = 1;
$('#append').click(function() {
var cnt = $('.cnt').val();
for (var i = 0; i < cnt; i++) {
c++;
$('#inputs').append("<div id='inputs' name='" + c + "'>" + c + ".)<button id='remove' name='" + c + "'>X</button></div>");
}
});
$(document).on('click', '#inputs #remove', function() {
var nm = $(this).attr('name');
$('div[name="' + nm + '"]').remove();
c--;
});
#show {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<button id='display'>Display</button>
<div id='show'>
<br>
<input type='text' class='cnt' value='1' placeholder="num of append" />
<button id='append'>+</button>
<br>
<div id='inputs'>
1.)
</div>
</div>
Here is the jsfiddle of the code.
here is your answer
Fiddle Here
$('#display').click(function() {
$('#show').show();
});
var c = 1;
$('#append').click(function() {
var cnt = $('.cnt').val();
for (var i = 0; i < cnt; i++) {
c++;
$('#inputs').append("<div class='inputs' name='" + c + "'><span class='number'>" +c + "</span>.)<button class='remove' name='" + c + "'>X</button></div>");
}
});
$(document).on('click', '#inputs .remove', function() {
var nm = $(this).attr('name');
$('div[name="' + nm + '"]').remove();
c--;
resetCount();
});
function resetCount(){
$('#inputs div.inputs').each(function(i){
$('.number', $(this)).text(i+2);
$('input', $(this)).attr('name', i+2);
});
}
#remain,
#total {
background-color: #333;
width: 60px;
height: 20px;
color: #fff;
padding: 0 10px;
}
input:focus {
background-color: #000;
color: #fff;
}
input {
background-color: #ccc;
}
#show {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id='display'>Display</button>
<div id='show'>
<br>
<input type='text' class='cnt' value='1' placeholder="num of append" />
<button id='append'>+</button>
<br>
<div id='inputs'>
1.)
</div>
</div>
You should not be using the same ID for different elements
Also the way you could do this is by creating a function that resets the elements counting after each add/delete event
When creating and appending elements in jQuery its better to use this syntax:
$('<ELEMENT TAG/>',{
ATTRIBUTE: VALUE
});
When looping through elements in jQuery its better to use $.each
$('#append').on('click', function(){
$('<div/>', {
'class': 'inputs',
html: '<span class="count"></span><input type="text" class="time" name="0" value="00:00:00"/><button>X</button>'
}).appendTo('#inputs');
resetInputsCount();
});
$('#inputs').on('click', '.inputs button', function(){
var $this = $(this);
$this.parent().remove();
resetInputsCount();
});
//The function that resets the count span text and the name value based on the current count of elements
function resetInputsCount(){
//looping through elements
$('#inputs div.inputs').each(function(i){
//caching the current element in a var named $this
var $this = $(this);
//changing the count span text to i+2 the 2 is added because the index starts at 0 and there is already one element 1.)
$('.count', this).text((i+2) + '.) ');
//change the value of the input name
$('input', $this).attr('name', i+2);
});
}
Demo on JSFiddle
I know theres an answer already but since I did the work I might as well post it.
Here's the fiddle for the example
here's the code:
Html
<div id='button'>
<span>Add</span>
</div>
<div id='content'></div>
CSS
#button span {
padding: 5px 15px;
background: #ccc;
cursor: pointer;
}
#button {
margin: 5px 0;
}
.delete {
cursor: pointer;
padding: 0 5px;
border: 1px solid gray;
}
jQuery
$(document).ready(function() {
var index = 1;
$('#button').on('click', function() {
var add = '<div class="new"><span class="number">' + index + '</span><input type="text"/><span class="delete">x</span></div>';
$('#content').append(add);
index++;
});
$(document).on('click', '.delete', function() {
index--;
$(this).parent().remove();
var index2 = 1;
var newelement = $('.new');
$(newelement).each(function() {
$(this).find('.number').text(index2);
index2++;
});
});
});
Using your html structure and adding some input fields (to be sure we maintain values)
Here is my approach:
(Also fixed duplicate id and names you have)
$('#display').click(function() {
$('#show').show();
});
var c = 1;
var inputs = [];
$('#append').click(function() {
var cnt = $('.cnt').val();
for (var i=0; i<cnt; i++) {
c++;
$div = $("<div id='input"+c+"' />").data('index', c);
$span = $("<span />").text(c+".)");
$button = $("<button class='input_remove' />").text("X");
$input = $("<input type='text' class='small' />").attr("name","input"+c);
$div.append($div).append($span).append($input).append($button);
$('#inputs').append($div);
}
});
$(document).on('click', '.input_remove', function() {
index = $(this).parent().data('index');
$("#inputs").find('#input'+index).remove();
c = 1;
$("#inputs").find('div').each(function(index,ele){
c++;
$(ele).attr('id',"input"+c).data('index',c)
.find("span").text(c+".)").end()
.find("input").attr("name","input"+c);
});
});
#show {
display: none;
}
.small { width:100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<button id='display'>Display</button>
<div id='show'>
<br>
<input type='text' class='cnt' value='1' placeholder="num of append" />
<button id='append'>+</button>
<br>
<div id='inputs'>
1.)
</div>
</div>

How to dynamically create table in html with certain constraints?

i want to take input from user(number) and display image as many times as number.If user inputs 5 then the image should be displayed 5 times next to each other with corresponding number below the images-Below 1st image '1' 2nd Image '2'.Basically putting this table in loop.
<HTML>
<BODY>
<TABLE>
<TR>
<TD>
<IMG SRC="C:/Users/User/Desktop/RE/G.JPG">
</TD>
</TR>
<TR><TD ALIGN="CENTER">1</TD>
</TABLE>"
</BODY>
</HTML>
You can use jQuery for this task and write a function that generates HTML with a dynamic value:
Complete Solution
<HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function generateTable(number) {
return "<table><tr><td>" +
"<img src='C:/Users/User/Desktop/RE/G.JPG'></td></tr><tr><td align='center'>" +
number +
"</td></table>";
}
$(function(){
var userInput = 3;
for (var i = 0; i < userInput; i++) {
$('#dynamic').append(generateTable(i + 1));
}
});
</script>
</head>
<body>
<div id='dynamic'></div>
</body>
</html>
You can add an input and a button to trigger the function.
You could also check if the inserted value is actually a number or not.
$(document).on('click', '#add', function() {
var that = $(this);
var times = parseInt($('#times').val());
for (i=1;i<=times;i++) {
$('#table-wrp').append('<table class="table-times"><tbody><tr><td><img src="http://code52.org/aspnet-internationalization/icon.png" /></td></tr><tr><td>' + i + '</td></tr></tbody></table>');
}
});
$(document).on('input', '#times', function() {
var that = $(this);
var value = that.val();
if ((value != '' || value != false) && !isNaN(value)) {
$('#add').prop('disabled', false);
} else {
$('#add').prop('disabled', true);
}
});
#table-wrp {
height: 80px;
}
.table-times {
width: 100px;
height: 80px;
float: left;
border-collapse: collapse;
}
.table-times td {
border: 1px solid #d8d8d8;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="textbox" id="times" />
<button id="add" disabled>Add</button>
<div id="table-wrp"></div>
Or for a pure javascript version of Pugazh's answer
var tab = "<div></div>";
var num = prompt("Enter a number");
for(i = 0; i < num; i++){
document.getElementById('tab').innerHTML += "<div><div><img src='http://placehold.it/150x150'></div><div></div></div>";
}
img{
float: left;
box-shadow: 5px 5px 10px rgba(0,0,0,0.4);
height: 100px;
width: 100px;
margin: 10px;
}
<div id="tab"></div>
This will work just as well, but doesn't require jQuery as well.
<HTML>
<BODY>
<div id="tbl"></div>
</BODY>
</HTML>
<script>
var num = prompt("Enter a number");
var div=document.getElementById("tbl");
var l1='',l2="";
for(i=0;i<num;i++)
{
l1 += '<td><img src="C:/Users/User/Desktop/RE/G.JPG"></td>';
l2 += '<td>'+i+'</td>';
}
div.innerHTML = "<table><tr>"+l1+"</tr><tr>" + l2 + "</tr></table>";
</script>
Try this
$(function() {
var tab = "<div></div>";
var num = prompt("Enter a number");
for (i = 0; i < num; i++) {
$("#tab").append("<div class='left'><div><img src='http://placehold.it/150x150'></div><div>" + (i + 1) + "</div></div>");
}
});
div.left {
display: inline-block;
margin-right: 5px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="tab">
</div>
</body>
</html>

show borders and handles on textarea when highlighted

I have dynamically created textareas which are nested in a dynamcally created divs. the divs are draggabnle and the textareas are resizable using jquery.
I want the border and drag/resize handles for any paticular div/textarea to only appear when the user clicks on that paticular textarea. I am assuming I would need to use the same onclick event that the draggable is using but I dont have the js knowledge for making the handles and border show up.
any help greatly appreciated
here is my code
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<style>
body{background-color:#ccc;}
.dragbox{width:10px; height:10px;padding: 0.0em; margin:25px; border:0;cursor:move; z-index:2}
.textarea1{ width: 300px; height: 300px; padding: 0.5em; z-index:3}
#handle{
display: block;
height: 16px;
width: 100px;
background-color: red;
position: absolute;
top:-15px;
left:0px;
font-size:10px;
}
#content
{
position:absolute;
top:150px;
left:0px;
margin:auto;
z-index:1;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src = "http://js.nicedit.com/nicEdit-latest.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
var i=0;
var p=25;
}
function editor1(idf) {
//var body = document.body;
// The magic
document.getElementById(idf).addEventListener ("dblclick", function (event) {
var target = event.target;
if (target.nodeName === "TEXTAREA") {
var area = new nicEditor ({fullPanel : true}).panelInstance (target);
area.addEvent ("blur", function () {
this.removeInstance (target);
});
}
}, false);
};
function NewTextArea(id)
{
id=id+i;
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.setAttribute('class', 'dragbox');
newdiv.setAttribute('iterate',i);
newdiv.style.position = "relative";
newdiv.style.top = p;
newdiv.style.left = p;
newdiv.style.cursor='move';
newdiv.innerHTML = "<div id='handle'>Drag me into position</div></div><br><textarea id='"+i +"' onDblClick='editor1("+i+")' name='textarea["+i +"]' class='textarea1' style='position:absolute; top:0px;left:0px;overflow-y: auto;background-color:transparent;border: 2px dashed #000; '>some text here</textarea>";
newdiv.innerHTML=newdiv.innerHTML+"<br><input type='hidden' value='"+i+"' name='id["+i+"]'><br><input name='box_type["+i+"]' type='hidden' value='text'/>";
newdiv.innerHTML=newdiv.innerHTML+"<br><input type='hidden' value='300' name='width["+i+"]' id='width"+i+"'><br><input type='hidden' value='300' name='height["+i+"]' id='height"+i+"'>";
newdiv.innerHTML=newdiv.innerHTML+"<br><input type='hidden' value='0' name='left["+i+"]' id='left"+i+"'><br><input type='hidden' value='0' name='top["+i+"]' id='top"+i+"'>";
document.getElementById("frmMain").appendChild(newdiv);
$(function()
{
$("#"+i).resizable(
{
stop: function(event, ui)
{
var width = ui.size.width;
var height = ui.size.height;
// alert("width="+width+"height="+height);
ValProportions(width,height,ui.element.context.id);
}
});
$( "#"+id ).draggable(
{
stop: function(event, ui)
{
Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
// alert("left="+Stoppos.left+"top="+Stoppos.top);
ValPostion(Stoppos.left,Stoppos.top,$(this).attr('iterate'));
}
});
$("#"+i).draggable({handle:"#handle"});
});
function ValProportions(defaultwidth, defaultheight,id) {
$('#width'+id).val(defaultwidth);
$('#height'+id).val(defaultheight);
}
function ValPostion(defaultleft,defaulttop,id) {
$('#left'+id).val(defaultleft);
$('#top'+id).val(defaulttop);
}
i++;
p=p+25;
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain" enctype="multipart/form-data" action="dynamic_div5.php" method="post">
<input id="btn1" type="button" value="Add New textbox" onClick="NewTextArea('draggable');"/>
<input type="submit" value="Save Page" >
</form>
</body>
</html>
If I understand the question correctly, this can be done with just CSS:
textarea { resize:none; border:none; }
textarea:focus { resize:both; border:1px solid #000; }
JSFiddle example.

Categories

Resources