Issue function called x times button is clicked - javascript

I'm facing this problem that whenever user clicks "Click" couple times and then clicks on "SEND" it shows clicked times the message.
For example if the dialog opens 5 times it shows 5 times the message.
Facing this problem couple times something with binding how can i fix this i dont want to learn a quick fix.
But a good way to code things.
var test = {
init: function() {
$(".toggle-dialog").on("click", function() {
$(".picture-upload-dialog").toggle("fast", function() {
if ($(this).is(":visible")) {
test2.uploadPicture()
}
});
});
}
},
test2 = {
uploadPicture: function() {
var submitButton = $(".submit-picture");
submitButton.on("click", function() {
var fileVal = $("#fileToUpload").val();
if (fileVal !== "") {
var ext = fileVal.split("."),
arrayExtensions = ["jpg", "jpeg", "png", "bmp", "gif"];
console.log(fileVal)
ext = ext[ext.length - 1].toLowerCase();
if (arrayExtensions.lastIndexOf(ext) == -1) {
test3.errorMessage(001)
}
} else {
test3.errorMessage(002)
}
})
}
},
test3 = {
errorMessage: function(type) {
var error;
switch (type) {
case 001:
error = "< Ext error >"
break;
case 002:
error = "< No picture selected. >"
break;
default:
return "ERROR"
}
$(".error").append(error)
}
}
test.init();
.picture-upload-dialog {
display: none;
}
.toggle-dialog:hover {
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="error">
</div>
<div class="public-text-input">
<div class="text-options">
<i class="toggle-dialog ct icon-picture" title="Upload...">Click</i>
<div class="picture-upload-dialog">
<div class="picture-upload-header">
Upload your picture
</div>
<div class="picture-upload-content">
<input type="file" name="fileToUpload" id="fileToUpload">
<button class="ct icon-picture submit-picture">SEND</button>
</div>
</div>
</div>
<div id="color-picker"></div>
</div>

It is because you are calling test2.uploadPicture() every time it is visible, which in turn is adding one click handler every time "click" is clicked. Try the updated version:
var test = {
init: function() {
test2.uploadPicture()
$(".toggle-dialog").on("click", function() {
$(".picture-upload-dialog").toggle("fast", function() {
});
});
}
},
test2 = {
uploadPicture: function() {
var submitButton = $(".submit-picture");
submitButton.on("click", function() {
var fileVal = $("#fileToUpload").val();
if (fileVal !== "") {
var ext = fileVal.split("."),
arrayExtensions = ["jpg", "jpeg", "png", "bmp", "gif"];
console.log(fileVal)
ext = ext[ext.length - 1].toLowerCase();
if (arrayExtensions.lastIndexOf(ext) == -1) {
test3.errorMessage(001)
}
} else {
test3.errorMessage(002)
}
})
}
},
test3 = {
errorMessage: function(type) {
var error;
switch (type) {
case 001:
error = "< Ext error >"
break;
case 002:
error = "< No picture selected. >"
break;
default:
return "ERROR"
}
$(".error").append(error)
}
}
test.init();
.picture-upload-dialog {
display: none;
}
.toggle-dialog:hover {
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="error">
</div>
<div class="public-text-input">
<div class="text-options">
<i class="toggle-dialog ct icon-picture" title="Upload...">Click</i>
<div class="picture-upload-dialog">
<div class="picture-upload-header">
Upload your picture
</div>
<div class="picture-upload-content">
<input type="file" name="fileToUpload" id="fileToUpload">
<button class="ct icon-picture submit-picture">SEND</button>
</div>
</div>
</div>
<div id="color-picker"></div>
</div>

Related

li element vanish after page reload

I am trying to add a li element in the below div (Functionality is to upload an attachment)
See below pic 1
My JavaScript functionality of Submit button adds the Li in the div perfectly fine. But, when I refresh the page it's gone.
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">CHOOSE A FILE</button>
<span id="custom-text">No file chosen, yet.</span>
<button type="button" id="submit-button" onclick="Submit()">Submit</button>
<div id="collapseThree">
</div>
<script>
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
const submitBtn = document.getElementById("submit-button");
const slides = [];
var str = '';
customBtn.addEventListener("click", function() {
realFileBtn.click();
});
window.addEventListener('load', (event) => {
console.log(slides)
console.log('The page has fully loaded yo');
// document.getElementById("collapseThree").innerHTML
});
/* window.onload = document.getElementById("slideContainer").innerHTML
*/
function Submit() {
console.log("going in");
document.getElementById("collapseThree").innerHTML += str
}
realFileBtn.addEventListener("change", function() {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(
/[\/\\]([\w\d\s\.\-\(\)]+)$/
)[1];
console.log(customTxt.innerHTML)
slides.push(customTxt.innerHTML);
slides.forEach(function(slide) {
str = '<li>' + slide + '</li>';
});
console.log(arr)
console.log(slides)
} else {
customTxt.innerHTML = "No file chosen, yet.";
}
});
</script>
You can use localStorage to save and read data. Simply call
function getSlides() {
var slidesJson = localStorage.getItem('slides') || '[]';
return JSON.parse(slidesJson);
}
to get all current slides and
function setSlides(slides) {
localStorage.setItem('slides', JSON.stringify(slides))
}
to save the current state of the array.

"set_correct " Class is applied to the all the elements. why?

I am trying to make my javascript quiz page. I'm facing the issue set_correct class is applied to the all elements. But I want this class should be apply to only the correct answer. "set_wrong" class also should be apply to the wrong answer. please look at my code.
<div class="container">
<div class="button_port">
<input type="button" id="btnid" class="pevcls" value="Previous Question" onclick="Prevfn()">
<input type="button" id="btnidnt" class="nextcls" value="Next Question" onclick="Nextfn()">
</div>
<div class="content_box">
<div id="question">
</div>
<div id="answer_button">
</div>
</div>
</div>
var i=1;
var questionpos=document.querySelector(".content_box");
var getquestion=document.getElementById("question");
var answersbutton=document.getElementById("answer_button");
function Prevfn()
{
if(i==1)
{
document.getElementById("btnid").disabled=true;
alert("Dont have the previous one");
document.getElementById("btnidnt").disabled=false;
}
else{
i--;
setquestion();
}
}
function Nextfn()
{
if(i==5)
{
var ind=document.getElementById("btnidnt").disabled=true;
document.getElementById("btnid").disabled=false;
alert("Dont have next content");
}
else{
i++;
setquestion();
}
}
var allAnswerButtons = [];
function setquestion(question)
{
var questionsvari=questions[i].question;
getquestion.innerHTML=questions[i].question;
allAnswerButtons.forEach(abutton => abutton.remove());
allAnswerButtons = [];
questions[i].Answers.forEach(answer=>
{
const button=document.createElement("button");
button.classList.add('Ans_btn');
button.innerText=answer.text;;
if(answer.correct)
{
button.dataset.correct=answer.correct;
}
button.addEventListener('click', selectanswer);
answersbutton.appendChild(button);
allAnswerButtons.push(button)
}
)
}
function selectanswer(e)
{
var sal_answer=e.target;
var tof_value=sal_answer.dataset.correct;
Array.from(answersbutton.children).forEach(function(button)
{
setStatusClass(button,tof_value);
}
)
}
function setStatusClass(element,correct)
{
console.log(element);
if(correct=="true")
{
clearstatusclass(element);
element.classList.add('set_correct');
}
else
{
element.classList.add('set_false');
}
}
function clearstatusclass(element)
{
element.classList.remove('set_correct');
element.classList.remove('set_false');
}
const questions=[
{
question:"How many factors do a prime number have?",
Answers:[{text:'1 and the number itself',correct:'true'},{text:'2 and the 4',correct:'false'},{text:'3 and 6',correct:'false'},{text:'4 and 8',correct:'false'}]
},
{
question:"What type of term 2x+7y is?",
Answers:[{text:'234',correct:'true'},{text:'Binomial',correct:'false'},{text:'132',correct:'false'},{text:'222',correct:'false'}]
},
{
question:"What is the percentage of 2:5?",
Answers:[{text:'JavaScript',correct:'false'},{text:'40%',correct:'true'},{text:'JavaSql',correct:'false'}]
},
{
question:"Which food contains lactobacillus?",
Answers:[{text:'Curd',correct:'true'},{text:'Jojeshe',correct:'false'},{text:'JavaSql',correct:'false'},{text:'JavaSql',correct:'false'}]
},
{
question:"What is the national game of Bangladesh?",
Answers:[{text:'JavaScript',correct:'false'},{text:'Jojeshe',correct:'false'},{text:'Kabaddi',correct:'true'}]
},
{
question:"What is the national game of Bangladesh?",
Answers:[{text:'JavaScript',correct:'false'},{text:'Jojeshe',correct:'false'},{text:'Kabaddi',correct:'true'}]
}
];
My full code is below
https://codepen.io/pavisaran/pen/wvgQaew
Anyone please tell me where Im doing my mistake
When you click on the answer, you go through all the options (buttons) instead of setting for one.
function selectanswer(e)
{
var sal_answer=e.target;
var tof_value=sal_answer.dataset.correct;
Array.from(answersbutton.children).forEach(function(button)
{
setStatusClass(button,tof_value);
}
)
}
Change button.addEventListener('click', selectanswer); in setquestion to button.addEventListener('click', (e) => selectanswer(e, button));
And fix selectanswer
function selectanswer(e, button)
{
var sal_answer=e.target;
var tof_value=sal_answer.dataset.correct;
setStatusClass(button,tof_value);
}

ngInfiniteScroll stops working after ng-click on repeated element

I'm using ngInfiniteScroll in a few different places to show contacts, and missed calls. It loops over every item and adds a ng-click to show user profile. The scrolling works fine in all locations until you actually click on a user/call. Afterwards the scroll never triggers again in either contacts nor phone calls. I've looked at their docs and seen infinite-scroll-listen-for-event which I figured is what I needed for infinite scroll to reset after the click event, but it doesn't appear to be working. I can't tell if I have the $emit in the wrong location, or what?
HTML
<md-list infinite-scroll="recent.moreContacts()" infinite-scroll-disabled="recent.busy" infinite-scroll-listen-for-event="resetInfiniteScrollList" infinite-scroll-distance="1" infinite-scroll-immediate-check="false" infinite-scroll-parent="true">
<md-list-item ng-repeat="client in recent.clients | orderBy:'firstName'" ng-click="recent.viewCustomer(client.id)" class="repeater-list-item recent-session" layout="row" layout-align="start start" aria-label="View {{client.fullName}}'s profile">
<div ng-if="client.avatar" class="md-avatar" style="background-image: url('{{client.avatar}}');"></div>
<div ng-if="!client.avatar" class="md-avatar" ></div>
<div class="md-list-item-text">
<h3>{{client.firstName}} {{client.lastName}} <span ng-if="!client.firstName">Unknown <small class="text-tertiary text-gray">(Customer: {{client.id}})</small></span></h3>
</div>
</md-list-item>
</md-list>
loading contacts
vm.moreContacts = function () {
$timeout(function () {
$rootScope.closeSidenavs();
$rootScope.btnActive = 'contacts';
$mdSidenav('contacts').open();
$sessionStorage.currentTab = 'contacts';
if (vm.busy || vm.foundAllContacts || vm.contactsSearchActive) {
} else {
vm.busy = true;
api.get('/account/' + $rootScope.user.account.id + '/clients?page=' + vm.contactsNextPage, function (success, data) {
if (success) {
for (var i = 0; i < data.clients.length; i++) {
vm.clients.push(data.clients[i]);
}
self.totalFound = data.totalFound;
self.lastPageLoaded = data.page;
if (data.clients.length === 25) {
vm.contactsNextPage = vm.contactsNextPage += 1;
console.log(vm.contactsNextPage);
}
if (vm.clients.length === self.totalFound) {
vm.foundAllContacts = true;
}
} else {
vm.isClientsError = true;
}
vm.busy = false;
});
}
}, 10);
};
ng-click function
vm.viewCustomer = function (clientId) {
if (clientId > 0) {
if ($mdMedia('xs') || $mdMedia('sm')) {
$rootScope.btnActive = '';
$rootScope.closeSidenavs();
}
$location.path(
"/customer/" + clientId + "/feed"
);
$rootScope.$emit('resetInfiniteScrollList');
//vm.contactsSearchActive = false;
}
};

how to handle the multiple ng-show and one ng-hide in angularjs if one condition is set to true and the left out ng-show to be false

When a user hovers over the stars, I want to show the message You rated <b>{{rate1}} star.</b><a ng-click="showMe()" class="modifyIt"><b > modify?</b></a>, and if the user has clicked on the rating I want to show 'Thanks for rating' (see html below for my logic). But after this if the user hovers again over the stars I want to show You rated <b>{{rate1}} star.</b><a ng-click="showMe()" class="modifyIt"><b > modify?</b></a> again.
Issue is once rated, it shows 'Thanks for rating' always. How to fix this?
Please see my attempt at doing this below, and it would be helpful if someone can point out the error I have made. Thanks!
<div class="user">
<uib-rating ng-model="rate" max="5" read-only="isReadonly" on-titles="['one','two','three']" aria-labelledby="default-rating" class="readOnlyRating "></uib-rating>
<div class=" arrow_box rt" ng-show="showRatings">
<div class="ratingName">
<h5><b>Give your rating here..</b></h5>
</div>
<div class="stars">
<uib-rating ng-model="rate1" ng-click="rating(rate1)" max="5" read-only="isReadonly1" on-hover="hoveringOver(value)" on-leave="overStar = null" titles="['one','two','three']" aria-labelledby="default-rating" class="readOnlyRating "></uib-rating>
</div>
</div>
<div ng-mouseleave="hoverOut()" class="arrow_box rt" ng-show="ratevalue ">
<h5 class="ratedPopover"> Thanks for rating </h5>
</div>
<div class="arrow_box rt" ng-hide="showRatings">
<h5 class="ratedPopover">You rated <b>{{rate1}} star.</b><a ng-click="showMe()" class="modifyIt"><b > modify?</b></a>
</h5>
</div>
</div>
here is my directive file
scope.rating = function (rate) {
scope.ratevalue = rate;
if ($localStorage[localStorageRatingKey] == undefined) {
previousRatingValue = 0;
$localStorage[localStorageRatingKey] = scope.ratevalue;
} else {
previousRatingValue = $localStorage[localStorageRatingKey];
$localStorage[localStorageRatingKey] = scope.ratevalue;
}
ratingService.update({
companyId : scope.details._id,
userRating : scope.ratevalue,
previousRatingValue : previousRatingValue
}, scope.details, successCallback, errorCallback);
function successCallback(res) {
// console.log("coming from callback");
scope.rate = res.avgRatings;
scope.reviewsCount = res.totalRatingsCount;
}
function errorCallback(res) {
NotificationFactory.error('Failed to update the product rating...', res.data.message);
}
};
scope.showMe = function () {
scope.showRatings = !scope.showRatings;
console.log("showme :" + scope.showRatings);
}
scope.hoverOut = function () {
if ($localStorage[localStorageRatingKey]) {
scope.showRatings = !scope.showRatings;
} else {
scope.showRatings = true;
}
console.log("hoverOut ShowRatings:" + scope.showRatings);
}
if ($localStorage[localStorageRatingKey]) {
scope.showRatings = false;
} else {
scope.showRatings = true;
}
Instead of using ratevalue to show the message 'Thanks for rating', I would suggest using a flag like hasjustRated. In your code initialize this to false
at the beginning of this function definition: scope.rating = function (rate) { ... }
Also at the end of the success callback, add the following lines:
scope.hasjustRated = true;
Then on leave of hover, reset this value to false. I suggest adding a clear function for on leave that would do all the necessary steps when leaving hover.
Also what the showMe function does is a bit unclear.

why my onClick() method of the Button can't be useful?

Here is part of my html layout (with sciter framework):
<div id="volume_micphone_slider" style="z-index:1;">
<input id="volume_slider" class="volume_slider" type="vslider" name="p1c" max="100" value="20" buddy="p1c-buddy" />
</div>
<div>
<button id="volume_show" class="volume_show" ></button>
<button id="micphone_show" class="micphone_show"></button>
</div>
Here is my onClick() method of the Button(use tiscript):
var volume_flag=1;
function volume_ctrl()
{
if(volume_flag)
{
$(#volume_slider).style#display ="none";
volume_flag=0;
}
else
{
$(#volume_slider).style#display ="inline-block";
volume_flag=1;
}
}
$(#volume_show).onClick = function()
{
volume_ctrl();
}
But this method can't be useful.Please help me to figure out my problem.Thanks.
Multiple problems in your code as explained inline
var volume_flag=1;
function volume_ctrl()
{
if(volume_flag)
{
$("#volume_slider").style.display ="none"; //selector in quotes and . before style
volume_flag=0;
}
else
{
$("#volume_slider").style.display ="inline-block";
volume_flag=1;
}
}
$("#volume_show").onclick = function() //small c instead of C in onclick
{
volume_ctrl();
}
it is pure javascript code
var volume_flag = 1;
function volume_ctrl() {
if (volume_flag) {
document.getElementById('volume_slider').style.display = "none";
volume_flag = 0;
} else {
document.getElementById('volume_slider').style.display = "inline-block";
volume_flag = 1;
}
}
document.getElementById('volume_show').addEventListener("click", function() {
volume_ctrl();
})

Categories

Resources