Check the code below. Now if I put some text in pTitle and when I press space from the keyboard it makes a - clone dash between words I typed. But the problem is after I press next word previous - dash removes also between - and word it also makes an auto space which I don't want. Now tell me how can I fix the - auto remove issue? Any advice? also, a fiddle link attached for a quick check
Html:
pTitle: <input type="text" id='pTitle' name="fname"><br>
<br>
pUrl: <input type="text" id='pUrl' name="lname"><br>
Jq code:
$('#pTitle').keyup(function (e) {
if (e.keyCode === 32) {
$('#pUrl').val($(this).val()+'-');
} else {
$('#pUrl').val($(this).val());
}
var charNumber = e.currentTarget.value.length;
if (charNumber === 0) {
$('#pUrl').val('#');
}
});
You can use a .replace() to swap the spaces for hyphens. The ternary equation allows the url to be "#" of the length of the input value == 0 (for example if you have text entered and then delete all characters) or the hyphenated text if there is text in the input.
$('#pTitle').keyup(function (e) {
var newVal = $(this).val();
newVal.length == 0
? $('#pUrl').val('#')
: $('#pUrl').val(newVal.replace(/ /g,'-'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
pTitle: <input type="text" id='pTitle' name="fname"><br>
<br>
pUrl: <input type="text" id='pUrl' name="lname"><br>
A nice solution is provided by #gavgrif above.
If you want to avoid regex, then here's a non regex solution
$('#pTitle').keyup(function (e) {
var val = $(this).val();
val.length==0
? $('#pUrl').val('#')
: $('#pUrl').val(val.split(" ").join("-"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
pTitle: <input type="text" id='pTitle' name="fname"><br>
<br>
pUrl: <input type="text" id='pUrl' name="lname"><br>
You can simply read the text from pTitle input and replace space by dash character '-' and set the result into pUrl input
$('#pTitle').keyup(function (e) {
$('#pUrl').val($(this).val().replace(/ /g,'-'));
var charNumber = e.currentTarget.value.length;
if (charNumber === 0) {
$('#pUrl').val('#');
}
});
Related
I want to change the first letter to Uppercase when I write on the textbox.
I wrote the below code but it changes the letter in style of css and when I send it with form it send it with small word at first.
how can i transform to capitalize in jquery?
here is my code :
$('.capital').css('textTransform', 'capitalize');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" value="" class="capital"/>
Use toUpperCase and substr to get 1st letter and make it upper case.
$(".capital").focusout(function() {
var yourtext = $(this).val();
alert(yourtext.substr(0, 1).toUpperCase() + yourtext.substr(1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" value="" class="capital"/>
This code always changes the first letter to uppercase. I think it's bad design to do so.
var firstCapitalAlways= function (event) {
var val = $(event.target).val();
var firstLetterUpper = val[0] ? val[0].toUpperCase() : "";
$(event.target).val(firstLetterUpper + val.substr(1, val.length));
}
var firstCapitalOnBlur = function(event) {
var val = $(event.target).val();
if(val){
$(event.target).val(val[0].toUpperCase() + val.substr(0, val.length))
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label>Always</label>
<input type="text" value="" onkeyup="firstCapitalAlways(event);" class="capital"/>
<label>Onblur</label>
<input type="text" value="" onblur="firstCapitalOnBlur(event);" class="capital"/>
For example I have, input type with predefined length.
I want to achieve, when the input value is bigger or equal to 3, to replace that part of string[3] with '/';
<input type="text" id="number" maxlength="6" placeholder="MM/YY"/>
And here is jquery
$('#number').on('keypress',function(){
if(this.value.length <= 3) {
this.value.replace(this.value[3],'/');
}
});
So in short when user types inside input field for example: 1234, the number 3 needs to be replaced with '/' and than the value would be 12/2017, like expiration date of credit card. Thanks in advance
You can try something like this. Had to change the maximum length of input's value from 6 to 7.
Try with e.g. 12/2017.
$('#number').on('keypress', function() {
if (this.value.length >= 2) {
this.value = this.value.slice(0, 2) + '/' + this.value.slice(3, this.value.length)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="number" maxlength="7" placeholder="MM/YY" />
You could try the following.
Where delimeterIndeces is where in the string you want to check and change the values. InputString is the string returned from the input tag.
let delimeterIndices = [2,5]; // "02[/]15[/]2017";
let inputString = "123152017";
let resultString = inputString.split('').map((char, index) => {
if(delimeterIndices.indexOf(index) !== -1) {
return '/';
} else {
return char;
}
}).join('');
console.log(resultString);
I want to set a minimum number of text that is written in a text box.
Normally we use the min property of html. But I don't want it.
Can anybody help me with the JavaScript code which check the number of text written in a text box and if it is lesser than 7 and greater than 21 an alert box would be shown. Or else it wont
<input type="text" id="txt">
<input type="button" onClick="myFunction()">
Js
function myFunction() {
.....
}
I know only this much.
Please help
You can use pattern attribute of HTML5
This will set minimum characters required to 1 and max characters required
to 15
<input type="text" id="txt" pattern="[a-z]{1,15}>
function myFunction() {
if ($('#txt').val().length < 21 && $('#txt').val().length > 7) alert("yez");
}
$('button').on('click', function() {
myFunction()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt">
<button>click</button>
this should work - it checks the length of the content in your #txt HTML element. If its greater than 7 and smaller than 21 it will alert yez
i added snippet which is counting only number of real 'words' empty spaces are omitted.
function wordCount(text) {
totalCount = 0;
words = text.split(' ')
words.forEach(function(word) {
if (word.length > 0) {
totalCount++;
}
})
return totalCount;
}
window.myFunction = function() {
textarea = document.getElementById('txt');
words = wordCount(textarea.value);
if(words < 7 || words > 21) {
alert('Wrong number of words');
}
}
<input type="text" id="txt">
<input type="button" onClick="myFunction()" value="Submit">
You can trigger an event on blur that means, when the text box loses focus
$(document).ready(function(){
$('#text-box').blur(function(){
var value = $('#text-box').val();
if(value.length < 7 || value.length > 21){
alert("Invalid length");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text-box">
function validate(){
x=document.myForm
input=x.myInput.value
if (input.length>5){
alert("The field cannot contain more than 5 characters!")
return false
}else {
return true
}
}
I am having the below code to show input field with phone number in certain format. i.e., If phone number starts with 33,55 or 81 I will show it as (33) 1234-5678. If phone number starts with any other numbers, the format will be (123) 456-7890.
Now, the problem is when I submit the form, it is submitted as (33) 1234-5678. But I should submit 3312345678 and display (33) 1234-5678.
Could someone help me, how could i overcome this issue. I didnt use any jquery plugins;
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
jQuery(document).ready(function() {
jQuery("#criterion").change(function () {
var searchBy = jQuery('#smartWirelessSearch').val();
if(searchBy == 'Mobile'){
jQuery(this).attr("criterion", $(this).val());
var twoDigit = jQuery('#criterion').val().substr(0, 2);
var threeDigit = jQuery('#criterion').val().substr(0, 3);
var remainingDigits = jQuery('#criterion').val().substr(2, 10);
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
jQuery('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
jQuery('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
You can change the value when the form is submitted, just before it is sent to the server:
$("form").on("submit", function(){
var originalVal = $("#criterion").val();
var newVal = originalVal.replace(/[^\d]/g, '');
$("#criterion").val(newVal);
});
You could have a hidden input that you store the original value of the input before modifying it.
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
<input type="hidden" id="org" name="org" />
-
$(document).ready(function() {
$("#criterion").change(function () {
var searchBy = $('#smartWirelessSearch').val();
$('#org').val($(this).val());
if(searchBy == 'Mobile'){
$(this).attr("criterion", $(this).val());
var twoDigit = $('#criterion').val().substr(0, 2);
var threeDigit = $('#criterion').val().substr(0, 3);
var remainingDigits = $('#criterion').val().substr(2, 10);
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
$('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
$('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
If you need to have the original cleaned value all the time, there are many ways to do that too. One simple solution is to have clean it by your self everytime input changes.
If so, replace $('#org').val($(this).val()); by $('#org').val($(this).val().replace(/[^\d]/g, ''));
This basically replaces everything that is not a digit with an empty string.
There are two possibilities to solve this, the first is to have a second (extra) hidden input like:
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
<input id="criterion_hidden" name= "criterion_real" type="hidden" size="15" maxlength="60" value="" placeholder="" onkeypress = "submitOnReturn(event);">
And populate it in your jquery:
jQuery(document).ready(function() {
jQuery("#criterion").change(function () {
var searchBy = jQuery('#smartWirelessSearch').val();
if(searchBy == 'Mobile'){
jQuery(this).attr("criterion", $(this).val());
var twoDigit = jQuery('#criterion').val().substr(0, 2);
var threeDigit = jQuery('#criterion').val().substr(0, 3);
var remainingDigits = jQuery('#criterion').val().substr(2, 10);
$("#criterion_hidden").val(twoDigit + remainingDigits); //update it here.
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
jQuery('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
jQuery('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
The other solution is to change the value on the server side (PHP?) by using a replace with a regular expression such as /[^\d]/g.
On submit of the form replace input value of ( ) - with empty string "".
I would suggest two solutions:
1. Toggle Format
With this solution, you either show the formatted value in the input, or the clean digit-only value. So you would take care to show the digit-only value when the form is submitted, but also when the user edits the value (as suggested by #Rune FS):
jQuery(function($) {
function cleanMobile() {
if ($('#smartWirelessSearch').val() == 'Mobile') {
// Strip all non-digit characters
$("#criterion").val($("#criterion").val().replace(/[^\d]/g, ''));
}
}
function formatMobile() {
if ($('#smartWirelessSearch').val() == 'Mobile') {
// Apply format after first stripping all non-digit characters
$("#criterion").val($("#criterion").val()
.replace(/[^\d]/g, '')
.replace(/(33|55|81|...)(.*?)(....)$/, '($1) $2-$3'));
}
}
$("#myform").submit(cleanMobile);
$("#criterion").blur(formatMobile).focus(cleanMobile).keypress(function(e) {
if (e.keyCode == 13) {
$(this).closest('form').submit();
}
});
// Set initial format correctly on page load
formatMobile();
}, jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<select id="smartWirelessSearch">
<option value="Mobile">Mobile</option>
</select>
<input id="criterion" name="criterion" type="tel" class="inputboxBg"
size="15" maxlength="60" style="width:85%;" value="" placeholder="">
<input type="submit" value="submit">
</form>
Run the snippet to see how it responds to focus and submit.
Note that the code above also:
Uses a regular expression to format the number;
attaches the keypress handler via code instead of the element's onkeypress attribute;
defines functions for the format manipulations so these can be referenced in blur, focus and submit events;
defines a dummy smartWirelessSearch element so the code is compatible with your form;
gave the form an id myform, which you should replace with yours.
2. Use Hidden Input
If you do not want the input value to visibly change at form submission, you could add a hidden input and give that the digit-only value, like this:
<input id="criterionClean" name="criterionClean" type="hidden">
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15"
maxlength="60" style="width:85%;" value="" placeholder=""
onkeypress="submitOnReturn(event);">
In your Javascript add one line:
if(searchBy == 'Mobile'){
// ... your code ...
// Then pass the digits only in the hidden input
$('#criterionClean').val($(this).val().replace(/[^\d]/g, ''));
}
Now you'll submit both the formatted and the cleaned value. Your server code could then use the clean digit-only value.
If you prefer the clean value to be called #criterion, then swap the names of the two inputs in html and in your code.
HTML:
<input id=MyTextBox type="text" onkeypress="MyFunction()" />
<input id=MyButton type="button" onclick="Control()" />
Onkeypress Javascript :
I want to do below example , however i have not integrated according to "MyTextBox"
http://jsfiddle.net/2cYeu/9/
There must not be no space before character in textbox.
TRY this DEMO
For the first time space is not allowed later its allowed
function call(e) {
if (document.getElementById('nospace').value.length == 0) {
if (e.keyCode == 32) {
e.preventDefault();
}
}
}
function Control() {
var text = document.getElementById("MyTextBox").value;
if (text.charAt(0)==" ") {
alert("First Chart is space");
}
}
This works I have tested it
Also, to the left of jsfiddle, don't select "onDOMReady"
select no wrap in body
That's the problem why you get those errors