Multiple clicks required to complete two functions - javascript

I have some javascript that for some reason requires two consecutive clicks in order to function correctly. Here is the code for the link:
Select All
Now, here is the code for the function that is called with the onclick:
function select_all_com(){
$("[name=file_com_appeal].com-checkbox").each( function() {
$(this).attr('checked', true);
});
UpdateTotalFee();
}
and finally, here is the last bit of code:
function UpdateTotalFee(){
var AppealCount = 0;
$('input[name=file_com_appeal].com-checkbox').each(function(){
if( $(this).next().hasClass('checked') ){
AppealCount++; }
});
$('#AppealFeeTotal').text("$"+(AppealCount*140));
}
This final part is supposed to run the first time the link is clicked but some reason it does not run the first time, only the second time. Specifically what I mean is that the first click updates all of the checkboxes from off to on, but does not update the #AppealFeeTotal. A subsequent click of the Select All link when the checkboxes are already selected then causes the #AppealFeeTotal to update.
Any ideas why this might be requiring two clicks? I should also add that there is one line of code in particular that I am unsure about. I inherited the code from someone else, and I'm not sure of the reason why this is used:
if( $(this).next().hasClass('checked') ){
Thanks for any ideas you might have.

A few things, first attr('checked') is not the same as hasClass('checked') I suspect this is where your problem is. Your code does not add a "checked" class that I can see, but you're counting where that is the case. You should be using is:checked selector for this.
Second, if I read your code correctly, you're just counting checked checkboxes to get your total. You can do this more efficiently like this:
$(":checkbox").filter(':checked').length
Naturally you'll want to refine that selector (so it only counts specific checkboxes) but without more html, I can't help with that.

$(document).ready( function() { // this is a function which execute when document is ready in jQuery
var clicks = 0; // I am taking clicks variable so, to check whether the user have clicked for the first time
$("a").on("click", function() { // this is a function which execute when target anchor tag is clicked
clicks++; // now user have clicked the anchor tag so, i have to increase value to 1
if(clicks==1) { // this condition checks whether user have clicked the anchor tag for the first time? if yes, then execute the code
$("[name=file_com_appeal].com-checkbox").each( function() { // this is a each function which loops through all targets perform operations
$(this).attr('checked', true); // while looping through all targets this will set attribute or property "checked" to true means its checked
});
}
else if(clicks==2) { // this conditions check that whether anchor tag is clicked for second time
var AppealCount = 0;
$('input[name=file_com_appeal].com-checkbox').each(function(){
if( $(this).prop('checked') ){
AppealCount++;
}
});
$('#AppealFeeTotal').text("$"+(AppealCount*140));
clicks = 0; // set to zero because if user repeatedly clicks the anchor tag
}
});
});

Related

Click on button first time show alert, click second time execute code

I want to show users, when they click on a button for the first time, an alert when in a date field a value is chosen which lies before the current date. When they insist to this choice for good reasons, I want them to give a second chance to click on the same button, and then the value has to be submitted.
The click event is defined in a function:
$("#edit_date_btn").click(function(){
// do something and save
}
In an other function the comparing is handled. The basic code is:
function edit_date_compare() {
....
if(usersDate < today)
{ //show alert
return false; // needed for the first click so the input is not submitted
}
I've tried several options e.g. with a count on the click function (on a second click 'return true;' instead of 'return false;') but it seems difficult to handle this situation. Any ideas how to make this successful? It could be with Javascript or jQuery.
You have the right idea with the count on the click function. I suspect you might have difficulty implementing it. You need a separate variable that tracks the number of clicks. Here's a working fiddle: http://jsfiddle.net/zwmquxaL/
$(document).ready(function () {
var clickCount = 0;
$("#btnSave").click(function () {
if (clickCount > 0) {
AlertSave();
} else {
AlertFirst();
clickCount++;
}
});
});
function AlertSave() {
alert("Some code has been executed!");
}
function AlertFirst() {
alert("Are you sure you want to perform this operation?");
}

How to Capture changing value of textbox

I have a webpage with a small survey. I want to pre populate some of the answers based on user inputs to previous question.
In the below code, if value of id QR~QID3 depends upon value of QID1_Total. However after the page loaded and even if the condition is met the textbox is not populated with correct value.
.addOnload(function()
{
if(document.getElementById("QID1_Total").value>15) {
document.getElementById("QR~QID3").value = "Good";
}
else{
document.getElementById("QR~QID3").value = "Average";
}
});
$("#QID1_Total").on("input", function() {
//statements goes here
});
use of on("input" will track every inputting event, include drop and paste.
know more about onInput : https://mathiasbynens.be/notes/oninput
Here is an Fiddle Example to know how trigger works :
https://jsfiddle.net/5sotpa63/
An Assumption
Let Us Say you are using a function, which holds this statement show Good and Average according to users Input.
var targetElem = document.getElementById("QID1_Total");
var showComment = (targetElem,value>15) ? "Good" : "Average";
document.getElementById("QR~QID3").value = showComment;
Above code is the shorter method of your own statement mentioned in your question.
Now on Change of the target QR~QID3 you need to load some content. you utilize the below code as follows.
$("#QR~QID3").on("input", function() {
//your next question loading statements goes here,
//statements to proceed when you show some comment Good or Average
}).trigger("input");
Hope! this could be helpful.
$('#QID1_Total').keydown(function () {
//ur code
});
as the mouse key is pressed in the input field the function is called
You need to add an event listener to the "QID1_Total" element.
If you want to run the check while the user changes the input, i.e. after each keypress use the oninput event.
If you want to run the check after the user has completed the input, use the onchange event. The onchange event will only fire after the input loses focus.
You can bind the event listeners by using the addEventListener() function like this:
document.getElementById("QID1_Total").addEventListener("input", function(){
//Code goes here
});
Here is a JSFiddle showing both methods.
You also have to use the parseInt() function on the textbox values before you can perform mathematical functions with them.

Simulate div click multiple times

I've got slider in template glitching, and code is minimized. So, got tired of looking for the cause of the problem and decided to use a quick hack.
I need to fire a div click multiple times.
I've used this piece of code to trigger a click
$('.control-prev').trigger('click');
Works fine for one time click.
Now, how do i make it click multiple times?
http://jsfiddle.net/br4Lmyso/ (warning: creates three alerts, just to quickly show it works)
// set your count to whatever you want. Get a reference to the div
// so you're not querying the DOM everytime.
var triggerCount = 3;
var triggerDiv = $('.control-prev');
// loop!
for(var i = 0; i < triggerCount; i++) {
triggerDiv.trigger('click');
}
To be clear, trigger(...) does not simulate the click behavior and there is no way you can simulate the click behavior. What it does is to call the function that handle given event. These two are total different. For example:
$('#test').click(function() {
console.log("Clicked");
});
$('#test').dblclick(function() {
console.log("Double Click");
});
$('#test').trigger('click');
$('#test').trigger('click');
Despite of rapidly trigger two clicks, the double click will not trigger.

Disable Submit button if none of selector options is selected

I would like to disable the Submit button on a search form that only contains select dropdowns. There are several similar questions here but I most of them deal with fields. The closest thing to my case is Disable submit button if all three of three specific dropdown fields are empty. I modified the solution supplied in JSFiddle to feature an empty option, and did get it working -- but only in JSFiddle, not on my page.
I use the same code from the proposed answer (only changed IDs):
$('#submit').attr('disabled','disabled');
$('select').change(function(){
if ( $(this).hasClass('require_one') ){
$('#submit').removeAttr('disabled');
}
});
$('#submit').click(function() {
$('#searchform').submit();
});
I add the above code right after I include the jquery.js (v. 1.9.1).
I generate the form dynamically, but in JSFiddle I use exactly what is seen in the page source: http://jsfiddle.net/cheeseus/d5xz6aw8/8/
I have no idea why I can't get it to work on the actual page, hope those more knowledgeable can help sort it out.
And, if possible, I would also like the Submit button to be disabled again if all three selects are set to blank values again.
I usually don't like using the ID(3) for CSS selector since you can have only one ID selector with that name on the document and there might be another element already with the same ID. How about using the class hierarchy instead to pinpoint the button element?
In any case you need to re-check the count everytime what you select on what is empty:
var $submitButton=$('.selector .btn');
var $selectors=$('.selector select.require_one');
$submitButton.attr('disabled','disabled');
$('.selector select.require_one').change(function(){
var $empty=$selectors.filter(function() { return this.value == ""; });
if ( $selectors.filter(function() { return this.value == ""; }).length == $selectors.length ){
$submitButton.attr('disabled','disabled');
} else
{
$submitButton.removeAttr('disabled');
}
});
$submitButton.click(function() {
$('#searchform').submit();
});
JSFiddle code here
You can just use a simple count to see if you should display the button or not. Here is jQuery code.
var count = 0;
$('.require_one').change(function() {
count++;
if (count >= 3) {
$('#submit').removeAttr('disabled');
}
});
$('#submit').attr('disabled','disabled');
I think this is because you didn't check is your document ready.
I added few improvements:
caching jquery object in variables, makes your code a bit faster (you don't look for it everytime select is beeing changes).
used recommended way of binding events - 'on' function
'disabled' is property not an attribute, jQuery has dedicated method to use
on select change - check all selects if there is any not selected, it there is - set prop disabled to true, otherwise set false.
instead of disabling submit at initialization, trigger same action you do when selected is beeing changed (if you start with option selected in all select initial state won't be disabled).
$(document).ready(function () {
var $submit = $('#submit');
var $selects = $('select.require_one');
$submit.on("click", function() {
$('#searchform').submit();
});
$selects
.on("change", function(){
var $not_selected = $selects.filter(function() {
return !$(this).val();
});
$submit.prop('disabled', $not_selected.length ? true : false);
})
.first()
.triggerHandler('change');
});

Function keyup executed even though its not called

I have an input called itemtitle. When I click on a button the element called counter increases by one. So the code bellow works for the first item. The counter div's innerHTML is 1 and when I write in the itemtitle input the text shows up on item 1.
if (document.getElementById("counter").innerHTML === "1"){
$("#itemtitle").keyup(function() {
$("#item1").html($("#itemtitle").val());
});
I click the button again and the counter innerHTML goes up to 2. I there have the following code.
if (document.getElementById("counter").innerHTML === "2"){
$("#itemtitle").keyup(function() {
$("#item2").html($("#itemtitle").val());
});
But when I write in the itemtitle input the text shows up on both item1 and item2. Even though the counter value is 2. How do I solve this? When counter is 1 I only want the text to go to item1. And when counter is 2 it should only go to item 2.
Thanks in advance
You are registering keyup event based on those two if conditions, So it would not mean that the particular events will fire only when the if condition matches, It would fire all the times. So what you should do is, Write a if condition inside that keyup event, so that the branching statement would react according to the html values. i.e] 1 or 2
Try this,
$("#itemtitle").keyup(function() {
if($.trim($("#counter").html()) === "1")
{
$("#item1").html($(this).val());
}
else
{
$("#item2").html($(this).val());
}
});
I solved it now. And were still able to have them seperated. I changed it to:
$("#itemtitle").keyup(function() {
if (document.getElementById("counter").innerHTML === "1"){
$("#item1").html($("#itemtitle").val());
}
});
This way it checks the value whenever i enter something into the input.

Categories

Resources