Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to let the star colored when I click on it , but because I have both of Javascript and HTML file in separate folder , how can I revert the function in javascript to the html file?
Fiddle
HTML
<input type="hidden" name="rating" id="rating" />
<ul>
<li id="fav">★</li>
</ul>
Javascript
function addRating(obj) {
$('li').each(function(index) {
$(this).toggleClass('selected');
$('#rating').val((index+1));
if(index == $("li").index(obj)) {
return false;
}
});
}
$("#fav").click(function(){
addRating(obj);
});
Css
li{float:left; margin-left:9px;display: inline-block;color: #F0F0F0;text-shadow: 0 0 1px #666666;font-size:30px;}
.highlight, .selected {color:#F4B30A;text-shadow: 0 0 1px #F48F0A;}
Just pass this to the addRating it holds the context of the owner object.
function addRating(obj) {
$('li').each(function(index) {
$(this).toggleClass('selected');
$('#rating').val((index + 1));
if (index == $("li").index(obj)) {
return false;
}
});
}
$("#fav").on('click',function() {
addRating(this);
});
li {
float: left;
margin-left: 9px;
display: inline-block;
color: #F0F0F0;
text-shadow: 0 0 1px #666666;
font-size: 30px;
}
.highlight,
.selected {
color: #F4B30A;
text-shadow: 0 0 1px #F48F0A;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="rating" id="rating" />
<ul>
<li id="fav">★</li>
</ul>
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How to display pop-window with aggregated data when Double-click event in jQuery?I use below code to get aggregated data, each quessionId has many related reasons. when I click/choose questionId button/event, OnClick select questionId and Double-click to remove/cancel, when OnClick select a questionId, related reasons dictonary will display below questionId, if Double-click remove that questionId, and related reasons dictonary will display in a `pop-windows' as below picture(User can click 'Confirmed' button after 5
seconds, when confimed, closed pop-windows automatically).
Below is my partial code of .js code in jQuery, all related data is fine by below code:
function fmtQuestionsByID(id,callback){
if(!DATA.questions[id] || !$('#card_'+id) )return;
var project = DATA.projects[DATA.questions[id].projectId];
if(!project)return;
var issueQuestionLists = DATA.alltags.reduce(function(a,b){
if(a[b['quessionId']]) {
a[b['quessionId']].push({name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']})
} else{
a[b['quessionId']] = [{name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']}]
}
return a;
},{});
var d = 0;
for(var i=0;i < DATA.questions[id].tags.length;i++){
var lid = DATA.questions[id].tags[i];
for(var l in issueQuestionLists){
var lb = issueQuestionLists[l]
for(var c=0;c< lb.length;c++){
var lc = lb[c];
if(lc._id == lid){
d++;
var info = lc;
console.log('info', info);
$('.tags_question').append(d + '['+info.name+']' + info.description + '。' + 'Reason: '+info.reason+ '。' ||'[no data]' );
}
}
}
}
}
Below code to OnClick to select and Double-click to remove.
function _fmtQuetionTags(){
fmtUsers( DATA.lastShowID ,function(html){
html = '<span class="add_plus_pic question projectinfo_addquestion" title="" href="#" aria-label=""><i class="fa fa-plus"></i></span>' + html;
$('#projectinfoUsers').html( html );
$('#projectinfoUsers .js-question').attr('title','Double-click remove question').unbind().on('dblclick',function(){
var id = $(this).data('id');
doSubmitSetQuestion(DATA.questionid,DATA.lastID,id,function () {
});
});
});
}
And I use below html to get above data
<div id="questioninfo">
<span class="tags_question"></span>
</div>
Based on your description, I created the following example code.
$(function() {
$("#showAlert").click(function() {
$(".alert.dialog").show("fast", function() {
setTimeout(function() {
$(".alert.dialog button[disabled]").prop("disabled", false);
}, 5000);
});
});
$(".ok.btn").click(function() {
$(this).closest(".dialog").hide("fast", function() {
$(".ok", this).prop("disabled", true);
});
});
$(".dialog li").click(function() {
$(this).removeClass("marked").addClass("selected");
}).dblclick(function() {
$(this).removeClass("selected").addClass("marked");
})
});
.alert {
width: 340px;
border: 1px solid #ccc;
border-radius: 6px;
padding: 0;
display: none;
}
.title {
width: 100%;
background: #eee;
text-align: center;
font-weight: bold;
border-bottom: 1px solid #ccc;
padding-top: 6px;
padding-bottom: 6px;
}
.response {
width: 95%;
margin-top: 10px;
padding-left: 6px;
}
.button-set {
width: 100%;
margin: 5px;
text-align: center;
}
.button-set .default {
font-weight: bold;
}
.selected {
background-color: #FF0;
}
.marked {
background-color: #F00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="showAlert">Alert</button>
<div class="alert dialog">
<div class="title">Alert 1</div>
<div class="response">This is an alert description
<ul>
<li>Option 1</li>
</ul>
</div>
<div class="button-set">
<button class="ok btn default" disabled="disabled">Okay</button>
</div>
</div>
Hopefully this is similar to what you're doing and what type of functions you're trying to achieve. This example makes use of various methods, .click() and .dblclick(). It also uses setTimeout() in the callback for .show().
See More:
https://api.jquery.com/click/
https://api.jquery.com/dblclick/
https://api.jquery.com/show/
https://api.jquery.com/hide/
https://www.w3schools.com/jsref/met_win_settimeout.asp
I have searched high and low for a solution and could not find one. It may be because I'm searching in a wrong way but anyway, I can't solve the issue I'm having without any help from the outside.
First a bit of background:
I have an embedded form of the MA platform we are using. Since the adjustments one can make visually on these forms are very limited, I decided to hide the checkboxes on it and create my own. When checking those checkboxes the corresponding ones on the embedded form have to be checked as well.
I also have a checkbox which checks all checkboxes in a list.
Now the issue is, when I check any checkbox that isn't the check-all-checkbox the corresponding boxes on the embedded form do not respond. Whenever I check the check-all checkbox, they do.
I'm getting an unknown error in the snippet generator, which I have never noticed before.
I provided the relevant code in a snippet and added comments where I think stuff is going wrong.
var clickedBox = "default";
$(".checkall").click(function() {
clickedBox = this.id;
// This next block seems to be an issue
// This is the block that selects all checkboxes when the #checkall one is checked.
// Normally I have multiple of these lists on the page
$("#" + clickedBox).change(function () {
$("." + clickedBox + " input:checkbox").prop("checked", $(this).prop("checked"));
$("." + clickedBox + " input:checkbox").val(parseInt($("." + clickedBox + " input:checkbox").val()) + parseInt(1)).trigger("change");
});
// This one does something weird as well, on unchecking it multiplies but I can find a solution for this by myself
$("." + clickedBox + " input:checkbox").change(function () {
if ( $("." + clickedBox + " input:checkbox:not(:checked)").length != 0 ) {
$("#" + clickedBox).prop("checked", false);
console.log("unchecked a checkbox");
}
else if ( $("." + clickedBox + " input:checkbox:not(:checked)").length == 0 ) {
$("#" + clickedBox).prop("checked", true);
console.log("checked a checkbox");
}
});
$(".one").change(function () {
$("#correspondingOne").prop("checked", $(this).prop("checked"));
});
$(".two").change(function () {
$("#correspondingTwo").prop("checked", $(this).prop("checked"));
});
$(".three").change(function () {
$("#correspondingThree").prop("checked", $(this).prop("checked"));
});
$(".four").change(function () {
$("#correspondingFour").prop("checked", $(this).prop("checked"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<label>
<input class="checkall" type="checkbox" id="checkall" />
<strong><h3>Dropdown list of checkboxes</h3></strong>
</label>
</div>
<div class="checkall checkboxes">
<p><label><input type="checkbox" class="one" /> one </label></p>
<p><label><input type="checkbox" class="two"/> two </label></p>
<p><label><input type="checkbox" class="three" /> three </label></p>
<p><label><input type="checkbox" class="four" /> four </label></p>
</div>
</div>
Let's regard this one as the MA Form
<br><br>
<form>
<label><input type="checkbox" id="correspondingOne" /> correspondingOne </label>
<label><input type="checkbox" id="correspondingTwo" /> correspondingTwo </label>
<label><input type="checkbox" id="correspondingThree" /> correspondingThree </label>
<label><input type="checkbox" id="correspondingFour" /> correspondingFour </label>
</form>
Anyone that can give me a hand or at least give me a push in the right direction? Would be highly appreciated!
Thanks!
Tom
The issue in the code that I posted is the fact that the change functions (below is an example)
$(".one").change(function () {
$("#correspondingOne").prop("checked", $(this).prop("checked"));
});
are included in the $(".checkall").click function. Which means they only get activated after the item with class="checkall" has been clicked.
Moving them outside solves this issue.
I don't recommend using this solution as simply creating new labels for the checkboxes is a much simpler solution as you don't have to parse change triggers and connect one checkbox to another, but it might be interesting to check out the trigger behaviour.
Check All Checkbox
HTML
<label>/<input> Pairs
<label> attribute [for] set to the value of a form control's #ID establishes an association between them. When the <label> is clicked, the associated <input> is triggered by that click event as well.
<label for="ID"></label>// Click label...
<input id="ID" type="checkbox">// ...checkbox will become un/checked
CSS
Pseudo-elements
Each checkbox is hidden and placed at the top of the page. Each <label> that's paired to a checkbox has a ::before pseudo-element in place of the associated checkbox.
General/Adjacent Sibling Combinators and :checked Pseudo-class
There are 2 states to each checkbox: checked = true/false. The checkboxes can influence the styles of all preceding sibling elements and their descendants with and without the :checked pseudo-class. To narrow this down, general and adjacent sibling combinators (~ and + respectively) allow a selector to take a specific path. The example below declares 2 states for a <label>:
Default (adjacent sibling combinator: +)
input + fieldset label {color:black}
Active (adjacent sibling combinator: +)
input:checked + fieldset label {color:red}
🢁
When an <input> is :checked and if the next element is a <fieldset> that has nested <label>(s), then change the <label>'s text color: to red.
Replace the adjacent combinator (+) with a general combinator (~), and the declaration would be:
Active (general sibling combinator: ~)
input:checked ~ fieldset label {color:red}
🢁
When an <input> is :checked and if any sibling thereafter is a <fieldset> that has nested <label>(s), then change the <label>'s text color: to red.
JavaScript
No jQuery was used only plain JavaScript of which was not complex to warrant anything worth mentioning. There is a step-by-step description commented within the Demo if you want to review the function. Although it didn't play a big part in the Demo. HTMLFormControlsCollection API was used.
Demo
// See HTMLFormControlsCollection in post
// Reference the form tag
var card = document.forms.card;
// Reference all form controls of form tag
var ui = card.elements;
// Register the ALL checkbox (input#c0) to the change event
ui.c0.addEventListener('change', chxAll);
// Callback function passes Event Object
function chxAll(e) {
// Declare increment counter outside of loop
var c = 1;
// Ternary checks to see if input#c0 is checked
var all = e.target.checked ? true : false;
// Loop thruogh the next 4 inputs...
for (c; c < 5; c++) {
// Check/uncheck each checkbox in ui HTMLCollection
ui[c].checked = all;
}
// Open the details tag (optional)
document.querySelector('.options').open = true;
}
html,
body {
font: 400 16px/1.2 Consolas;
font-variant: small-caps;
width: 100%;
height: 100%;
}
.chx {
display: none
}
.lab {
display: inline-block;
margin: 10px;
cursor: pointer;
}
.lab::before {
content: '\1f518';
box-shadow: 0px 1.5px 1px 2.5px rgba(51, 51, 51, 0.3);
border-radius: 50%;
}
#c1:checked~.header .options .c1::before,
#c2:checked~.header .options .c2::before,
#c3:checked~.header .options .c3::before,
#c4:checked~.header .options .c4::before {
content: '\1f535';
box-shadow: 0px 1.5px 1px 2.5px rgba(15, 102, 241, 0.5);
}
#c0:checked~.header .c0::before,
#c0:checked+#c1:checked~.header .options .c1::before,
#c0:checked~#c2:checked~.header .options .c2::before,
#c0:checked~#c3:checked~.header .options .c3::before,
#c0:checked~#c4:checked~.header .options .c4::before {
content: '\1f534';
box-shadow: 0px 1.5px 1px 2.5px rgba(241, 102, 15, 0.5);
}
#c1:checked+#c2:checked+#c3:checked+#c4:checked+.header .c0::after {
content: ' Selected';
color: rgba(15, 102, 241, 1);
text-shadow: 1.5px 2px 1.75px rgba(15, 102, 241, 0.7);
}
#c0:checked+#c1:checked+#c2:checked+#c3:checked+#c4:checked+.header.header .c0::after {
content: ' Selected';
color: rgba(241, 102, 15, 1);
text-shadow: 1.5px 2px 1.75px rgba(241, 102, 15, 0.7);
}
#c1:not(:checked)~.header .c0::after,
#c2:not(:checked)~.header .c0::after,
#c3:not(:checked)~.header .c0::after,
#c4:not(:checked)~.header .c0::after {
content: '';
}
#c1:not(:checked)~.header .c0::before,
#c2:not(:checked)~.header .c0::before,
#c3:not(:checked)~.header .c0::before,
#c4:not(:checked)~.header .c0::before {
content: '\1f518';
box-shadow: 0px 1.5px 1px 2.5px rgba(51, 51, 51, 0.3);
}
.header {
border: 3px inset rgba(51, 51, 51, 0.51);
border-radius: 5px;
-webkit-padding-before: 0.0em;
-webkit-padding-start: 0.15em;
-webkit-padding-end: 0.15em;
-webkit-padding-after: 0.15em;
box-shadow: 0px 1.5px 1px 2.5px rgba(51, 51, 51, 0.3);
width: 380px;
}
legend {
height: 35px
}
legend h3 {
font-size: 1.55rem;
line-height: 2;
transform: translateY(-35px);
}
.options {
background: rgba(3, 9, 27, 0.1);
border: 3px inset rgba(51, 51, 51, 0.15);
border-radius: 5px;
box-shadow: 0px -2px -1px 0px rgba(51, 51, 51, 0.15);
}
summary {
padding: 3px 5px;
font-size: 1.2rem;
cursor: pointer;
}
<form id='card'>
<input type="checkbox" class="chx" id="c0" />
<input type="checkbox" class="chx" id='c1' />
<input type="checkbox" class="chx" id='c2' />
<input type="checkbox" class="chx" id='c3' />
<input type="checkbox" class="chx" id='c4' />
<fieldset class='header' name="header">
<legend>
<h3>List of Checkboxes</h3>
</legend>
<label for='c0' class='c0 lab'> All Options</label>
<details class="options">
<summary>Select Options</summary>
<label for='c1' class='c1 lab'> One </label>
<label for='c2' class='c2 lab'> Two </label>
<label for='c3' class='c3 lab'> Three </label>
<label for='c4' class='c4 lab'> Four </label>
</details>
</fieldset>
</form>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I would like to make a basic shopping cart app in which you can click on items, every click should add the item to an array. At the end you should be able to press a total button and see all the items you have added, but so far it's not working.
Code so far:
function add() {
var shoppingCart = [];
document.getElementById("itemOne").addEventListener("click", function() {
shoppingCart.push("One");
});
document.getElementById("itemTwo").addEventListener("click", function() {
shoppingCart.push("Two")
});
document.getElementById("total").addEvenetListener("click", function() {
document.getElementById("display").innerHTML =
shoppingCart;
})
}
Jsfiddle: https://jsfiddle.net/xpb8oarx/
Typo # addEventListener
Never called add() you do not need that anyways
var shoppingCart = [];
document.getElementById("itemOne").addEventListener("click", function() {
shoppingCart.push("One");
});
document.getElementById("itemTwo").addEventListener("click", function() {
shoppingCart.push("Two");
});
document.getElementById("total").addEventListener("click", function() {
document.getElementById("display").innerHTML = shoppingCart;
});
.container {
width: 70%;
background-color: black;
height: 300px;
margin: 0 auto;
}
#itemOne,
#itemTwo {
width: 100px;
height: 100px;
border: 1px solid white;
margin: 1%;
color: white;
}
#display {
color: white;
text-align: center;
}
<div class="container">
<div id="itemOne" class="itemOne">
<button class=" item">Chicken</button>
</div>
<div id="itemTwo">
<button class="item">Veggies</button>
</div>
<button id="total">Total</button>
<h1 id="display"></h1>
</div>
You'll find a tutorial HERE which explain how to implement a cart in pure HTML5 and Vanilla.
Tuto written by a french JS ninja
I'm making a tag box similar to that of StackOverflow. I see that this question has already been asked here (How to make a "tags box" using jQuery (with text input field + tags separated by comma)) but I'm having a question with regards to the Javascript.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tag-container' id = "tag-container">
<span class='dashfolio-tag'>Tag1</span>
<span class='dashfolio-tag'>Tag2</span>
<span class='dashfolio-tag'>Tag3</span>
</div>
<input type="text" value="" placeholder="Add a tag" id = "add-tag-input" />
CSS:
.tag-container {
max-width: 300px; /* helps wrap the tags in a specific width */
}
.dashfolio-tag {
cursor:pointer;
background-color: blue;
padding: 5px 10px 5px 10px;
display: inline-block;
margin-top: 3px; /*incase tags go in next line, will space */
color:#fff;
background:#789;
padding-right: 20px; /* adds space inside the tags for the 'x' button */
}
.dashfolio-tag:hover{
opacity:0.7;
}
.dashfolio-tag:after {
position:absolute;
content:"×";
padding:2px 2px;
margin-left:2px;
font-size:11px;
}
#add-tag-input {
background:#eee;
border:0;
margin:6px 6px 6px 0px ; /* t r b l */
padding:5px;
width:auto;
}
JS:
$(document).ready(function(){
$(function(){
$("#add-tag-input").on({
focusout : function() {
var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig,''); // allowed characters
if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});
this.value = "";
},
keyup : function(ev) {
// if: comma|enter (delimit more keyCodes with | pipe)
if(/(188|13)/.test(ev.which)) $(this).focusout();
}
});
$('.tag-container').on('click', 'span', function() {
if(confirm("Remove "+ $(this).text() +"?")) $(this).remove();
});
});
});
My question is pretty simple, how do I add the new input as a span with class dashfolio-tag inside the #tag-container? I dabbled with the insertBefore property trying to add it to the right node, but to no avail. Thanks in advance guys!
Change this line of code,
if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});
to
if(txt) {
$("<span/>", {
text:txt.toLowerCase(),
appendTo:"#tag-container",
class:"dashfolio-tag"
});
}
See the demo: https://jsfiddle.net/2gvdsvos/4/
To fix the margins in between tags,
Update HTML to,
<div>
<div class="tag-container" id="tag-container">
<span class='dashfolio-tag'>tag1</span>
<span class='dashfolio-tag'>tag2</span>
<span class='dashfolio-tag'>tag3</span>
</div>
</div>
<div>
<input type="text" value="" placeholder="Add a tag" id="add-tag-input" />
</div>
And add this to CSS,
.tag-container:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
.dashfolio-tag {
...
margin-right: 4px;
float: left;
}
Hope this helps! ;)
https://jsfiddle.net/2gvdsvos/5/
I want to change the background color of the button based upon the class. Why it is not going back after second click?
var $begin1 = $(".begin1").click(function(e) {
e.preventDefault();
var buttonState = $(this).attr("class");
if (buttonState != 'pressed') {
$begin1.removeClass('pressed');
$(this).addClass('pressed');
} else {
$(this).removeClass('pressed');
$(this).addClass('unpressed');
}
});
li {
list-style-type: none;
}
.begin1.unpressed,
.begin2.unpressed {
background-color: white;
color: black;
border: 2px solid #4CAF50;
margin: 0 0 10px 0;
}
li.begin1.pressed,
li.begin2.pressed {
background: #4CAF50;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<li class="begin1 unpressed">
<h2>Button</h2>
</li>
https://jsfiddle.net/nrebaL00/
You can simplify your code greatly. Apply the default styling from the beginning and you don't need an .unpressed class.
The issue with using .attr( 'class' ) is that it will retrieve all the classes applied to the element as a string. Performing a check like if ( 'a' === $el.attr( 'class' ) ) won't work where $el is <li class="a b c"> as $el.attr( 'class' ) would return 'a b c' and not 'a'. Which is why your check was failing after the first click. This kind of check would be good for .hasClass().
e.prevendDefault() is not required for an <li>, so remove that.
Note: the selector I used for jQuery is pretty generic. You may need to increase it's specificity if there are other <li> on the page that don't require the functionality. Something along the lines of adding a class to the <ul> and using that as the part of the jQuery selector. i.e. <ul class="clicky-mcclickens"> and $( '.clicky-mcclickens li' ).
$('li').on('click', function(e) {
$(this).toggleClass('pressed');
});
li {
list-style-type: none;
background-color: white;
color: black;
border: 2px solid #4CAF50;
margin: 0 0 10px 0;
}
.pressed {
background: #4CAF50;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<h2>Button 1</h2>
</li>
<li>
<h2>Button 2</h2>
</li>
</ul>
Sometimes you need more control than simply adding/removing a class when an element is clicked. In those instances you can use .hasClass() to check if the element has the class in question and apply the appropriate action.
Your code is much more complex than it needs to be; you can just call toggleClass() like this:
var $begin1 = $(".begin1").click(function() {
$(this).toggleClass('pressed unpressed');
});
Updated fiddle
Note that e.preventDefault() is redundant for an li element as it has no default behaviour to prevent.
I would use toggleClass instead of adding and removing manually. This seems to work:
var $begin1 = $(".begin1").click( function(e) {
$begin1.toggleClass('pressed');
});
Instead of check the complete string of the class of the element you can check if the element has specific class using hasClass:
var $begin1 = $(".begin1").click( function(e) {
e.preventDefault();
if(!$(this).hasClass('pressed')){
$begin1.removeClass('unpressed');
$(this).addClass('pressed');
} else{
$(this).removeClass('pressed');
$(this).addClass('unpressed');
}
});
li{
list-style-type: none;
}
.begin1.unpressed,
.begin2.unpressed {
background-color: white;
color: black;
border: 2px solid #4CAF50;
margin: 0 0 10px 0;
}
li.begin1.pressed,
li.begin2.pressed{
background: #4CAF50;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<li class="begin1 unpressed"><h2>Button</h2></li>
The problem with using the attr('class') is that you can't know what exactly will be the final string.
Just replace your js with:
$(document).ready(function() {
$(".begin1").click(function(){
$(this).toggleClass("pressed");
});
});