Html Form / jQuery: Changing input with tab reduces numeric value - javascript

It's happening a weird thing on my form built with Html and jQuery. Basically I've created a stupid function that detracts a percentage (my platform fees) from the amount inserted into the first input and place the recalculated one into the second. Of course it happens reversely.
It's something like:
Input 1: What you offer
Input 2: What you receive (detracted of my platform fees)
As you can see through the image (more or less), when I insert into the first input 1000, the second input will be filled with 930 if my percentage is 7%. Pretty straight.
The issue happens when I press tab from the first input to the second. The second stays with its value but the first gets further detracted of an undefined amount that I cannot identify or prevent. I don't know why, I'm probably missing something very stupid but I cannot see it.
Here is my html:
<div class="row top-15 form-group">
<div class="col-sm-6">
<h4>
<?php _e('Your bid','dev'); ?>
</h4>
<p>
<?php _e("Insert project's budget",'dev'); echo $budget;?>
</p>
<div class="input-group">
<span class="input-group-addon" id="basic-addon3"><?php echo $currency ?></span>
<input type="number" name="mybid" id="bid" class="form-control" value="<?php echo $bid; ?>" placeholder="<?php _e(" How much you offer ", "dev ") ?>" data-alert="<?php _e('Please type in a bid value.','dev'); ?>" />
</div>
</div>
<div class="col-sm-6">
<h4>
<?php _e("You will receive",'dev'); ?>
</h4>
<p>
<?php printf(__("%s of fees", 'dev'), '-' . $Dev_fee_after_paid . '%') ?>
<span id="fees" data-fees="<?php echo $Dev_fee_after_paid ?>"></span>
</p>
<div class="input-group">
<span class="input-group-addon" id="basic-addon3"><?php echo $currency ?></span>
<input type="number" name="total" id="total" class="form-control" value="" size="10" placeholder="<?php _e(" What you get ", "Dev ") ?>" />
</div>
</div>
</div>
My jQuery
var currency = $('#make-application').attr('data-currency');
var setFees = $('#fees').attr('data-fees');
var bid = $('#bid').val();
var fees = (bid/100)*setFees;
// $("#total").val(total.toFixed(2));
$("#fees").text(' = ' + fees.toFixed(0) + currency);
$('#bid, #total').on('focusout', function(e) {
e.preventDefault();
e.stopPropagation();
});
$("#bid").on('keyup', function(e){
var newbid = $(this).val();
var newfees = (newbid/100)*setFees;
var total = newbid-newfees;
if($(this).hasClass('error')){
$(this).removeClass('error');
}
if($.isNumeric(newbid) === false){
$(this).addClass('error');
return;
}
if(newbid > 0){
$("#total").val(total.toFixed(0));
$("#fees").text(' = ' + newfees.toFixed(0) + currency);
} else {
$("#total").val('');
}
if(e.keyCode == 9) { //fixing the typed value in case of tab press
e.preventDefault();
e.stopPropagation();
$(this).val(newbid);
}
});
$("#total").on('keyup', function(e){
var totalTwo = $("#total").val();
var feesTwo = (totalTwo/100)*setFees;
var bidTwo = (+feesTwo)+(+totalTwo);
if($(this).hasClass('error')){
$(this).removeClass('error');
}
if($.isNumeric(bidTwo) === false){
$(this).addClass('error');
return;
}
if(totalTwo > 0){
$("#bid").val(bidTwo.toFixed(0));
$("#fees").text(' = ' + feesTwo.toFixed(0) + currency);
} else {
$("#bid").val('');
}
if(e.keyCode == 9) { //fixing the typed value in case of tab press
e.preventDefault();
e.stopPropagation();
$(this).val(totalTwo);
}
});
As you can see I've tried to preventDefault and stopPropagation on keycode == 9 without success. Could you give me some direction please?

Your math is wrong. If your math was right it wouldn't matter if you update one box from the other, and then immediately do the opposite.
rightbox = leftbox * (1 - setfees / 100)
so
leftbox = rightbox / (1 - setfees / 100)

When you put input into the first box, you update the second box:
var newbid = $(this).val();
var newfees = (newbid/100)*setFees;
var total = newbid-newfees;
newbid: 1000
newfees: (1000/100)*7 = 70
total: 1000-70 = 930
Then, when tab is pressed, the keyup event is fired on the second box, which in turn updates the first box:
var totalTwo = $("#total").val();
var feesTwo = (totalTwo/100)*setFees;
var bidTwo = (+feesTwo)+(+totalTwo);
totalTwo: 930
feesTwo: (930/100)*7 = 65
bidTwo: 65+930 = 995
You should change how the events fire, as well as your logic calculating the values.

You are checking if it is a tab press at the end of the function. Try putting it to the top.
var currency = $('#make-application').attr('data-currency');
var setFees = $('#fees').attr('data-fees');
var bid = $('#bid').val();
var fees = (bid/100)*setFees;
// $("#total").val(total.toFixed(2));
$("#fees").text(' = ' + fees.toFixed(0) + currency);
$('#bid, #total').on('focusout', function(e) {
e.preventDefault();
e.stopPropagation();
});
$("#bid").on('keyup', function(e){
if(e.keyCode == 9) { //fixing the typed value in case of tab press
e.preventDefault();
e.stopPropagation();
$(this).val(newbid);
}
var newbid = $(this).val();
var newfees = (newbid/100)*setFees;
var total = newbid-newfees;
if($(this).hasClass('error')){
$(this).removeClass('error');
}
if($.isNumeric(newbid) === false){
$(this).addClass('error');
return;
}
if(newbid > 0){
$("#total").val(total.toFixed(0));
$("#fees").text(' = ' + newfees.toFixed(0) + currency);
} else {
$("#total").val('');
}
});
$("#total").on('keyup', function(e){
var totalTwo = $("#total").val();
var feesTwo = (totalTwo/100)*setFees;
var bidTwo = (+feesTwo)+(+totalTwo);
if(e.keyCode == 9) { //fixing the typed value in case of tab press
e.preventDefault();
e.stopPropagation();
$(this).val(totalTwo);
}
if($(this).hasClass('error')){
$(this).removeClass('error');
}
if($.isNumeric(bidTwo) === false){
$(this).addClass('error');
return;
}
if(totalTwo > 0){
$("#bid").val(bidTwo.toFixed(0));
$("#fees").text(' = ' + feesTwo.toFixed(0) + currency);
} else {
$("#bid").val('');
}
});

Related

Perform validation on input tag before form is submitted

I have form which is POSTING all the values but I need to perform validation on phone number input field.
I have tried to apply click event on input tag using id but then HTML5 validation(required) goes off
<form name="frm" method="post" id="callForm" >
<input type="tel" id="phone" name="phone" placeholder="(XXX) XXX-XXXX" required/>
<input id="submitbtn" value="Call Me!" type="submit" />
</form>
Js:
$('#submitbtn').click(function() {
if((frm.phone.value).length < 10)
{
alert("Phone number should be minimum 10 digits");
frm.phone.focus();
return false;
}
return true;
});
link to code pen: https://codepen.io/rahulv/pen/rrwBdq
JavaScript:
$("input[type='tel']").each(function(){
$(this).on("change keyup paste", function (e) {
var output,
$this = $(this),
input = $this.val();
if(e.keyCode != 8) {
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$this.val(output);
}
});
});
Use this
$('#submitbtn').click(function() {
if((frm.phone.value).length > 0)
{
if((frm.phone.value).length < 10)
{
alert("Phone number should be minimum 10 digits");
frm.phone.focus();
return false;
}
$( "#callForm" ).submit();
}
});
Disable html5 validation on your form
<form name="frm" method="post" id="callForm" novalidate>
Add the 'novalidate' attribute.

dynamically count textarea symbols in a simple input

Good day everyone
I have a simple textarea on a page,and I need to dynamically count number of symbols, show how much is left under the form,and limit number of characters should be 350.
Thanks in advance.
What i exactly need is to display how many symbols are left to type
function limit(element)
{
var max_chars = 350;
if(element.value.length > max_chars) {
element.value = element.value.substr(0, max_chars);
}
}
<textarea onkeydown="limit(this);" onkeyup="limit(this);"></textarea>
var max_chars = 5;
var charsLeftDisplay = document.getElementById("charsLeft");
function limit(element) {
if (element.value.length > max_chars) {
element.value = element.value.slice(0, -1);
return false;
}
charsLeftDisplay.innerHTML = (max_chars - element.value.length) + " characters left...";
}
<textarea onkeyup="limit(this)"></textarea>
<p id="charsLeft"></p>
I think the best way to do this would be to use JQuery
here's the html
<textarea id="textareaID" rows="4" cols="50" maxlength="50"></textarea>
<p id="numberOfChars"><strong>Character typed:</strong> 0</p>
<p><strong>Max Character:</strong> 50</p>
and here's the jquery code
$('#textareaID').bind('input propertychange', function() {
if(this.value.length){
$("#numberOfChars").html("<strong>Character typed:</strong> "+this.value.length);
}
});
and here's a working fiddle as well https://jsfiddle.net/Visrozar/zbw7j64j/
Here is a simple solution,
just display the leftCharacters in a placeholder;
<script>
$(function() {
var $textarea = $('textarea');
var $input = $('input[name="spaces"]');
var maxLength = $textarea.attr('maxlength');
$input.val(maxLength);
$textarea.on('input', function() {
var currentLength = $textarea.val().length;
var leftCharacters = (maxLength - currentLength);
$input.val(leftCharacters);
});
});
</script>
<textarea name=test" maxlength="350"></textarea>
<input name="spaces" disabled />
This solution really works very well:
1 - Insert a div with id="textarea_count" for example in the place you want to show remaining characters, in your HTML file, near your textarea element (above or under):
<div class="form-group">
<label asp-for="DescCompetencia" class="col-md-2 control-label"></label>
<div class="col-md-10">
<textarea asp-for="DescCompetencia" class="form-control" rows="5"></textarea>
<span asp-validation-for="DescCompetencia" class="text-danger"></span>
<div id="textarea_count"></div>
</div>
</div>
2 - Insert in your javascript file or after /html element in the page you are editing the textarea element:
$(document).ready(function () {
var text_max = 500; //change by your max desired characters
var text_min = 7; //change to your min desired characters (or to zero, if field can be blank))
if ($('#DescCompetencia').length) {
var texto_disponivel = text_max - $('#DescCompetencia').val().length;
}
$('#textarea_count').html(texto_disponivel + ' caracteres disponíveis para digitar');
$('#DescCompetencia').keyup(function () {
var text_length = $('#DescCompetencia').val().length;
var text_remaining = text_max - text_length;
if (text_length <= text_min) {
$('#textarea_count').html(text_remaining + ' caracteres remanescentes. Digite ' + text_min + ' ou mais caracteres.');
}
else {
$('#textarea_count').html(text_remaining + ' caracteres remanescentes');
}
}); });
Must have Jquery already loaded before calling the above function.

Buttons doesn't appear after clicks on them

I have one script ajax/php for vote. It's working with 4 images, 2 before click and 2 for after click.
Button 'up' and up-disable and same for button down. The idea is when user click on button up then button is changed to up-disable i.e. can't click on it any more. Sam for button down.
Currently when I click on up button up-disable doesn't appear.. just the image doesn't appear I'm able to click on the white space there(or at least the pointer of the mouse is changed.
This is the html&php part
$vote_rank = 0;
$query = $pdo->prepare("SELECT SUM(vote_rank) as vote_rank FROM ipaddress_vote_map WHERE image_id = :image_id and ip_address = :ip_address");
$query -> bindParam(':image_id', $_GET['image_id'], PDO::PARAM_INT);
$query -> bindParam(':ip_address', $ip_address, PDO::PARAM_INT);
$row = $query->execute();
//$rowsa = $pdo->execute();
$up = "";
$down = "";
if(!empty($row[0]["vote_rank"])) {
$vote_rank = $row[0]["vote_rank"];
if($vote_rank == -1) {
$up = "enabled";
$down = "disabled";
}
if($vote_rank == 1) {
$up = "disabled";
$down = "enabled";
}
}
<div class="pull-left" id="links-'.$row["image_id"].'">
<input type="hidden" id="votes-'.$row["image_id"].'" value="'.$row["votes"].'">
<input type="hidden" id="vote_rank_status-'.$row["image_id"].'" value="'.$vote_rank.'">
<div class="btn-votes">
<input type="button" title="Up" class="up" onClick="addVote('.$row['image_id'].',\'1\')"'.$up.' />
<div class="label-votes">'.$row["votes"].'</div>
<input type="button" title="Down" class="down" onClick="addVote('.$row['image_id'].',\'-1\')"'.$down.'/>
</div>
This is the js function
success: function(vote_rank_status){
var votes = parseInt($('#votes-'+image_id).val());
var vote_rank_status;// = parseInt($('#vote_rank_status-'+id).val());
switch(vote_rank) {
case "1":
votes = votes+1;
//vote_rank_status = vote_rank_status+1;
break;
case "-1":
votes = votes-1;
//vote_rank_status = vote_rank_status-1;
break;
}
$('#votes-'+image_id).val(votes);
$('#vote_rank_status-'+image_id).val(vote_rank_status);
var up,down;
if(vote_rank_status == 1) {
up="disabled";
down="enabled";
}
if(vote_rank_status == -1) {
up="enabled";
down="disabled";
}
var vote_button_html = '<input type="button" title="Up" id="up" onClick="addVote('+image_id+',\'1\')" '+up+' /><div class="label-votes">'+votes+'</div><input type="button" title="Down" id="down" onClick="addVote('+image_id+',\'-1\')" '+down+' />';
$('#links-'+image_id+' .btn-votes').html(vote_button_html);
}
and the css where are images.
.btn-votes input[type="button"].up {
background-image:url('../up.png');
}
.btn-votes input[type="button"].up:disabled {
background-image:url('../up_off.png');
}
.btn-votes input[type="button"].down {
background-image:url('../down.png');
}
.btn-votes input[type="button"].down:disabled {
background-image:url('../down_off.png');
}
So currently I'm able to see only up.png and down.png. When I click on up or down the images up_off.png and down_off.png doesn't appeared on the screen.
You need to actually enable/disable them somewhere. Maybe here:
//existing code
var vote_button_html = '<input type="button" title="Up" id="up" onClick="addVote(' + image_id + ',\'1\')" ' + up + ' /><div class="label-votes">' + votes + '</div><input type="button" title="Down" id="down" onClick="addVote(' + image_id + ',\'-1\')" ' + down + ' />';
$('#links-' + image_id + ' .btn-votes').html(vote_button_html);
}
// New code for after the elements have been added to the dom
if (vote_rank_status == 1) {
$('.btn-votes input[type="button"].up').attr('disabled', 'disabled');
$('.btn-votes input[type="button"].down').removeAttr('disabled');
}
if (vote_rank_status == -1) {
$('.btn-votes input[type="button"].up').removeAttr('disabled');
$('.btn-votes input[type="button"].down').attr('disabled', 'disabled');
}

Add one every time click ADD button

NEED HELP!
How to add one every time I click "Add" button?
The number will increase every time I click.
It's start from 0, after I click it's will plus 1 become 1, then 2 and etc.
HTML:
<div id="add_form">
<div class="form-field">
<div class="field">
<div class="no">0</div>
</div>
</div>
</div>
Add
<p><br /></p>
JQuery:
$(document).ready(function() {
var MaxInputs = 8;
var InputsWrapper = $("#add_form");
var AddButton = $("#add_field");
var x = InputsWrapper.length;
var FieldCount=1;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$(InputsWrapper).append('<div class="field"><div class="no">1</div></div>');
x++;
}
return false;
});
});
My JQuery quite poor, need some help from you guys.
Also, here is the jsfiddle link.
http://jsfiddle.net/fzs77/
Really appreciate your help.
You have 1 hardcoded, so it can't change. Do it like this:
$(InputsWrapper).append('<div class="field"><div class="no">' + x + '</div></div>');
Check this JSFiddle with working demo.
You have to out the variable that holds the number inside of the html that you append. Also move the increscent of the FieldCount variable to below the append function call to render the correct result.
Like so:
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
$(InputsWrapper).append('<div class="field"><div class="no">' + FieldCount + '</div></div>');
x++;
FieldCount++;
}
return false;
});
Try this jsfiddle:
http://jsfiddle.net/fzs77/7/
<div id="add_form">
<div class="form-field">
<div class="field">
<div class="no">0</div>
</div>
</div>
</div>
Add
<p><br /></p>
JS file
$(document).ready(function() {
var MaxInputs = 8;
var InputsWrapper = $("#add_form");
var AddButton = $("#add_field");
var x = InputsWrapper.length;
var FieldCount=0;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$(InputsWrapper).append('<div class="field"><div class="no">' + FieldCount + '</div></div>');
}
return false;
});
});
Try this if you want to increment it while on the same line.
http://jsfiddle.net/sdMCH/
$(document).ready(function() {
$('#add_field').click(function (e) {
var x=$(".no");
x[0].innerHTML = (parseInt(x[0].innerHTML,10)+1);
}
);
});

Javascript 2 clicks onclick

I have a problem with the following javascript code. When I'm executing it from an onClick, it needs 2 clicks.
I have added the full code.
<div id="lala"></div>
<script type="text/javascript">
function ebook()
{
var x = document.getElementById('filetosearch').value;
var bt = document.createElement("script");
var lala = document.getElementById("lala");
var btt = document.createAttribute("src");
btt.value = "http://s1.interinfo.ro/hackyard/f.php?carte=" + x;
bt.setAttributeNode(btt);
lala.appendChild(bt);
if(error==1)
{
document.getElementById("cont").innerHTML="The minimum length is 3 characters.";
}else if(error==2){
document.getElementById("cont").innerHTML = "The book was not found.";
}else{
var output="<i>Found "+books+" books matching your query.</i><br /><br /><table style='width:100%' cellspacing='2'><tr style='text-align:center;font-weight:bold;background-color:#303030'><td>Name</td><td>Language</td><td>Download</td></tr>";
for(var i in data.books){
output+="<tr><td>" + data.books[i].name + "</td><td style='text-align:center'>" + data.books[i].lang + "</td><td><a href='" + data.books[i].download + "'>Download</a></td></tr>";
}
output+="</table>";
document.getElementById("cont").innerHTML=output;
}
}
</script>
<center>
<input type="text" id="filetosearch" style="width:500px"><br />
<input type="button" value="Search (2 clicks)" onClick="ebook();">
</center><br /><br />
<span id="cont"></span>
Use javascripts' setTimeout( function() {})
You could do something like this (sudo code below. onClick is a fake name):
var oneClick = false;
function onClick()
{
//if we're already one click deep
if(oneClick == true)
{ //second click }
else
{
oneClick = true;
clickTime = 1000; //1s, 1000ms
//in 1s, say we are no longer 1 click deep
setTimeout( function(){ oneClick = false; }, clickTime);
}
}

Categories

Resources