I need to copy a value from a "Div" to an "input" by clicking the button.
the function is copying the whole div html value, contrary to what i need, i want to copy only the text.
view example: https://jsfiddle.net/fg79vypb/
$('#copy').on('click', function() {
$('#message').val($('<div/>').append($('#whatsapp').clone()).html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="copy">Get order on WhatsApp</button>
<div id="whatsapp" style=" position: fixed; width: 200px; height: auto; bottom: 40px; right: 40px; background-color: #e0ffe7; border-radius: 10px; padding-left: 10px; border-top-width: 10px; padding-top: 10px; padding-bottom: 10px;"><span class="simpleCart_total">R$ 18.00</span> (<span class="simpleCart_quantity" id="simpleCart_quantity">1</span> items)
<br><br>
<div class="simpleCart_items"><div class="cartHeaders"><div class="itemName">Name</div><div class="itemPrice">Price</div><div class="itemQuantity">Quantity</div><div class="item"></div></div><div class="itemContainer"><div class="itemName">Product name 1</div><div class="itemPrice">R$ 18.00</div><div class="itemQuantity">1</div><div class="item"> </div></div></div>
<a class="simpleCart_empty" href="javascript:;">clean cart</a>
<br><br>
<a class="simpleCart_checkout" href="javascript:;">go to checkout</a></div>
<input id="message" type="text" >
I would like to get only the text value, and is displaying all html code.
This code will do what you want. Just copy text not html code
$('#copy').on('click', function() {
$('#message').val($('#whatsapp').text());
});
Here is an example of how to capture all item names and their prices and place them into an array using JQuery. You can then decide what you want to do with them from there:
let items = []; //Declare an array which will hold all items selected by user
let valueForTextbox = "";
//Iterate each name and grab it's corresponding price:
$('.itemName').each(function(){
//Check for the header row, so we don't place titles into the array
if($(this).text() !== 'Name'){
items.push({ ItemName: $(this).text(), ItemPrice: $(this).next('.itemPrice').text() });
}
});
//Display each item's name and price
items.forEach(function(item){
//Concat the item names and item prices
valueForTextbox += item.ItemName + " " + item.ItemPrice + " ");
});
//Set the textbox value
$('#message').val(valueForTextbox);
//You can then format each item to whatever you need from here
Related
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>
I have a following <div> structure:
<div class="color-class" data-color="red">
<div class="inside-color">Red</div>
</div>
<div class="color-class" data-color="green">
<div class="inside-color">Green</div>
</div>
<div class="color-class" data-color="blue">
<div class="inside-color">Blue</div>
</div>
So, when people click on any color class then the page is redirected with corresponding color in the url with the following:
var color=urlObj.searchParams.get("color");
$(".color-class").on("click",function(){
if( $(this).find(".inside-color").hasClass("selected")){
location.href=location.href.replace(/&?color=([^&]$|[^&]*)/i, "");
}
else {
var se_val=$(this).data("color");
$(this).find(".inside-color").addClass("selected");
if ( !color ){
if(url.indexOf("?") >= 0){
url =url+"&color="+se_val;
}
else {
url =url+"?color="+se_val;
}
window.location.href=url;
return;
}
if ( color){
urlObj.searchParams.set("color", color+","+se_val);
window.location.href=urlObj;
return;
}
}
});
So using this code i can redirect so after my redirection i get url like example.com/?color=red
Then I have to add class name called selected to the corresponding inside-color.
So I write the following code:
if ( color ){
$(".color-class[data-color='"+color+"']").find(".inside-color").addClass("selected");
}
But if my url is http://www.example.com/?color=red%2Cgreen how i can add selected class to both… ie add selected class to both red and green,
If my url is http://www.example.com/?color=red%2Cgreen and some one again click on green color then how can i remove green from the url and add selected to red color only.
Any Help will be appreciated.
Consider if this was a form, you might have something like:
<form action="example.com" method="get">
<input type="checkbox" class="inside-color" name="inside-color[]" value="red" /><label>Red</label>
<input type="checkbox" class="inside-color" name="inside-color[]" value="green" /><label>Green</label>
<input type="checkbox" class="inside-color" name="inside-color[]" value="blue" /><label>Blue</label>
<button type="submit">Go</button>
</form>
This will create an encoded URL like:
example.com?inside-color%5B%5D=red&inside-color%5B%5D=green
This is the method for passing an Array via GET. one option would be to pass the details in this method and parse it. Doing this will result in a small array and you can then iterate the array set selected on each of the specific colors.
In your example, you are passing a single string in one variable, and using a delimiter. Sp you'd need to first get the string and then split it. Again, this will result in an array that can be iterated.
if the user unchecked one of the options, removing selected, you could then remove that element from the array.
My suggestions:
function setSelections(c) {
$.each(c, function(k, v) {
if (v) {
$(".color-class[data-color=" + k + "]").addClass("selected");
}
});
}
$(function() {
var colors = {
red: 0,
green: 0,
blue: 0
};
$(".color-class").click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
colors[$(this).attr("data-color")] = 0;
} else {
$(this).addClass("selected");
colors[$(this).attr("data-color")] = 1;
}
});
$("#save-selection").click(function(e) {
e.preventDefault();
var url = "http://example.com/?" + $.param(colors);
console.log("URL: " + url);
})
});
.color-class {
width: 40px;
height: 40px;
border: 2px solid #ccc;
border-radius: 4px;
margin: 2px;
}
.color-class:hover {
border-color: #a0a0a0;
}
.color-class.selected {
border-color: #202020;
}
.color-class .inside-color {
border-radius: 3px;
width: 100%;
height: 70%;
color: white;
font-size: 75%;
text-align: center;
padding-top: 30%;
}
.color-class .inside-color.red {
background: red;
}
.color-class .inside-color.green {
background: green;
}
.color-class .inside-color.blue {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-class" data-color="red">
<div class="inside-color red">Red</div>
</div>
<div class="color-class" data-color="green">
<div class="inside-color green">Green</div>
</div>
<div class="color-class" data-color="blue">
<div class="inside-color blue">Blue</div>
</div>
<button id="save-selection">Save</button>
The console shows: URL: http://example.com/?red=1&green=1&blue=0 This will be easier to parse back into an object that can be used with setSelections() function.
Hope that helps.
ok try something like this i am just posting some part of your code
var color=urlObj.searchParams.get("color");
if ( color ){
var splitColors = color.split('%2C');
for(var i=0;i<splitColors.length;++i)
{
$(".color-class[data-color='"+splitColors[i]+"']").find(".inside-color").toggleClass("selected");
}
}
I have an HTML document. There are 2 fields:
First one is an hidden input field (with a pre selected value)
The other is an empty text input field. It displays the current value of the first one with jQuery.
Between that 2 fields, I have 9 buttons with different texts inside them.
With jQuery, when I click on a button it add his text in the visible field (separated by a coma) and it adds to himself an enabled class. This works.
When I click on the same button, the class is removed (this works).
What is not working:
I would like at the same time it removes his name from the field (with a coma) I With jQuery / JavaScript I have tried to convert with split() each name in the field (coma separated) to an array, to easily delete one of them when needed with splice().
What I haven done yet:
I need to convert-it back to a coma separated string, replacing the existing string value in the field ( I haven done this yet). I am not far.
My code on JS Fiddle
How can I achieve this?
My code in here:
jQuery(document).ready(function($){
if ($('.subscribe-text').val() == ''){
$('.subscribe-text').val($('.subscribe-text-get').val()+',')
}
$('.subscribe-button').click(function(){
if(!$(this).hasClass('enable'))
{
$('.subscribe-text').val($('.subscribe-text').val()+$(this).html()+',');
$(this).addClass('enable');
}
else if($(this).hasClass('enable'))
//
// I would like to remove the name in the field
// when a button is clicked and has 'enable' class
//
{
var myArray = new Array();
var myString = $('.subscribe-text').val();
myArray = myString.split(",");
var myItem = $(this).html()+' ';
var indexPos = myArray.indexOf(myItem);
if(indexPos != -1)
{
myArray = myArray.splice(indexPos, 1);
}
$('.subscribe-text').val(myArray);
$(this).removeClass('enable');
}
});
});
.subscribe-button {
background-color:#ddd
}
#buttons_x3 {
width:500px;
}
.subscribe-text {
width:100%;
font-size:9px;
}
.subscribe-button {
display: inline-block;
text-align:center;
padding:3px;
margin-bottom: 10px;
color: black;
height:20px;
width:100px;
margin:10px 20px 10px;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="my_custom_checkout_field">
<input type="hidden" class="subscribe-text-get" name="my_field_name" value="woo-multi-1">
</div>
<br>
<div id="buttons_x3">
<a class="subscribe-button">woo-single-1</a>
<a class="subscribe-button">woo-single-2</a>
<a class="subscribe-button">woo-single-3</a>
<a class="subscribe-button">woo-multi-1</a>
<a class="subscribe-button">woo-multi-2</a>
<a class="subscribe-button">woo-top-1</a>
<a class="subscribe-button">woo-top-2</a>
<a class="subscribe-button">woo-top-3</a>
<a class="subscribe-button">woo-special</a>
</div>
<br>
<div id="my_custom_checkout_field">
<input type="text" class="subscribe-text" name="my_field_name" value>
Be careful of a few things here:
1) Every time you click a button you are creating a new array with one long string inside.
2) Splice returns the value of the removed item, so each time a button is clicked you are setting the array string to be the item that you just removed.
Instead, initialize the array outside of your click function, and add each new item to the end. Set the value of the input with the toString() method. This will preserve the array of remaining values and their order.
jQuery(document).ready(function($){
var myArray = [];
if ($('.subscribe-text').val() == ''){
myArray[0] = $('.subscribe-text-get').val();
$('.subscribe-text').val( myArray.toString() );
}
var $item, length;
$('.subscribe-button').click(function(){
length = myArray.length;
if(!$(this).hasClass('enable')) {
$item = $(this).html();
myArray[length] = $item;
$('.subscribe-text').val( myArray.toString() );
$(this).addClass('enable');
}
else if($(this).hasClass('enable')) {
var myItem = $(this).html();
var indexPos = myArray.indexOf(myItem);
if(indexPos != -1) {
myArray.splice(indexPos, 1);
}
$('.subscribe-text').val( myArray.toString() );
$(this).removeClass('enable');
}
});
});
.subscribe-button {
background-color:#ddd
}
#buttons_x3 {
width:500px;
}
.subscribe-text {
width:100%;
font-size:9px;
}
.subscribe-button {
display: inline-block;
text-align:center;
padding:3px;
margin-bottom: 10px;
color: black;
height:20px;
width:100px;
margin:10px 20px 10px;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="my_custom_checkout_field">
<input type="hidden" class="subscribe-text-get" name="my_field_name" value="woo-multi-1">
</div>
<br>
<div id="buttons_x3">
<a class="subscribe-button">woo-single-1</a>
<a class="subscribe-button">woo-single-2</a>
<a class="subscribe-button">woo-single-3</a>
<a class="subscribe-button enable">woo-multi-1</a>
<a class="subscribe-button">woo-multi-2</a>
<a class="subscribe-button">woo-top-1</a>
<a class="subscribe-button">woo-top-2</a>
<a class="subscribe-button">woo-top-3</a>
<a class="subscribe-button">woo-special</a>
</div>
<br>
<div id="my_custom_checkout_field">
<input type="text" class="subscribe-text" name="my_field_name" value>
Here is my code on a jsFiddle
I have created a modal with checkboxes that when checked, are added to the DOM. The issues that I am having that I have been trying to troubleshoot for days are that whether the checkboxes are checked or unchecked, the tag is added to the DOM, not just when checked.
I also cannot figure out how to remove the tag from the DOM when the associated checkbox is unchecked. I have the amount of checkboxes that are able to be checked max out at 6, which is what I am looking to have, but is there a way to max the amount of child divs within a parent div there could be? That way theres another safeguard to fall back on so that no more than 6 tags can be selected at one time?
Here is a jsfiddle http://jsfiddle.net/co5w7c9j/ with what I have, hopefully I explained enough without making it sound too confusing.
Below is my jquery that I have written thus far, I think I am missing a step somewhere to achieve what I am looking for.
Thank you for taking the time to look through my code.
// When specilaty is checked, add tag to profile page
$('[name=specialty]').click(function() {
$newTag = $("<div class='specTag'>" + $(this).attr('value') + "<div class='xOut'>x</div></div>");
$(this).attr('value');
$('.Specialties').append($newTag);
/* if ($('.Specialties > .specTag').has(('[name=specialty]:checked').attr('value'))) {
$('.Specialties > .specTag').has((this).txt()).remove();
} */
// Count number of checkboxes selected and display in modal
var increment = 0;
$('[name=specialty]:checked').each(function() {
if (this.checked) {
increment++;
} else {
increment--;
}
$('#specCount').html(increment);
});
// Disable checkboxes when 6 (maximum) are selected
$("input[type=checkbox][name=specialty]").click(function() {
var bol = $("input[type=checkbox][name=specialty]:checked").length >= 6;
$("input[type=checkbox][name=specialty]").not(":checked").attr("disabled", bol);
});
// Create array of checked items - add on checked - remove on uncheck
specialtyArray = $('[name=specialty]:checked').map(function() {
return $(this).val();
// if item is in the array, then remove it from the DOM
if (jQuery.inArray($('[name=specialty]:checked').val(), specialtyArray) > -1) {}
});
console.log(specialtyArray.get());
});
// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function() {
$('.modal-body > #updateSpecForm > .columns').children().removeAttr('checked');
$('#specCount').html(0);
})
// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function() {
$(this).parent().fadeOut('slow');
$(this).parent().remove();
});
Try
// When specilaty is checked, add tag to profile page
$('input[name=specialty]').change(function() {
var value = this.value;
//if checked add a new item else remove item.
if (this.checked) {
var $newTag = $("<div class='specTag'>" + value + "<div class='xOut'>x</div></div>").attr('data-id', value);
$('.Specialties').append($newTag);
} else {
//use the attribute value which is the same as the input value to find out the item to be removed
$('.Specialties').find('div.specTag[data-id="' + value + '"]').remove()
}
//cache the result since it is used multiple times
var $checked = $('input[name=specialty]:checked');
// Count number of checkboxes selected and display in modal
var increment = $checked.length;
$('#specCount').html(increment);
// Disable checkboxes when 6 (maximum) are selected
var bol = increment.length >= 6;
//use prop instead of attr to set the disabled state
$("input[type=checkbox][name=specialty]").not(":checked").prop("disabled", bol);
// Create array of checked items - add on checked - remove on uncheck
var specialtyArray = $checked.map(function() {
return $(this).val();
});
console.log(specialtyArray.get());
});
// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function() {
$('.modal-body > #updateSpecForm > .columns').children().prop('checked', false);
$('#specCount').html(0);
})
// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function() {
$(this).parent().fadeOut('slow', function() {
$(this).remove();
});
//uncheck the corresponding checkbox
$('input[name=specialty][value="' + $(this).closest('.specTag').attr('data-id') + '"]').prop('checked', false)
});
.Specialties {
background-color: #FFFFFF;
width: 350px;
height: 135px;
margin-left: 249px;
margin-top: 125px;
top: 0;
position: absolute;
z-index: 1;
}
.specTag {
background-color: #51b848;
color: #FFFFFF;
font-weight: 200;
letter-spacing: 1px;
font-size: 12px;
width: 150px;
height 30px;
padding: 8px;
position: relative;
margin-left: 10px;
margin-bottom: 5px;
border-radius: 5px;
display: inline-block;
}
.xOut {
background-color: #FFFFFF;
width: 25px;
padding: 3px;
position: absolute;
right: 5px;
text-align: center;
color: #333333;
top: 5px;
border-radius: 0 3px 3px 0;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="GET" id="updateSpecForm">
<!-- ATHLETIC TRAINER OPTIONS -->
<div class="columns" id="athleticTrainer">
<input type="checkbox" name="specialty" value="Boot Camp" />Boot Camp
<br />
<input type="checkbox" name="specialty" value="Children's Fitness" />Children's Fitness
<br />
<input type="checkbox" name="specialty" value="Circuit Training" />Circuit Training
<br />
<input type="checkbox" name="specialty" value="Core Training" />Core Training
<br />
<input type="checkbox" name="specialty" value="Cycling/Spinning" />Cycling/Spinning
<br />
<input type="checkbox" name="specialty" value="Dance" />Dance
<br />
<input type="checkbox" name="specialty" value="Flexibility/Balance" />Flexibility/Balance
<br />
<input type="checkbox" name="specialty" value="Meal Planning" />Meal Planning
<br />
<input type="checkbox" name="specialty" value="Men's Fitness" />Men's Fitness
<br />
<input type="checkbox" name="specialty" value="Women's Fitness" />Women's Fitness
<br />
</div>
<div class="Specialties">
<!-- SHOW BELOW DIV ONLY IF LOGGED IN -->
<!-- <div class="updateOn">+ Update My Specialties</div> -->
<!-- ***PRO CAN ADD UP TO 6 SPECIALY TAGS*** -->
</div>
</form>
Sometimes it's easier to compartmentalize code by setting parts of it into functions so that conditional aspects are easier to read through .
The biggest issue in your code was not testing if checkboxes were checked or not in the click handler.
Since the checkbox needs to do the same as the click on new tag does when it is unchecked, all logic flows through the change event of checkbox. Note that the click handler on X of tag triggers the change also
var maxChecked = 6;
// use change handler on checkboxes, will get triggered also below in another click handler
var $checkboxes = $('[name=specialty]').change(function() {
var value = $(this).val();
if(this.checked ){
addTag( value);
}else{
removeTag( value );
}
checkBoxStatus();
});
function removeTag(checkBoxValue){
/* we stored the checkbox value as data attribute, use that to filter*/
$('.specTag').filter(function(){
return $(this).data('value') === checkBoxValue;
}).slideUp(function(){
$(this).remove();
})
}
function addTag( checkBoxValue){
$newTag = $("<div class='specTag'>" + checkBoxValue + "<div class='xOut'>x</div></div>");
/* store the value in elment data so we can reference back to checkbox */
$newTag.data('value', checkBoxValue);
$('.Specialties').append($newTag);
}
/* use this to both disable and enable checkboxes */
function checkBoxStatus(){
var limitReached = $checkboxes.filter(':checked').length === maxChecked;
$checkboxes.not(':checked').prop('disabled',limitReached);
}
$(document.body).on('click', '.xOut', function () {
var $element = $(this).parent(),
$checkbox = $checkboxes.filter(function(){
return this.value === $element.data('value');
/* trigger change to remove element and reset disabled checkboxes */
}).prop('checked',false).change();
});
DEMO
Working fiddle:
http://jsfiddle.net/co5w7c9j/1/
// When specilaty is checked, add tag to profile page
$('[name=specialty]').click(function() {
$newTag = $("<div class='specTag'>" + $(this).attr('value') + "<div class='xOut'>x</div></div>");
$(this).attr('value');
$('.Specialties').append($newTag);
EnableDisableCheck();
// Create array of checked items - add on checked - remove on uncheck
specialtyArray = $('[name=specialty]:checked').map(function(){
return $(this).val();
// if item is in the array, then remove it from the DOM
if (jQuery.inArray($('[name=specialty]:checked').val(), specialtyArray) > -1) {
}
});
console.log(specialtyArray.get());
});
// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function () {
$('.modal-body > #updateSpecForm > .columns').children().removeAttr('checked');
$('#specCount').html(0);
})
// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function () {
$(this).parent().fadeOut('slow');
$(this).parent().remove();
var text = $(this).parent().text();
$('[name=specialty]:checked').filter(function () {
return text.indexOf($(this).val()) > - 1;
}).removeAttr('checked');
EnableDisableCheck();
});
function EnableDisableCheck(){
if($('[name=specialty]:checked').length >=5)
{
$('[name=specialty]').attr("disabled","disabled");
}
else
{
$('[name=specialty]').removeAttr("disabled");
}
}
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 .