Didn't updating class for element - jQuery [duplicate] - javascript

This question already has answers here:
Why does the setInterval callback execute only once?
(2 answers)
Closed 6 years ago.
After blur, if input is empty, i want to add class .hass-error, after that i write some text into input, on idea class .hass-error must removed and added class has-success. .has-error is removing but new clas
function checkSignupData() {
var username = $('.signup-panel input[name="username"]');
username.on({
'focusin': function(){},
'focusout': function(){
if(!this.value.length) {
$(this).closest('.form-group').removeClass('has-success').toggleClass('has-error');
}
else if(this.value.length > 3 && this.value.length < 32) {
$(this).closest('.form-group').removeClass('has-error').toggleClass('has-success');
}
}
});
}
setInterval(checkSignupData(), 100);

function checkSignupData() {
var username = $('.signup-panel input[name="username"]');
if (username.text().length > 0) {
username.closest('.form-group').removeClass().addClass('has-success');
} else {
username.closest('.form-group').removeClass().addClass('has-error');
}
}
window.setInterval(function(){
checkSignupData();
}, 5000);
This is not an ideal solution using setInterval as the DOM will become messy and slow your application. For example, if this username is within a form, then you can call the check when the form is submitted. Like I said, not the most ideal solution but the one I think you are trying to achieve.
checkSignupData() will be called every 5 seconds.
Another solution I have just thought of which may work:
username.on('keyup', function() {
// call function
});
I originally thought this may not work as it would not fire if nothing was in the input. However, pressing a backspace to remove text will trigger the event as well. The only think is that on start up, you will have to initialise the element to have has-error class as there will be initially nothing in it.

you don't need set interval because you are using events you will end up binding tons of event handlers which is probably causing your problem
also you should use addClass as it's more assertive
edit: remove the setInterval and call checkSignupData one time

Related

How to change an objects properties right after a condition is met?

I am trying to make a button go from .disabled = true to .disabled = false. I am making a Yahtzee clone for fun, and you have to choose a score to take on your third roll, and then after that the button will be unlocked and you can roll again. Here's what I had, but it crashes. I wanted to make a while statement until a score is selected. ptsss is the amount of scores that have been selected. (i.e. third roll should equal 1 score entered)
if(rollcount == 3){
while (ptsss * 3 < rollcount){
document.getElementById("rollbutton").disabled = true;
if (ptsss * 3 == rollcount){
document.getElementById("rollbutton").disabled = false;
break;
}
}
}
}
Try removing the while loop and (possibly) rewrite the code as a function to enable/disable the roll button as required. E.G.
function checkRollButton( rollcount, ptsss) {
if(rollcount == 3) {
document.getElementById("rollbutton").disabled = ptsss != 1;
}
}
Then call (or inline the code for) checkRollbutton in event handlers that update rollcount and/or ptsss.
As commented, the value of ptsss cannot be changed by other code while the while loop is running, because JavaScript is single threaded.
I've modified the statement that enables/disables the roll button according to my understanding of the design, please check it before use.
Loops in JavaScript are not like loops in some other languages.
If the condition in the loop is not being modified within the loop itself, it won't be modified (unless possibly it's happening inside an asynchronous function).
Also you shouldn't constantly use the getElement in a loop anyways.
The way to achieve the general functionality of what a while loop is in other languages, in JavaScript, is to use an interval.
So based on that your updated code can look something like this (not sure where the first if statement is being called from so I took it out, also the nested if statement would have never been called because it only takes effect if it's condition is false, so I changed that as well):
var roll=document.getElementById("rollbutton")//make sure this is called after that element has loaded
var inter=setInterval(function(){
if (ptsss * 3 == rollcount){
roll.disabled = false;
clearInterval(inter)
//Similar to break in while loop, can restart interval later after this
}
if (ptsss * 3 < rollcount){
roll.disabled = true;
}
}
},1000/30//30 FPS
);

Why is for loop setting all jquery onclick to last iteration [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
I have the following code that works
var btns = $('.gotobtn');
$('#'+btns.get(0).id).click(function() {
document.querySelector('#navigator').pushPage('directions.html', myInfo[0]); });
$('#'+btns.get(1).id).click(function() {
document.querySelector('#navigator').pushPage('directions.html', myInfo[1]); });
$('#'+btns.get(2).id).click(function() {
document.querySelector('#navigator').pushPage('directions.html', myInfo[2]); });
// this works. I click on button 0 and get myInfo[0],
// on 1 and get myInfo[1], on 2 and get myInfo[2]
But replacing it with a loop does not work correctly. Instead, I always get the last element: myIfno[2] for any button I press.
var btns = $('.gotobtn');
var i = 0;
for (i = 0; i<3; i++){
var btnid = "#" + btns.get(i).id;
$(btnid).click(function() {
document.querySelector('#navigator').pushPage('directions.html', myInfo[i]); });
}
// this does set the buttons on-click but when I click on them,
// all get the latest iteration, in this example myInfo[2]
Why is this? And how do I fix that, without defining each button manually?
I want to see how to do it in jquery.
Because: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script
Replace:
$(btnid).click(function() {
document.querySelector('#navigator').pushPage('directions.html', myInfo[i]);
});
With:
$(btnid).click(customFunction(i));
And declare this function outside the loop:
function customFunction(i) {
document.querySelector('#navigator').pushPage('directions.html', myInfo[i]);
}
your
$(btnid).click(function() {
document.querySelector('#navigator').pushPage('directions.html', myInfo[i]); });
Must be outside your for loop.
#ibrahim mahrir is correct. It's caused by the same phenomena as described in 46039325 although this question is specific for JQuery binding and will probably be useful to some. (I saw the unanswered question in several places on the web)
It happens because I'm binding to i, and in the meantime i has changed to the last iteration (which is 2 in this example). I need to bind to the value of i while iterating.
This will happen (due to quirks in javascript) if I define the binding to a parameter of a function. The parameter is "dynamically created" each time and the value of that param (during that iteration) will be bound.
So when I finally do click on the second button (id:1, the first is id:0), it will invoke the method with the value of 1, correctly.
Here's an example of how the fix looks in jQuery:
$(function(){ // document ready
function btnaction(i){
var btns = $('.gotobtn');
$('#'+btns.get(i).id).click(function() {
document.querySelector('#navigator').pushPage('directions.html', gotoInfo[i]);
});
}
and I call it in the loop
for (i = 0; i<6; i++)
btnaction(i);
Alls well that ends well...

Asking if variable is equal to an integer inside jquery click not working

The title really explains most of it, but basically, this should alert when I get the click the element, but it doesn't. It also does work when I put the alert() outside of the if, and in the beginning of the jquery on click. Here's my code:
var hasClickedWelcome = 0;
//Onclick event
$(".menu-welcome" ).click(function() {
var welcomeButton = document.getElementByClassName("menu-welcome");
if(hasClickedWelcome == 0) {
alert("hello");
$(".menu-welcome").addClass("menu-welcome-clicked");
hasClickedWelcome = 1;
} else {
welcomeButton.classList.remove("menu-welcome-clicked");
hasClickedWelcome = 0;
}
});
Your if statement has no meaning
if(hasClickedWelcome == hasClickedWelcome)
This will always return true, you'll always hit this code no matter what:
alert("hello");
$(".menu-welcome").addClass("menu-welcome-clicked");
hasClickedWelcome = 1;
Therefore, you have a clear logic problem.
Edit: See Daniel Beck suggestion on comments section
Initially, you have syntactic error, there is no inbuild function like document.getElementByClassName() (unless its your custom function), so clearly even if you put your alert in beginning of click it won't work.
Also, you are checking if(hasClickedWelcome == hasClickedWelcome) which does not make sense.
Use: document.getElementsByClassName("menu-welcome"); to get array of nodes having the class. Then, rest of your logic accordingly.
//Onclick event
$(".menu-welcome" ).click(function() {
// in jQuery "this" refers to the element that was selected in a callback
// it looks like toggleClass is really what you're looking for
$(this).toggleClass("menu-welcome-clicked");
});

Is it possible to disable 'step' in input type number [duplicate]

This question already has answers here:
Can I hide the HTML5 number input’s spin box?
(20 answers)
Closed 7 years ago.
I would like to know if its possible to override the browser step behaviour or to intercept and change the step value before steping or prevent stepping from happening as a function for input type number.
For example when incrementing using up and down increment/decrement arrows/scroll stepping etc, I would like to manipulate the stepping process before it happens.
eg:
<input type="number" min="1.01" max="1000" id="num"/>
I tried not giving a step attribute. This did not work.
Step attribute only takes values 'all' and numbers, it does not take false.
So I cannot disable it using any attributes. I also tried over riding the stepUp, stepDown functions but that does not get called when the browser step function is happening.
I basically want it either to not step at all or if it does step, then do a custom step function, in which I decide the step value based on its current value.
I tried modifying on change, but this does not seem to work for the current step, only for the next step.
Here is the javascript:
$("#num").on("keyup change focusin focusout", function (e) {
$(this).attr("step", getStep($(this).val()));
});
function getStep (val) {
val = parseFloat(val);
var step = 1;
if (val < 5) {
console.log('here');
step = 2;
} else if (val < 10) {
step = 5;
}
return step;
}
http://jsfiddle.net/urrLmm4L/
Here if I enter 5 it should increment by 5, but it increments by 1. Next time it increments by 5. I want to override the step value before stepping if possible.
I am not trying to solve this by using a text input, I am trying to identify whether there is a means to override the stepping function.
Not sure if this is what you're looking for but I'll give it a try.
WebKit desktop browsers add little up down arrows to number inputs called spinners. You can turn them off visually like this:
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
Source: https://css-tricks.com/snippets/css/turn-off-number-input-spinners/
EDIT
Solved it! Here is the fiddle
http://jsfiddle.net/649d66bb/
$(document).ready(function() {
$("input[type=number]").on("focus", function() {
$(this).on("keydown", function(event) {
if (event.keyCode === 38 || event.keyCode === 40) {
event.preventDefault();
}
});
});
});

Command Buttons Not Responding to JS functions

I am very close to finishing this program but am unable to get past one last hurdle. I want some very simple code to execute when the command buttons are pressed. When the Submit Order button is pressed the following code should run to check that the form is completed.
function validateForm()
{
if ($("tax").value = 0)
{
alert ("You have not selected anything to order");
}
if ($("shipCost").value = 0)
{
alert("You must select a method of shipping");
}
}
And when the reset button is pressed the following code should run.
function initForm()
{
$('date').value = todayTxt();
$('qty1').focus();
}
Unfortunately the buttons are not executing the code which I am trying to execute through the following set of functions.
window.onload = function ()
{
initForm();
todayTxt();
productCosts();
shipExpense();
$('shipping').onchange = calcShipping;
calcShipping();
$("Submit Order").onclick = validateForm();
$("reset").onclick = initForm();
}
I have created a fiddle so you can see the full program: http://jsfiddle.net/KhfQ2/ Any help is greatly appreciated.
You're doing it way wrong.
With if statements, you use == instead of =.
= in A = B means assign value of B to A
== in A == B means A equals B
Read about .ready and use it instead of window.onLoad, it's quite a bad choice when it comes to binding, ie.
$( document ).ready(function() {
//taken from api.jquery.com/ready/
});
If you're using jQuery, use # when refering to ID objects, ie.
$('#tax').val();
On no account should you use spaces when giving any object a unique name or class!
Pay attention to letters. You had ".clisk()" instead of "click()".
Check it out and provide us with fixed code.
It is simple. $("Submit Order") doesn't work, because the button doesn't have this id. You can change this to something like $("btn-submit-order"). Same thing to reset.
Moreover, when you test $("tax").value = 0 I think you mistyped = instead of ==.
Other issues...
I think you mean
if ($("#tax").val() == 0)
Note:
Uses the correct selector #
Uses the jQuery val() function. The jQuery object doesn't have a value property.
Compares to 0 using loose checking, though personally I would write the line as
if (+$("#tax").val() === 0)

Categories

Resources