Prevent double on.click event Javascript - javascript

i'm still new in using java script, i try to make trigger time when first input field get click, then the function trigger will active, the problem every time i click input field, the triggger always active again, i try using
event.preventDefault();
but it's didn't work, please help me where i do it wrong ?
this my code
$('#trigger').on("click", function(e) {
e.preventDefault();
var timeleft = 1;
var downloadTimer = setInterval(function(){ document.getElementById('countdown').value = `${timeleft} seconds`;
timeleft += 1;
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="trigger" class="form-control" required>
<input type="text" id="countdown" class="form-control" required>
edit : i try it like this, but its still haunt me if is this the best method?
function myFunction() {
var timeleft = 1;
var downloadTimer = setInterval(function() {
document.getElementById('countdown').value = `${timeleft} seconds`;
timeleft += 1;
}, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="trigger" onclick="myFunction(); this.onclick=null;" class=" form-control" required>
<input type="text" id="countdown" class="form-control" required>

You can use focusout event of Textbox
$( "#trigger" )
.focusout(function() {
myFunction();
});
and after focusout you can disable Textbox

Related

onmouseover doesn't function when onchange does?

I've got a little script that toggles a button between disabled and not depending on the value of a number input. It works exactly as I'd expect when the event trigger is input.onchange, but it doesn't seem to work if I try to make the event button.onmouseover.
This works:
<form action="/action_page.php">
<label for="quantity">Quantity (between 1 and 5):</label>
<input onchange="myFunction()" type="number" id="quantity" name="quantity" min="1" max="5">
<input disabled id="submit" type="submit">
<p id="number"></p>
</form>
<script>
function myFunction() {
var x = document.getElementById("quantity");
var y = document.getElementById("submit");
if (x.value >= "5") {
y.toggleAttribute("disabled");
} else if (y.hasAttribute("disabled") == false) {
y.toggleAttribute("disabled");
}
}
</script>
This does not:
<form action="/action_page.php">
<label for="quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
<input onmouseover="myFunction()" disabled id="submit" type="submit">
<p id="number"></p>
</form>
<script>
function myFunction() {
var x = document.getElementById("quantity");
var y = document.getElementById("submit");
if (x.value >= "5") {
y.toggleAttribute("disabled");
} else if (y.hasAttribute("disabled") == false) {
y.toggleAttribute("disabled");
}
}
</script>
If I remove the inital disabled attribute from the button, my else if toggle works, but the first if never toggles it off. Is there something about onmouseover that prevents it from checking the quantity value?
In HTML, disabled elements don't fire events, you can't hover or click them.
You can wrap such element within a div and fire mouseover on that div.
Here's code:
<form action="/action_page.php">
<label for="quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
<div style="display: inline;padding: 10px;" id="wrapper_submit">
<input disabled id="submit" type="submit">
</div>
<p id="number"></p>
</form>
<script>
// After page load
window.onload = function(){
// Get div and on its mouseover
document.getElementById("wrapper_submit").onmouseover = function(){
var x = document.getElementById("quantity");
var y = document.getElementById("submit");
if (x.value > "5") y.disabled = true;
else if(x.value >= "1") y.disabled = false;
}
}
</script>
Edit: Mouseover event only fires when cursor is over element it self, it will not fire if child element covers parent. In above case if you remove padding from [Div('wrapper_submit')], mouseover event will not work.
Use mouse enter event, it works even if child covers parent 100%.
document.getElementById("wrapper_submit").onmouseenter = function(){
var x = document.getElementById("quantity");
var y = document.getElementById("submit");
if (x.value > "5") y.disabled = true;
else if(x.value >= "1") y.disabled = false;
}
It happens because your input is disabled and it doesn't react
Try this code and let me know if it works to you
<form action="/action_page.php">
<label for="quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
<input onmouseover="myFunction()" disabled id="submit" type="submit">
<p id="number"></p>
document.getElementById("quantity").onmouseover = function() {myFunction()};
function myFunction() {
var x = document.getElementById("quantity");
var y = document.getElementById("submit");
if (x.value < "5" ) { y.removeAttribute("disabled"); }else if (x.value>= "5") {
y.toggleAttribute("disabled");
} else if (y.hasAttribute("disabled") == false) {
y.toggleAttribute("disabled");
}
}

Getting values from multiple text boxes on keypress in javascript

I have 8 different text fields in my form, it's a part of customer bill.
Here it is
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty">
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation">
......
up to 8
From this I want to show the sum of all the values as total value
<span>Total extra cost:1678</span>
It should be changed when the values of any text field is changed, so how can I do it perfectly using keyup event?
UPDATE
I have attached an onkeyup event to each textfield
`onkeyup="findSum(this.value)"'
and i am using a global array for store the input values var extras=[]
function findSum(value)
{
if(value!=''){
console.log(value);
extras.push(parseInt(value));
if(extras!='')
$('#extratotal').text(extras.reduce(getSum));
else $('#extratotal').text('0');
}
}
But its not worked well
You can get SUM of all inputs that have form-control class on keyup event like this:
$('input.form-control').on('keyup',function() {
var total = 0;
$('input.form-control').each(function(){
if (this.value == ''){
total += parseInt(0);
}else{
total += parseInt(this.value);
}
});
$('#total').val(total);
});
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtcustomduty" class="form-control" placeholder="Customs Duty" >
<input type="text" name="txtlcltranspotation" class="form-control" placeholder="Local Transportation" >
<input type="text" name="other" class="form-control" placeholder="other" >
Total extra cost: <input id="total" >
You can use the target.value property of the event passed to the key listener - this will give you the value of the input field:
document.addEventListener('input', 'keyup', function(e) {
// use e.target.value here
}
Just add this to a running total and update the text inside the listener function.
I have defined in JavaScript instead of jQuery. Try it..
<script>
function sum()
{
var sum = 0;
var array_field = document.getElementsByClassName('sum_field');
for(var i=0; i<array_field.length; i++)
{
var value = Number(array_field[i].value);
if (!isNaN(value)) sum += value;
}
document.getElementById("total").innerHTML = sum;
}
</script>
<body>
<input type="text" name="txtcustomduty" class="form-control sum_field" placeholder="Customs Duty" onkeyup="sum()">
<input type="text" name="txtlcltranspotation" class="form-control sum_field" placeholder="Local Transportation" onkeyup="sum()">
<p>Total:<span id="total">0</span></p>
</body>

jquery mobile delay slider event

I try to start the slider event when the last value was selected. The idea is, to create something like combination lock.
I've this solution:
<div data-role="page">
<label for="slider1">first</label>
<input data-type="range" name="slider1" id="slider1" value="10" min="0" max="20" />
<br>
<label for="slider2">second</label>
<input type="range" name="slider2" id="slider2" value="10" min="0" max="20" />
<br>
<label for="slider3">third</label>
<input type="range" name="slider3" id="slider3" value="10" min="0" max="20" />
</div>
var seconds = 3,
timer;
$("#slider1, #slider2, #slider3").on("slidestop", function(e) {
var slider1_value = $('#slider1').val();
var slider2_value = $('#slider2').val();
var slider3_value = $('#slider3').val();
var update = function() {
if (slider1_value == 15 && slider2_value == 2 && slider3_value == 2) {
alert("Great!!!");
} else {
alert("Try it again!!!");
}
}
if (timer) clearTimeout(timer);
timer = setTimeout(update, seconds * 1000);
});
Maybe there is a better solution, because the user have to wait for 3 seconds before something happens?
Here is my fiddle
How about this one?
$("#slider1, #slider2, #slider3").on("slidestop", function(e) {
var slider1_value = $('#slider1').val();
var slider2_value = $('#slider2').val();
var slider3_value = $('#slider3').val();
if (slider1_value == 15 && slider2_value == 2 && slider3_value == 2) {
alert("Great!!!");
}
});
EDIT
I have made you a fiddle as well: https://jsfiddle.net/EliteSystemer/7hpbanq9/
My reason for the change is that I would not want to have an error casted each time my combination is wrong, but only when it's correct.
The code above provides automatic verifiation each time one of the sliders are changed. A different approach is to add a button for manual verification. Please let me know if that's what you want, and I'll provide an example for that as well.

ie8 update value event

I have been staring at this for 2 hours. The purpose is for when a user tabs out of a field, the value will be converted in to two digits.
For some reason IE8 Chokes on this the first time you try it but it works the second time. After that it occasionally breaks.
// backbone snippit
events: {
'blur [name=month], [name=day], [name=year]': 'sanitizeAge'
},
'sanitizeAge': function(e) {
var view = this;
var $el = $(e.target);
var $val = $el.val();
if($val.length === 1){
$el.val('0'+$val);
}
},
// html snippet
<div class="padded grid-quarter">
<input name="month" type="text" placeholder="MM" class="grid-whole text-field month" data-validate="month" data-min="2" maxlength="2" tabindex="3">
</div>
<div class="padded grid-quarter">
<input name="day" type="text" placeholder="DD" class="grid-whole text-field day" data-validate="day" data-min="2" maxlength="2" tabindex="4">
</div>
<div class="padded grid-half">
<input name="year" type="text" placeholder="Year of Birth" class="text-field grid-whole year" data-validate="year" data-min="4" maxlength="4" tabindex="5">
</div>
</fieldset>
Here's a simplified version of your answer:
'sanitizeAge': function(e) {
var val = e.target.value;
if (val.length === 1){
e.target.value = '0'+val;
}
},
I was able to get it to work only by getting the value via javascript instead of jquery.
'sanitizeAge': function(e) {
var view = this;
var $el = $(e.target);
var $val = $el[0].value; // <---- FIX
if($val.length === 1){
$el.val('0'+$val);
}
},

Locally storing form to set last current form to the new current form

I know the title sounds quite difficult to understand (weird) but here is it's explanation:
Suppose I have 2 forms on my page. A button's click hides a current form and then shows up another. I refresh the page. Now I want the form which was before the refresh the current form to be after the refresh to be current form aswell. I know that it can be done by using localStorage but I don't know how. :P
Code (HTML):
<div class="span5">
<!-- Row's 2nd Column holding the sign-in/sign-up form -->
<form action="login.php" method="post" class="form-signin" id="login_frm">
<h2 class="form-signin-heading">Login</h2>
<input class="input-xlarge" type="text" placeholder="Username" name="username" />
<input class="input-xlarge" type="password" placeholder="Password" name="password" />
<br/>
<input type="submit" name="submit_login" value="Login" class="btn btn-primary" />
</form>
<form action="login.php" method="post" class="form-signin hide" id="register_frm">
<h2 class="form-signin-heading">Register</h2>
<input class="input-xlarge" type="text" placeholder="Username" name="username" />
<input class="input-xlarge" type="password" placeholder="Password" name="password" />
<input class="input-xlarge" type="password" placeholder="Confirm Password" name="confirm_password" />
<br/>
<input type="submit" name="submit_register" value="Register" class="btn btn-primary" />
</form>
</div>
CSS: Using bootstrap :)
JS:
var registerBtn = $("#register_button"); //storing the hyperlink of register in a variable
var i = 0; //click count
$(document).ready(function () {
$("#register_button").on('click', function (e) {
e.preventDefault();
i++;
if (i % 2 === 0) {
$("#register_frm").fadeToggle('fast', function () {
$("#login_frm").fadeToggle('fast');
});
$(this).text('Register');
} else {
$("#login_frm").fadeToggle('fast', function () {
$("#register_frm").fadeToggle('fast');
});
$(this).text('Login');
}
});
});
Well, here should be a working solution. I've marked new code with a comment.
var registerBtn = $("#register_button"); //storing the hyperlink of register in a variable
var i = 0; //click count
$(document).ready(function () {
$("#register_button").on('click', function (e) {
e.preventDefault();
i++;
if (i % 2 === 0) {
$("#register_frm").fadeToggle('fast', function () {
$("#login_frm").fadeToggle('fast');
});
$(this).text('Register');
localStorage.setItem("form", "login"); // < NEW CODE
} else {
$("#login_frm").fadeToggle('fast', function () {
$("#register_frm").fadeToggle('fast');
});
$(this).text('Login');
localStorage.setItem("form", "register"); // < NEW CODE
}
});
// v NEW CODE v
if (localStorage.getItem("form") == "register") {
$("#register_button").click();
}
// ^ NEW CODE ^
});
Here's a solution, although it does not work very well as a jsFiddle because of the page refresh due to the action method. PS. No need for local storage (in the conventional sense), these two variables can just be a couple of data properties of the window itself.
$(document).ready(function () {
var registerBtn = $("#register_button");
var rform = $('#register_frm');
var lform = $('#login_frm');
lform.show();
rform.hide();
var i = 0;
$("#register_button").on('click', function (e) {
e.preventDefault();
i++;
if (i % 2 === 0) {
rform.find('input[name = "username"]').val(window.data('username'));
rform.find('input[name = "password"]').val(window.data('password'));
$("#register_frm").fadeOut('fast', function () {
$("#login_frm").fadeIn('fast');
});
$(this).text('Register');
} else {
window.data('username', val('rform.find(input[name = "username"]'));
window.data('password', val('rform.find(input[name = "password"]'));
$("#login_frm").fadeOut('fast', function () {
$("#register_frm").fadeIn('fast');
});
$(this).text('Login');
}
});
});

Categories