I am validating certain input by using RegEx in jQuery which is working as expected. I want to add an addition where it adds 0 prior to decimal point if user don't add it.
For example,
.50 to 0.50
-.50 to -0.50
How to do that?
Code:
$(document).ready(function() {
$('#btnval').click(function() {
var floatRegex = new RegExp(/^-?[0-9]+([\,|\.]{0,1}[0-9]{2}){0,1}$/);
var currentSetTextBoxValue = $('#txtval').val();
//alert(currentSetTextBoxValue);
var validateInput = floatRegex.test(currentSetTextBoxValue);
alert(validateInput);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />
Change [0-9]+ to [0-9]*, so that it allows zero digits instead of requireing at least one.
$(document).ready(function() {
$('#btnval').click(function() {
var floatRegex = new RegExp(/^-?[0-9]*([\,|\.]{0,1}[0-9]{2}){0,1}$/);
var currentSetTextBoxValue = $('#txtval').val();
//alert(currentSetTextBoxValue);
var validateInput = floatRegex.test(currentSetTextBoxValue);
alert(validateInput);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />
You can fix the value like this if you need to convert it later:
if(currentSetTextBoxValue.indexOf('.') === 0){
currentSetTextBoxValue = '0' + currentSetTextBoxValue;
}
if(currentSetTextBoxValue.indexOf('.') === 1 && currentSetTextBoxValue.indexOf('-') === 0){
currentSetTextBoxValue = '-0.' + currentSetTextBoxValue.split('.')[1];
}
https://jsfiddle.net/str59woa/3/
You can replace the input using regex! This regex looks for . or -. at the beginning of the string and it will replace it by 0. or -0. depending on what it found, if it does not match the string will be the same.
$(document).ready(function() {
$('#btnval').click(function() {
var floatRegex = new RegExp(/^-?[0-9]+([\,|\.]{0,1}[0-9]{2}){0,1}$/);
var currentSetTextBoxValue = $('#txtval').val().replace(/^(\-)?\./, "$10.");
//alert(currentSetTextBoxValue);
var validateInput = floatRegex.test(currentSetTextBoxValue);
alert(validateInput);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />
https://jsfiddle.net/punsm9o0/1/
Related
I am working on a form with user input. This is my code:
<form role="search" id="default-search" action="<?php echo home_url(); ?>" novalidate>
<input class="number" name="price-from" placeholder="Cena od" maxlength = "11" min = "0">
</form>
First i want to automatically format user input from e.g. 10000 to 10,000 to have a clearer view on what was typed
My code for converting user input is:
jQuery.noConflict();
jQuery('input.number').keyup(function(event) {
// format number
jQuery(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
And for now everything works fine.
BUT!
When submitting this form, server is "thinking" that 10,000 = 10, not 10000.
So, what i need to do, is to convert back 10,000 to 10000 so server is counting it properly.
I need user to see formatted version of his input (like 10,000), while server should use plain number without commas (like 10000).
Any ideas much appriciated. Thanks!
I think, you are using type cast, so getting 10 as an output instead of 10000. So, it is truncating the character from the starting index of character (i.e. comma).
You can replace the comma and get the desired output.
var num = "10,000";
num = num.replace(',','');
Then, pass it to server side.
use this one to remove comma or all commas of your text
let num = "10,000"
num = num.replace(/,/g, ''),
Using the current Regex and replace approach:
You can just add a function that will use regex and the replace() method to remove all comma separators and then convert the input value to an integer using the parseInt() function when you are ready to submit the form like this:
jQuery.noConflict();
jQuery('input.number').keyup(function(event) {
// format number
jQuery(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
jQuery('#btn').click(function(){
const valueToSubmit = parseInt(jQuery('input.number').val().replace(/,/, ""));
alert("Submitting the value " + valueToSubmit);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="search" id="default-search" action="#" novalidate>
<input class="number" name="price-from" placeholder="Cena od" maxlength = "11" min = "0">
<button type="button" id="btn">Submit number</button>
</form>
Using the toLocaleString method:
You can just use the the toLocaleString() method along with the replace() method to automatically add comma separators to your input value and then converting them back to their original value when you want to submit the input value to your server like this:
jQuery.noConflict();
jQuery('input.number').on('input', function(e) {
e.target.value = parseInt(e.target.value.replace(/,/g, "")).toLocaleString();
});
jQuery('#btn').click(function() {
const valueToSubmit = parseInt(jQuery('input.number').val().replace(/,/g, ""));
alert("Submitting the value " + valueToSubmit);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="search" id="default-search" action="#" novalidate>
<input class="number" name="price-from" placeholder="Cena od" maxlength = "11" min = "0">
<button type="button" id="btn">Submit number</button>
</form>
With pure JavaScript, the above jQuery would look like this:
const input = document.querySelector('#default-search input[name="price-from"]');
const btn = document.getElementById('btn');
input.addEventListener('input', function() {
input.value = parseInt(input.value.replace(/,/g, "")).toLocaleString();
});
btn.addEventListener('click', function() {
const valueToSubmit = parseInt(input.value.replace(/,/g, ""));
alert("Submitting the value " + valueToSubmit);
})
<form role="search" id="default-search" action="#" novalidate>
<input class="number" name="price-from" placeholder="Cena od" maxlength = "11" min = "0">
<button type="button" id="btn">Submit number</button>
</form>
Using the Intl.NumberFormat object:
Another similar approach to do this would be to use the Intl.NumberFormat object along with the replace() method to automatically add comma separators to your input value and then converting them back to their original value when you want to submit the input value to your server like this:
$('input[name="price-from"]').on('input', function(e) {
e.target.value = new Intl.NumberFormat().format(parseInt(e.target.value.replace(/,/g, "")))
});
$('#btn').click(function() {
const valueToSubmit = parseInt($('input[name="price-from"]').val().replace(/,/g, ""));
alert("Submitting the value " + valueToSubmit);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="search" id="default-search" action="#" novalidate>
<input class="number" name="price-from" placeholder="Cena od" maxlength = "11" min = "0">
<button type="button" id="btn">Submit number</button>
</form>
With pure JavaScript, the above jQuery would look like this:
const input = document.querySelector('#default-search input[name="price-from"]');
const btn = document.getElementById('btn');
input.addEventListener('input', function() {
input.value = new Intl.NumberFormat().format(parseInt(input.value.replace(/,/g, "")))
});
btn.addEventListener('click', function() {
const valueToSubmit = parseInt(input.value.replace(/,/g, ""));
alert("Submitting the value " + valueToSubmit);
})
<form role="search" id="default-search" action="#" novalidate>
<input class="number" name="price-from" placeholder="Cena od" maxlength = "11" min = "0">
<button type="button" id="btn">Submit number</button>
</form>
How i can set value to jquery inseted set html code
in this question i set value on body
link
how i can set html code with input text and work like link
i write this code
<input type="text" style="width: 400px;height:400px;" class="in" /><br />
<input type="button" value="submit" onclick="myFunction()" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myFunction() {
var text = $("input:text").val();
console.log(text);//its ok but i don't how to use text in arr
var arr = $('ol li').map(function () {
var $li = $(this);
return {
value: $li.find('.Value').text(),
name: $li.find('.Name').text()
}
}).get();
console.log(arr);
}
</script>
</body>
</html>
Do you want set Text box value by jquery?
$('.in').val('your custom value or text');
First. For input multiline you need to use <textarea>
Then split string with
("Yourtext").split("Your Seperator",limit_arraysize);
//example
alert(("Howdy! I'm Flowey the flower").split(" ",3));
//That mean you split with " " (1 blank space)
OUTPUT:
[
"Howdy!"
,"I'm"
,"Flowey"
]
Some example below
function myFunction() {
var arr = [];
var text = $("textarea").val();
var submit = text.split("\n"); // USE TO split multiline
for (var i = 0; i < submit.length; i++) {
var temp = submit[i].split(",", 2);
arr[i] = {
value: temp[0],
name: temp[1]
};
}
console.log(arr);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea type="text" style="width: 400px;height:200px;" class="in">
25,ok
80,good
90,no</textarea>
<!--use TEXTAREA instead INPUT for multiline-->
<br>
<input type="button" value="submit" onclick="myFunction()" />
I'm trying to count the number of common letters between the user's input and the number generated. I am counting it so that the placement doesn't matter between them (so 411 and 004 should say "1 number in common").
I've placed my code in a snippet below. It works fine, except for that, when the generated string has two of the same numbers, it doesn't work properly. You can see that by typing "4", it will say that there are two chars. in common, when there is really only one (it counts the four twice.)
So, after all this, I'm asking what is the best way to show the common letters between the input and the generated number?
I'm fine with using jQuery and/or JavaScript, and sorry if my code isn't very good, I'm not very advanced at all.
Thanks for any help in advance! :)
// on ".check" click...
$(".check").click(function() {
var nmb = $(".number").text();
var ltr = $(".input").val();
var count = $(".cnt");
// Set logged text to 0
count.text("0");
// Test for numbers in common
if (ltr.includes(nmb.charAt(0))) {
count.html(function(i, val) {
return val * 1 + 1
});
}
if (ltr.includes(nmb.charAt(1))) {
count.html(function(i, val) {
return val * 1 + 1
});
}
if (ltr.includes(nmb.charAt(2))) {
count.html(function(i, val) {
return val * 1 + 1
});
}
if (ltr.includes(nmb.charAt(3))) {
count.html(function(i, val) {
return val * 1 + 1
});
}
$(".res1").html(" numbers in common");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" placeholder="Try typing 4 to see the issue" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
<span class="cnt"></span>
<span class="res1"></span>
</span>
First you can reduce each of the strings to only include unique characters, ie 4410 can be reduced to 410 as you don't need to test 4 more than once. You can do this by creating a Set of each string:
var numberSet = new Set(nmb);
var inputSet = new Set(ltr);
Then you can iterate over one of them, for least amount of iterations which ever is shortest, and use the has() method to see if that character was in the other Set
var counter = 0;
for(letter of inputSet){
if(numberSet.has(letter)){
counter++;
}
}
// on ".check" click...
$(".check").click(function() {
var nmb = new Set( $(".number").text() );
var ltr = new Set( $(".input").val() );
var count = $(".cnt");
var counter = 0;
for(let letter of nmb){
if(ltr.has(letter)){
counter++;
}
}
//No need to continually update text / html as each update wont be
//seen anyway so just set it once outside the loop.
count.text(counter);
$(".res1").html(" numbers in common");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" placeholder="Try typing 4 to see the issue" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
<span class="cnt"></span>
<span class="res1"></span>
</span>
You can do something like:
$(".check").click(function() {
var nmb = $(".number").text().trim().split(''); //Get the text and convert to string
var ltr = $(".input").val().trim().split(''); //Get the value and convert to string
var commonLetters = []; //The common letters will be stored on this variable
ltr.forEach(function(v) { //Loop thru the user's input letters
var idx = nmb.indexOf(v); //Find its index
if (idx !== -1) { //Check if found
commonLetters.push(4); //If found, push the letters to commonLetters
nmb[idx] = ''; //Clear the index
}
})
$(".cnt").text(commonLetters.length);
$(".res1").html(" numbers in common");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" placeholder="Try typing 4 to see the issue" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
<span class="cnt"></span>
<span class="res1"></span>
</span>
It's not entirely trivial. For example, you can't simply use filter or includes or has tests on their own because once a character is found, you have to remove it from each collection so it doesn't get matched again. I would use reduce and splice the array of characters to remove the found character every time a match is found. (No need for jQuery for this)
document.querySelector('.check').addEventListener('click', () => {
const numChars = [...document.querySelector('.number').textContent];
const inputChars = [...document.querySelector('.input').value];
const matchingCharCount = inputChars.reduce(
({ remainingNumChars = numChars, matchCount = 0 } = {}, inputChar) => {
if (remainingNumChars.includes(inputChar)) {
remainingNumChars.splice(remainingNumChars.indexOf(inputChar), 1);
matchCount++;
}
return { remainingNumChars, matchCount };
}, { remainingNumChars: numChars, matchCount: 0 })
.matchCount;
document.querySelector('.cnt').textContent = matchingCharCount;
document.querySelector('.res1').textContent = " numbers in common"
});
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
<span class="cnt"></span>
<span class="res1"></span>
</span>
Upon clicking a submit button, I would like to do some client side validation to ensure there are fewer than 5 commas in a text box with the class of submit-btn. I can use javascript, jquery and/or regex here.
What code should I place within this function?
$('.submit-btn').on("click", function() {
<< WHAT GOES HERE? >>
});
Any help is greatly appreciated.
I use regex to find the number of times the string , occurs in the textbox value. It prints whether or not it is valid (having less than 5 commas).
$("#validate").click(function () {
console.log(($("#textboxInfo").val().match(/,/g)||[]).length < 5)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textboxInfo" />
<button id="validate">less than 5 commas?</button>
Automatically responding to user input
In this particular situation, I'd prefer to have live validation. This can be accomplished by using the input event.
$("#textboxInfo").on('input', function () {
var isValid = ($(this).val().match(/,/g) || []).length < 5;
$(".isValid").html(isValid ? "Valid" : "Invalid");
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textboxInfo" value="I really love ,,, commas!" />
<div class="isValid"> </div>
Split the value of the input box and filter out , and check the length of it
$('.submit-btn').on("click", function() {
var getNumbers = $('#testBox').val().split('').filter(function(item) {
return item === ','
}).length;
console.log(getNumbers)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='testBox'>
<button class='submit-btn' type="button">Click</button>
You could try using this Comma Counter
$('button').on('click',function(){
var counter = ($('div').html().match(/,/g) || []).length;
$('.result').text(counter);
}
)/
You could also remove everything that is not a comma [^,], replace that with an empty string and count the length of the string.
$('.submit-btn').on("click", function() {
var nr = $("#tbx").val().replace(/[^,]/g, "").length;
console.log("Fewer than 5 commas? " + (nr < 5 ? "Yes" : "No") + " there are " + nr + " commas.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='tbx'>
<button class='submit-btn' type="button">Click</button>
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"/>