jQuery add unique identifier to inputs and class on clone() - javascript

This code dynamically adds a unique number to the id of each item. I want to be able to add a unique identifier to certain classes and id's in every new clone() and not only to the .item itself.
In this snippet I need the function to follow the same pattern for the [data-input="checkbox0"] and the [class="radio0"].
As a bonus, I would like to have only one .add button clone() the new .items instead of having one inside of each .item.
var rowNum = 0;
$("body").on("click", ".add", function() {
rowNum++;
var $item = $(this).parents('.item');
var next = $item.clone();
next.attr('id', 'item' + rowNum);
$item.after(next);
});
.item {
border: 2px solid;
height: 50px;
width: 50px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item" id="item0">
<label class="icon">
<input data-input="checkbox0" class="toggle" type="checkbox" name="toggle"/>
</label>
<label>
<input type="radio" class="radio0">
<div class="add">
<button type="button" class="addbtn">Add</button>
</div>
</div>

You might want something like this.
$("body").on("click", ".addbtn", function() {
var $item = $('.item').last();
var next = $item.clone();
// Gets last number dynamically, instead of saving it as global variable.
var rowNum = parseInt($item.attr("id").substr(4)) + 1;
next.attr('id', 'item' + rowNum).find("input[type='checkbox']").attr("data-input", "checkbox" + rowNum);
next.find("input[type='radio']").attr("class", "radio" + rowNum);
$item.after(next);
});
.item {
border: 2px solid;
height: 50px;
width: 50px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item" id="item0">
<label class="icon">
<input data-input="checkbox0" class="toggle" type="checkbox" name="toggle"/>
</label>
<input type="radio" class="radio0" />
</div>
<button type="button" class="addbtn">Add</button>

You just change the html a little bit, move add button outside and use $('.item').last() to get last item for the list item
var rowNum = 0;
$("body").on("click", ".addbtn", function() {
rowNum++;
var $item = $('.item').last();
var next = $item.clone();
next.attr('id', 'item' + rowNum);
$item.after(next);
next.find('input[type="checkbox"]').attr('data-input', 'checkbox' + rowNum);
next.find('input[type="radio"]').attr('data-input', 'radio' + rowNum);
});
.item {
border: 2px solid;
height: 50px;
width: 50px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item" id="item0">
<label class="icon">
<input data-input="checkbox0" class="toggle" type="checkbox" name="toggle"/>
</label>
<input type="radio" class="radio0" />
</div>
<button type="button" class="addbtn">Add</button>

Related

jQuery/JavaScript Get input values and then copy to clipboard

I have a bunch of input elements and with javascript on click i'm getting the values of these inputs and paste it in a div somewhere
Please run the code snipped below to check
$('#getthelist').click(function() {
$('.inputs>li .color').map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e) {
$('.list').append('<div>' + '\"' + e.name + '\": \"' + e.value + '\",</div>');
});
});
ul,li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<div class="list"></div>
So i have got one question and a problem i cant figure out how to fix.
The problem is, each time you click the button it pastes the values in the div repeatedly. It is a mess to me for what i'm trying to do. so, How do i force it not to repeat the same values when you click every time.
Question: How do i copy the input values to clipboard with the same click function?
Please check my snippet codes.
function copyToClipboad(texts) {
var textareaElCloned = $('<textarea>' + texts + '</textarea>');
$('.list').append(textareaElCloned);
/* Select the text field */
textareaElCloned[0].select();
/* Copy the text inside the text field */
document.execCommand("copy");
}
$('#getthelist').click(function() {
var html = '';
var texts = '';
var itemEls = $('.inputs > li .color');
itemEls.map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e, index) {
var text = '\"' + e.name + '\": \"' + e.value + '\",';
texts += text;
html += ('<div>' + text + '</div>');
if (index === itemEls.length-1) {
copyToClipboad(texts);
}
});
$('.list').html(html); // the textarea will be removed at this moment
});
ul,li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<div class="list" tabindex="1"></div>
save your data in localStorage.setItem (return value of .map must save in localstorage)
get your data with localStorage.getItem (get data from localstorage with key that you set for item)
create a template with handlebar.js, and when click on checkbox, render template with data that get from localstorage.
for new data, you must update localstorage.
I have tested the solution from Dipak chavda but it does not work for me also. The problem is that the input is type of hidden. So I changed it to hidden textarea. When you try to copy, I make it visible for a while, focus it, select it's value and then exec the copy. And it works ;)
function copyData(copyText) {
var $txtCopyArea = $("#txtCopyArea");
// set the text as value
$txtCopyArea.val(copyText);
// make textarea visible
$txtCopyArea.removeClass('hidden');
/* focus & select the text field */
$txtCopyArea.focus().select();
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText);
// hide textarea
$txtCopyArea.addClass('hidden');
}
$('#getthelist').click(function() {
// Clear html div content
$('.list').html("");
var copyText = "";
$('.inputs>li .color').map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e) {
var _data = '<div>' + '\"' + e.name + '\": \"' + e.value + '\",</div>';
$('.list').append(_data);
copyText += _data;
});
copyData(copyText);
});
ul,
li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<textarea id="txtCopyArea" class="hidden"></textarea>
<div class="list"></div>
I tried to give you both questions answer.
Answer of Q1
you should reset HTML content before set new value.
Answer of Q2
you should use document.executeCommand("copy") to copy the text.
Hope it may help to resolve your issue.
function copyData(copyText) {
$("body").append($("<textarea/>").val(copyText).attr({id:"txtareaCopyData"}));
var copyText = document.querySelector("#txtareaCopyData");
copyText.select();
document.execCommand("copy");
$("#txtareaCopyData").remove();
}
$('#getthelist').click(function() {
// Clear html div content
$('.list').html("");
var copyText = "";
$('.inputs>li .color').map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e) {
var _data = '<div>' + '\"' + e.name + '\": \"' + e.value + '\",</div>';
$('.list').append(_data);
copyText += _data;
});
copyData(copyText);
document.querySelector("#txtCopyArea").addEventListener("click", copyData);
});
ul,
li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<input type="hidden" id="txtCopyArea" name="txtCopyArea" />
<div class="list"></div>

How to get the sidebar to not interact?

I want to make a webpage that adds points when you click on it. There is a sidebar(just a left column) where there are images that act as checkboxes. Selecting one image gets you 1 point when you click on the page, selecting the other gives 5...
However, I don't want to have the sidebar give points. It means that when you click on it, it only changes the selected image, without adding points. Everything is working except the "not adding points on the sidebar" part. I tried the following code, but it doesn't work:
function addPoint(number) {
points = points + number;
document.getElementById('points').innerHTML = points;
};
function pointsAmount() {
chkBox1 = document.getElementById('picture1').checked;
addPoint(chkBox1 ? 1 : 0);
chkBox2 = document.getElementById('picture2').checked;
addPoint(chkBox2 ? 5 : 0);
chkBox3 = document.getElementById('picture3').checked;
addPoint(chkBox3 ? 10 : 0);
chkBox4 = document.getElementById('picture4').checked;
addPoint(chkBox4 ? 20 : 0);
};
function checkPicture(x, y) {
document.getElementById(x).checked = y;
}
function Border(x, y) {
document.getElementById(x).style.borderColor = y;
}
function onPageload() {
checkPicture('picture1', true);
Border('pic1', 'yellow');
}
window.onload = onPageload;
window.onmousedown = function(e) {
if (e.target.className != 'float-left-area') {
pointsAmount();
}
}
var points = 0;
body {
margin-top: 0px;
margin-right: 0px;
margin-left: 0px;
margin-bottom: 0px;
}
input[type=checkbox] {
display: none;
}
input[type=button] {
display: none;
}
.float-left-area {
position: absolute;
width: 20%;
float: left;
background-color: #dddddd;
border: 3px solid black;
height: 99%;
}
.float-right-area {
float: right;
width: 80%;
height: 100%;
}
.inner-left {
font-size: 2em;
}
img.size {
width: 3em;
height: 3em;
}
<div class="float-left-area">
<div class="inner-left">
<label for="picture1"><div id="pic1" style="border: 5px solid black;"><img src="eslcc_logo2.png" alt="eslcc logo" style="float:left;" class="size" /><p align="right">1</p></div></label>
<input id="picture1" type="checkbox" onchange="checkPicture('picture1', true)" onclick="
checkPicture('picture2', false);
checkPicture('picture3', false);
checkPicture('picture4', false);
Border('pic1', 'yellow');
Border('pic2', 'black');
Border('pic3', 'black');
Border('pic4', 'black');" />
<label for="picture2"><div id="pic2" style="border: 5px solid black;"><img src="imac_2.jpg" style="float:left;" class="size" alt="iMac" /><p align="right">5</p></div></label>
<input id="picture2" type="checkbox" onchange="checkPicture('picture2', true)" onclick="
checkPicture('picture1', false);
checkPicture('picture3', false);
checkPicture('picture4', false);
Border('pic2', 'yellow');
Border('pic1', 'black');
Border('pic3', 'black');
Border('pic4', 'black');" />
<label for="picture3"><div id="pic3" style="border: 5px solid black;"><img src="coding_img.png" style="float:left;" class="size" alt="iMac" /><p align="right">10</p></div></label>
<input id="picture3" type="checkbox" onchange="checkPicture('picture3', true)" onclick="
checkPicture('picture1', false);
checkPicture('picture2', false);
checkPicture('picture4', false);
Border('pic3', 'yellow');
Border('pic1', 'black');
Border('pic2', 'black');
Border('pic4', 'black');" />
<label for="picture4"><div id="pic4" style="border: 5px solid black;"><img src="ariane_6.jpg" style="float:left;" class="size" alt="Ariane 6"/><p align="right">20</p></div></label>
<input id="picture4" type="checkbox" onchange="checkPicture('picture4', true)" onclick="
checkPicture('picture1', false);
checkPicture('picture2', false);
checkPicture('picture3', false);
Border('pic4', 'yellow');
Border('pic1', 'black');
Border('pic2', 'black');
Border('pic3', 'black');" />
</div>
</div>
<div class="float-right-area">
<div class="inner-right">
<p align="center">Points: <span id="points">0</span></p>
Also, no jQuery please.
Not sure if this is what you want:
I remove the bulky code in the checkbox input and set different values in the attribute (i.e. value, data-pic), then consolidate all actions in the function addPoint(number).
I have also modified function pointsAmount() by using for loop to get the points of selected picture. And points will only be added when you click on the right side area.
function addPoint(number) {
points = points + number;
document.getElementById('points').innerHTML = points;
}
function checkPicture(x, y) {
document.getElementById(x).checked = y;
}
function Border(x, y) {
document.getElementById(x).style.borderColor = y;
}
function selectPicture(selectedPic) {
var checkboxes = document.getElementsByName('picture');
for (var i = 0; i < checkboxes.length; i++)
{
var id = checkboxes[i].id;
var pic = checkboxes[i].getAttribute('data-pic');
// Default state and style
checkPicture(id, false);
Border(pic, 'black');
if (id == selectedPic.id)
{
checkPicture(id, true);
Border(pic, 'yellow');
}
}
}
function pointsAmount() {
var checkboxes = document.getElementsByName('picture');
for (var i = 0; i < checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
var value = parseInt(checkboxes[i].value);
addPoint(value);
}
}
}
function onPageload() {
checkPicture('picture1', true);
Border('pic1', 'yellow');
}
window.onload = onPageload;
window.onmousedown = function(e) {
if (e.target.className == 'float-right-area') {
pointsAmount();
}
}
var points = 0;
<div class="float-left-area">
<div class="inner-left">
<label for="picture1">
<div id="pic1" style="border: 5px solid black;">
<img src="eslcc_logo2.png" alt="eslcc logo" style="float:left;" class="size">
<p align="right">1</p>
</div>
</label>
<input id="picture1" type="checkbox" name="picture" data-pic="pic1" value="1" onclick="selectPicture(this)">
<label for="picture2">
<div id="pic2" style="border: 5px solid black;">
<img src="imac_2.jpg" style="float:left;" class="size" alt="iMac">
<p align="right">5</p>
</div>
</label>
<input id="picture2" type="checkbox" name="picture" data-pic="pic2" value="5" onclick="selectPicture(this)">
<label for="picture3">
<div id="pic3" style="border: 5px solid black;">
<img src="coding_img.png" style="float:left;" class="size" alt="iMac">
<p align="right">10</p>
</div>
</label>
<input id="picture3" type="checkbox" name="picture" data-pic="pic3" value="10" onclick="selectPicture(this)">
<label for="picture4">
<div id="pic4" style="border: 5px solid black;">
<img src="ariane_6.jpg" style="float:left;" class="size" alt="Ariane 6">
<p align="right">20</p>
</div>
</label>
<input id="picture4" type="checkbox" name="picture" data-pic="pic4" value="20" onclick="selectPicture(this)">
</div>
</div>
<div class="float-right-area">
<div class="inner-right">
<p align="center">Points: <span id="points">0</span></p>
</div>
</div>

How to clone, modify (increment some elements) before appending using jQuery?

I have an element that contains multiple elements inside it, what I need is to clone the element, but on every "new" element, I need to increment an element (the object number -see my script please-)
In the script I'm adding I need (every time I click on the button) to have : Hello#1 (by default it's the first one) but the first click make : Hello#2 (and keep on top Hello#1) second click = Hello#1 Hello#2 Hello#3 ... We need to keep the oldest hellos and show the first one.
var count = 1;
$(".button").click(function(){
count += 1;
num = parseInt($(".object span").text());
$(".object span").text(count);
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
});
.object{
width:100px;
height:20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
You just have to change a little:
var count = 1;
$(".button").click(function() {
count += 1;
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(count); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
and if you want to simplify this more use this:
$(".button").click(function() {
var idx = ++$('.object').length; // check for length and increment it with ++
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(idx); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
Use the following function, this is more modular and you can use it to update the count if you remove one of the elements
function updateCount() {
$(".object").each(function(i,v) {
$(this).find("span").text(i+1);
});
}
$(".button").click(function() {
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
updateCount();
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>

How to revert radio button checked change?

I have a .change() placed for each radio button in table:
for (var i = 0; i < Count; i++) {
$('input[name="Options[' + i + '].Completed"]').change(function () {
var number = $(this).attr("name").match(/\d+/g)[0];
...
some action
...
});
}
What I'm tryin to do is to revert radio botton change in case of some condition.
By default, my radiobutten is marked as false (Yes No, No by default). If I clicked to Yes, but don't mach the condition, I need to stay on No.
I have tried to do this in this way:
if (... condition ...) {
$('input[name="Options[' + i + '].Completed"]').filter('[value=False]').prop('checked', true);
}
But this doesn't seems to work (nothing happened, but condition works fine).
What am I doing wrong and how can I accomplish my goal?
EDIT:
radiobutton html:
<div id="Options_0__Completed-styler" class="jq-radio" unselectable="on" style="-webkit-user-select: none; display: inline-block; position: relative;">
<input id="Options_0__Completed" name="Options[0].Completed" type="radio" value="True" style="position: absolute; z-index: -1; opacity: 0; margin: 0px; padding: 0px;">
<div class="jq-radio__div"></div>
</div>
<div id="Options_0__Completed-styler" class="jq-radio checked" unselectable="on" style="-webkit-user-select: none; display: inline-block; position: relative;">
<input checked="checked" id="Options_0__Completed" name="Options[0].Completed" type="radio" value="False" style="position: absolute; z-index: -1; opacity: 0; margin: 0px; padding: 0px;">
<div class="jq-radio__div"></div>
</div>
The i inside for loop is the shared between all instances of radio buttons. You need to make copy of it for each radio button as follow:
for (var i = 0; i < Count; i++) {
(function (i) {
$('input[name="Options[' + i + '].Completed"]').change(function () {
var number = $(this).attr("name").match(/\d+/g)[0];
if (...condition...) {
$('input[name="Options[' + i + '].Completed"]').filter('[value=False]').prop('checked', true);
}
});
})(i);
}
Also, there is no need to attach event on radio button in for loop individually.
You can use event delegation in jQuery.
$(document / parentSelector).on('change', 'input[name="Options[' + i + '].Completed"]', function () {
// Event handling code here
});
<input type="radio" name="check" value="1"/>
<input type="radio" name="check" value="2"/>
<input type="radio" name="check" value="3"/>
$(document).ready(function(){
$("input[name=check]")
.change(function(e){
if($(e.target).val()=="2"){
$(e.target).prop( "checked", false );
}
});
});
http://jsfiddle.net/aL86u746/

Do something if element has class

Here is what I want to do...First if you click the "All" li box it adds and removes a red border around all the other boxes. Now I want it so that if a box containing a red border is clicked then simply toggle the class .box-border.
<style>
.box { width: 100px; height: 100px; background: beige; }
.box.select-all { background: #333; color: white; }
.box-border { border: 1px solid red; }
ul li {
display: inline;
list-style: none;
float: left;
margin: 0 5px;
text-align: center;
line-height: 100px;
}
</style>
<div class="row">
<div class="large-10 push-2 medium-10 columns">
<ul>
<li class="box box1"></li>
<li class="box box2"></li>
<li class="box box3"></li>
<li class="box box4"></li>
<li class="box box5 select-all">All</li>
</ul>
</div>
</div>
<script>
$(document).ready(function(){
var selectAll = $('.box.select-all');
var boxes = $('.box').not(selectAll);
selectAll.click(function(){
boxes.toggleClass('box-border');
// if (boxes.hasClass('box-border')) {
// console.log('yes');
// }
});
$('ul li').click(function(){
var item = $(this).index();
if (item.hasClass('box-border')) {
console.log('yessssss');
}
});
});
</script>
You need to use $(this).hasClass('box-border')
As per your code, item will be a integer referring to elements index.
var item = $(this).index();
Modified Code:
$('ul li').click(function(){
var item = $(this).index();
if ($(this).hasClass('box-border')) {
console.log('yessssss');
}
});
EDIT
If you want to use toggleClass()
$('ul li').click(function(){
var item = $(this).index();
$(this).toggleClass('box-border');
});
I wrote this (with jQuery) to toggle between two pages upon clicking a button with a class (the class is removed if it is present, and added if it is absent to use the same button (element with the same ID) again),
the order of the method calls and 'innerHTML' property setting does matter in the function (you must make changes to the page(or other changed element) before you make changes to the button (or other event 'triggered' element)), and the order in which you add the 'mPage' class (the triggering class) to the button does not matter.
<script id="toSettings">
const spage = document.getElementById("mContent");
$( "#setsBtn" ).click(function(){
if ($(this).hasClass('mPage')) {
spage.innerHTML = '';
spage.innerHTML = '<br /><div style="width=100%; height=100%; top=0; left=0; background-color: pink;"> <button class="w3-btn w3-amber" onclick="goso()">dest</button><br /> <button class="w3-btn w3-amber">dest</button><br /><button class="w3-btn w3-amber">dest</button> </div>';
this.innerHTML = '<img src="img/leftarrow.svg"/>'
this.classList.remove('mPage');
}
else {
spage.innerHTML='';
spage.innerHTML = '<div style="width: 100%; height: 100%; " id="mContent" class="mContent w3-center"><br /><br /><br /><br /><br /><br /><br /><div id="" class=""><div class="mPageBtn w3-button w3-green" id="ledgerbtn" style="display: block;">Ledger</div><br /></div>';
this.classList.add('mPage');
this.innerHTML = '<img src="img/gear.svg"/>';
}
});
</script>
The 'w3' classes are part of the w3-css library available on w3schools.com .

Categories

Resources