Keep phone area code in input - javascript

What I am trying to achieve is the input type text with initial area code added as a value
<input type="text" value="+1" id="phone" name="phone">
when user starts adding his/her phone number - this first +1 remains.
Here is how I have solved this:
$('#phone').keyup( function(){
var phone = $('#phone').val().substr(3); // copy phone number without the code
$('#phone').val(''); // emptying the value
$('#phone').val('+1-'+ phone); // adding the area code + entered number
});
but I guess it is rather silly and could be way better.
Here is Fiddle:
https://jsfiddle.net/gjzv6aph/
How can I make it better?

Use val() method with a callback function to generate new value with old value, the callback holds index as the first argument and old value as the second argument.
$('#phone').val(function(i, v){
return '+1-' + v.substr(3);
});
$('#phone').on('input', function() {
$(this).val(function(i, v) {
return '+1-' + v.substr(3);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="phone" value="+1-">

Related

How do a maintain an accurate character count between input from separate fields using JS?

I am using a form to build a block of text, the final output of which needs to be kept under a certain character count.
For the user, I need to be able to provide real-time character counting so they can adjust their entries as appropriate.
Basic HTML would be as follows:
<form>
<input type="text" id="#input1">
<input type="text" id="#input2">
</form>
<div class="character-counter">0</div>
However my JS/jQuery is not working very well: while it is outputting a counter in real time, it seems to be concatenating the final results in the output despite me parsing the variables as integers.
$('#input1').keyup(function() {
// Variables
var currentCharCount = parseInt($('.character-counter').text());
var fieldLength = parseInt($(this).val().length, 10);
var newCharCount = fieldLength + currentCharCount;
// Counter output
$('.character-counter').text(Number(newCharCount));
});
$('#input2').keyup(function() {
// Variables
var currentCharCount = parseInt($('.character-counter').text());
var fieldLength = parseInt($(this).val().length, 10);
var newCharCount = fieldLength + currentCharCount;
// Counter output
$('.character-counter').text(Number(newCharCount));
});
The correct solution will update the '.character-counter' div with the correct total character count between the fields every time a character is typed or deleted or pasted in.
Thanks!
You don't want the old value of the character-counter element at all, you purely want to use the lengths of the text in the two inputs. Separately: Don't use keyup, use input. (What if the user right-clicks and pastes? No keyup occurs...)
Separately, the id attributes of your input fields are incorrect: They shouldn't have the # on them.
So (see comments):
// You can hook the event on both fields with the same call
// Note using `input`, not `keyup`
$("#input1, #input2").on("input", function() {
// Get the length of each input's current value, then put it
// in the .character-counter div
$('.character-counter').text($("#input1").val().length + $("#input2").val().length);
});
<form>
<input type="text" id="input1">
<!-- No # here --------^ -->
<input type="text" id="input2">
<!-- Nor here ---------^ -->
</form>
<div class="character-counter">0</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

jquery masking number input

I am using a function to mask the number input into my textbox but i want to assign the value prior to masking it to a knockout observable. I am unsure of where in my function i can grab and store that value since when you enter a value in the textbox and tab out the values are replaced by "*" as intended only for display. So where my textbox displays ***111 my observable should have a value of 1111111.
var viewModel = function () {
$(".textboxsemimedium").on("keydown keyup",
function (e) {
$(this).prop("value",
function (i, o) {
if (o.length < 6) {
return o.replace(/\d/g, "*");
}
});
});
self.theMemberNo = ko.observable();
}
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="textboxsemimedium" data-bind="value:theMemberNo" data-val="true" data-val-length="Member Number be of 9 characters!" data-val-length-max="9" data-val-length-min="9" data-val-required="Member Number is required!" id="MemberNumber" maxlength="10" name="MemberNumber" title="Member Number is Required!" type="text" value="">
<span data-bind="text:theMemberNo"></span>
Try using this https://css-tricks.com/better-password-inputs-iphone-style/
Then you implement it like so $('#user-password-2').dPassword();
It works similar to iphone password.
You are binding the theMemberNo to the input value. So that, if value changes from 1 to * the observable changes too.
I wouldn't bind the value of the input text to an observable I would just bind the event keyup and then, I would have an observable to keep the original value. Obviously, you will have to keep up to date this observable every time there is a keyup event.

Jquery replace string in a textarea

I am trying to replace a string value in textarea while typing in textbox with jquery. I used keypress event to try achieving that. What may be the issue here in this fiddle?
<input type="text" id="textbox" />
<textarea id="txtArea">This is a sample test.</textarea>
jquery code
$("#textbox").keypress(function () {
var txtAreaValue = $('#txtArea').val();
var txtAreaValueAfterreplace = txtAreaValue.replace('sample', $(this).val());
$('#txtArea').val(txtAreaValueAfterreplace);
});
The main problem is that, when using keypress you are getting the value of the input box before it is set, so nothing appears. However even if you change it to keyup you still will only get one value because once 'sample' is replaced it is gone so therefor it cannot be replaced again.
A new logic needs to be considered if you are wanting to replace sample with the full value of the textarea. Consider the following example:
$("#add").click( function () {
$( '#txtArea' ).val( $('#txtArea').val().replace( 'sample', $("#textbox").val() ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" /><br>
<input type='button' id='add' value='add'>
<textarea id="txtArea">This is a sample test.</textarea>
Or we replace when the user stopped typing
var typing;
$("#textbox").keyup( function () {
// Stop the change from being made since they typed again
clearTimeout(typing);
// They typed, so set the change to queue up in a 3rd of a second
typing = setTimeout(function(){
$( '#txtArea' ).val( $('#txtArea').val().replace( 'sample', $("#textbox").val() ) );
},350);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" /><br>
<textarea id="txtArea">This is a sample test.</textarea>
You want to look for keyup, not keypress (you want to make sure you get the whole string.
You are trying to put the textbox value right? You're looking for the textarea value in line two of the javascript.
If you replace sample on the first key stroke, there won't be anything to replace the second key stroke.
You can simplify lines 3 and 4 into one line.
replace can only be used on a string. So you need to get the value first, if you're going to do it that way. txtAreaValue.val().replace('sample', $(this).val());
Feel free to play around with it on this fiddle: http://jsfiddle.net/snlacks/abc6skp9/
$("#txtBox").on('keyup', function () {
var txtValue = $(this).val();
$('#txtArea').val("this is a " + txtValue);
});
If you have a longer string, replace might work better, but you still need to store the full string somewhere.
var longString = "some really long string... sample... more...";
$("#txtBox").on('keyup', function () {
var txtValue = $(this).val();
$('#txtArea').val(longString.replace('sample', txtValue);
});

Javascript change hidden field on submit

Hi I am trying to install a merchant facility onto my website and it needs to submit a value $vpc_Amount which is the amount purchased in cents.
What I need to do is multiply the amount entered by the user ($amount) by 100 to get $vpc_Amount.
I tried the following but it isn't working.
<input type="text" ID="A1" name="amount"onkeypress="process1()">
<input type="hidden" id="A2" name="vpc_Amount">
And then the javascript
function process1() {
f1 = document.getElementById("A1").value;
total = f1*1000;
document.getElementById("A2").value = total;
}
What is happening is it is occasionally working but most of the time it doesn't. I know there is something wrong with the script so hence asking here.
Try to use onkeyup function -
<input type="text" id="A1" name="amount" value="" onkeyup="process1();" />
<input type="hidden" id="A2" name="vpc_Amount" />
javascript function -
function process1() {
var f1 = document.getElementById("A1").value;
var total = (f1 * 100);
document.getElementById("A2").value = total;
}
Use Jquery. http://jquery.com/
$(function() {
$('#form_id').submit(function(){
$('#form_id').find('#A2').val('New value');
return true;
});
});
Have you tried to use onkeyup event? It might be so that onkeypress event is triggered before the character is added to text field.
<input type="text" ID="A1" name="amount" onkeyup="process1()">
Also, I would suggest that you try to convert the value of the textfield to integer and add other input handling too. Users might enter any kind of data there and it can crash your javascript code.
This code should work:
document
.getElementById('A1')
.addEventListener('keyup', function (e) {
document.getElementById('A2').value = parseInt(this.value) * 1000;
})
keypress event triggers before value changes in text field and keyup after value has changed.
Basically event trigger in order:
keydown (onkeydown)
keypress (onkeypress)
keyup (onkeyup)
Force value to be integer or you will get NaN in some cases.
I will suggest to use onblur this is the best way if you want to use the build in attribute listener if you don't use jquery. Here is example:
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
And url to the example in w3 school :) http://www.w3schools.com/jsref/event_onblur.asp
First of all, I think you should use onkeypup event and not onkeypress
<input type="text" id="A1" name="amount" onkeyup="process1()" value="" />
<input type="hidden" id="A2" name="vpc_Amount" value="" />
Javascript code -
function process1() {
var f1 = parseFloat(document.getElementById("A1").value);
var total = f1*100; //you said 100 so, I changed to 100
document.getElementById("A2").value = total;
}
jQuery code for the same -
jQuery(document).ready(function($){
$("#A1").keyup(function(){
var total = parseFloat($("#A1").val()) * 100;
$("#A2").val(total);
});
});
Your code can be simplified by making use of the fact that form controls are available as named properties of the form baed on their name. This removes the requirement to add IDs to form controls that must have a name anyway.
Pass a reference to the control in the listener:
<input type="text" name="amount" onkeyup="process1(this)">
<input type="hidden" name="vpc_Amount">
Then use the passed reference to get the form and other controls:
function process1(element) {
element.form.vpc_Amount.value = element.value * 100;
}
You may wish to use the change event instead to save updating the hidden field unnecessarily while the user is typing and also to catch changes that aren't based on key presses (e.g. pasting from the context menu).
You should also do some validation of the values entered so the user doesn't attempt to send the form with invalid values (noting that you must also do validation at the server as client side validation is helpful but utterly unreliable).

Always returns a undefined value

I am using jQuery to send Ajax request to the server to save the values being input in the form. Below the section where I am stuck. The HTML is as
<span class="no-margin multiple Date_Off" style="margin-left: 104px;">
<input type="text" value="" /><input type="text" />
<input type="text" value="-" /><input type="text" />
<input type="text" /><input type="text" value="-" />
<input type="text" /><input type="text" /><input type="text" />
<input type="text" />
</span>
I have tried using jQuery to send the request. What I want to do is something like this
I want to save the values from the form, to the same Column_Name that the input fields have. In the multiple input fields I am not using input names. Instead I am using a classname which is identical to the Column_Name in the database.
For that, I am using $(this).parent().attr('class');. If I use this in an alert, it gives me the result without error. But if I use it in the code, it gives me undefined.
I want to append each input's value to the string to save it as a single string.
Here is what I tried so far
var input = $('input');
input.change(function () {
// Input click function...
if ($(this).parent().attr('class')
.replace(' multiple ', '')
.replace('no-margins', '') == 'Date_Off') {
// Date Time for the office work!
var value = '';
value = $(this).parent().find('input').each(function (index, ele) {
value += ele.val();
});
send_request('Date_Off', value);
// Below is the else condition, to execute only when the input is single
// Like a single string input and not like the one in image
// That's why I am using attr('name') for that.
} else {
send_request($(this).attr('name'), $(this).val());
}
});
But what it returns is always a undefined in the Query structure. Here is the function for that
function send_request(input_name, value) {
$.ajax({
url: '/ajax_requests/save_form',
data: 'input_name=' + input_name + '&form_id=' +
$('input[type=hidden]').val() + '&value=' + value,
error: function () {
$('.main-content').append(
'There was an error in request.
Please contact your website Developer to fix it.'
);
},
success: function () {
}
});
}
Image for the code execution
The input in focus was 1. Date. And the console shows the Internal Server Error. Because jQuery sent the request with input_name=undefined which is not a Column_Name.
I have created a (Mini) fiddle for that: http://jsfiddle.net/afzaal_ahmad_zeeshan/EHWqB/
Any help here?
For the fiddle that you posted, there were two errors. The first was you were calling ele.val(), but ele in this context is not a jQuery object - so you need to get the value property off of it. The second is that the jQuery each function operates on an array of objects and it's return value is that array of objects. You don't want your value, which should be a string, to be accepting that return value. Here is an updated, working fiddle
input.change(function () {
// Input click function...
var value = '';
$(this).parent().find('input').each(function (index, ele) {
value += ele.value;
});
send_request('Date_Off', value);
});
In this line you're trying to get the name of the input
send_request($(this).attr('name'), $(this).val());
I don't see a "name" attribute anywhere in your code, I think what you want is to get the class of the parent instead?
send_request($(this).parent().attr('class'), $(this).val());

Categories

Resources