trying to clear value in textbox in javascript function - javascript

i am trying to put validation on a textbox onkeyup. Textbox should contain only 5 digit value and after decimal only upto 4 decimal places. eg,12345 ,12345.2345
if user enter value other than regex then the texbox should become blank and i want it to be done in function and this function should be generic so that any other can use this function
.Aspx
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this.value)" />
Script function
<script type="text/javascript">
function isFloatNumber(value) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
value = "";
return false;
}
return true;
}
</script>

function isFloatNumber(elem) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(elem.value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
elem.value = "";
return false;
}
return true;
}
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this)" />
<input type="number" id='inpSurfIndN1' value='' runat="server" onkeyup="isFloatNumber(this)" />
<input type="number" id='inpSurfIndN2' value='' runat="server" onkeyup="isFloatNumber(this)" />
You can use above snippet which will work for n numbers of inputs.

Updating value = ""; doesn't update the UI element. You should access the UI Element object by passing this and update the value like this.value = " " else you should use the selectors like document.getElementbyId() to access those object like document.getElementbyId('inpSurfIndN').value = ""

One of way you can use below logic,
function isFloatNumber(obj) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(obj.value);
if (regmatch == null || regmatch == false) {
alert("Please fil correct expression");
obj.value = "";
return false;
}
return true;
}
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this)" />

var n = document.getElementById("numPeople"),
r = document.getElementById("result");
n.addEventListener("keyup", function(e) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(n.value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
n.value='';
return false;
}
}, false);
<input id="numPeople" type="number" min="0" value="" placeholder="Pick a number" />

You cannot access the value variable which is passed as a parameter, it doesnt reference to the value of the input box
Instead you can access the element and change the value like below:
function isFloatNumber(eve) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
var elem = eve.currentTarget;
elem.value = "";
return false;
}
return true;
}

Related

Validating function with getElementById

I'm trying to use getElementById to validate both the quantity and price are integers. Any troubleshooting help would be appreciated. I've created a couple of inputs in HTML as well.
<body>
<section>
<p><input name="quantity" type="text" id="quantity"
placeholder="quantity" autofocus></p>
<p><input name="price" type="text" id="price" placeholder="price"></p>
</section>
<script>
quantity.addEventListener("blur", validate, false);
price.addEventListener("blur", validate, false);
function validate() {
box = this.id;
data = this.value;
thequantity = document.getElementById("quantity");
theprice = document.getElementById("price");
thetotal = document.getElementById("total");
if (data) {
error1 = thequantity.value.match(/[0-9\.]/);
error2 = thequantity.value.match(/[0-9\.]/);
if (!error1 && !error2) {
alert("Please enter a number");
price = Number(theprice.value);
quantity = Number(thequantity.value);
thetotal.value = thequantity.value * theprice.value;
}
if (error1) {
alert("Please enter a number");
document.getElementById(box).value = "";
}
if (error2) {
alert("Please enter a number");
document.getElementById(box).value = "";
}
} else {
var num = box.value(/[0-9]/);
document.getElementById(box).value = thetotal;
}
}
</script>
Just check if converting to a number does not result in NaN:
if (isNaN(Number(document.getElementById("quantity").value))) {
alert("Please enter a number.");
}

javascript - Merging checkboxes into one field in form

I would like to ask for help with function that merge checkboxes into one field. In question Combine checkbox values into string before submitting form I have found one but I would like it to start onsubmit with another function that checks if the form was filled correctlty.
Form:
<form id="formularz_wspolpraca" name="Zapis na poradnik" method="post" target="_top" onsubmit="return SprawdzFormularz(this) && mergeFunction(this)">
<input type="text" id="email" name="email"/>
<input type="text" id="imie" name="imie"/>
<input type="text" id="nazwisko" name="nazwisko"/>
<input type="text" maxlength="12" size="12" id="pole_1" name="pole_1"/>
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3a" value="polecajacy">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3b" value="projektant">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3c" value="instalator">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3d" value="ekspert">
<input type="hidden" name="pole_3" id="pole_3">
<input id="pp" type="checkbox" name="pp" checked=""/>
<input type="submit" value="Wyƛlij">
</form>
Merge function:
function mergeFuntion(event) {
event.preventDefault();
var boxes = document.getElementsByClassName('checkbox_wspolpraca');
var checked = [];
for (var i = 0; boxes[i]; ++i) {
if (boxes[i].checked) {
checked.push(boxes[i].value);
}
}
var checkedStr = checked.join(' ');
document.getElementById('pole_3').value = checkedStr;
return true;
}
Check function:
function SprawdzFormularz(f) {
if (f.email.value == "") {
alert("Nie poda\u0142e\u015b/a\u015b adresu e-mail.");
return false;
}
if (((f.email.value.indexOf("#", 1)) == -1) || (f.email.value.indexOf(".", 1)) == -1) {
alert("Poda\u0142e\u015b/a\u015b b\u0142\u0119dny adres e-mail.");
return false;
}
if (f.imie.value == "") {
alert("Wype\u0142nij pole Imi\u0119. ");
return false;
}
if (f.nazwisko.value == "") {
alert("Wype\u0142nij pole Nazwisko. ");
return false;
}
if (f.pole_1.value == "") {
alert("Wype\u0142nij pole Nr telefonu. ");
return false;
}
if ((f.pole_3a.checked == false) && (f.pole_3b.checked == false) && (f.pole_3c.checked == false) && (f.pole_3d.checked == false)) {
alert("Wybierz zakres wsp\u00f3\u0142pracy");
return false;
}
if (f.pp.checked == false) {
alert("Musisz zgodzi\u0107 si\u0119 z Polityk\u0105 Prywatno\u015bci.");
return false;
}
return true;
}
Check function is working without a problem but i can't get merge one to work as well. Can someone point out what am I doing wrong with merge function? I'm quite new to javascript so that could be some rookie mistake. Thanks in advance.
In onsubmit you are running SprawdzFormularz first and it returns true if all the checks pass. This means that it will submit the form, before the merge function is run.
You need to run the merge function inside the check function before returning true so that the form does not submit before you have combined the string and set the necessary value.
function SprawdzFormularz(f) {
// ....
var boxes = document.getElementsByClassName('checkbox_wspolpraca');
var checked = [];
for (var i = 0; boxes[i]; ++i) {
if (boxes[i].checked) {
checked.push(boxes[i].value);
}
}
var checkedStr = checked.join(' ');
document.getElementById('pole_3').value = checkedStr;
return true;
}

CustomValidator with Parameters

I'm validating a TextBox with a CustomValidator and JavaScript, passing it some paramaters:
<asp:CustomValidator ID="CustomValidator1" runat="server" SetFocusOnError="true" Display="Dynamic" ValidateEmptyText="true" ControlToValidate="tbFirstName" ClientValidationFunction="CVH.createFunction(notEmpty, 'tbFirstName','tbFirstNameRequired')"></asp:CustomValidator>
This is my JavaScript
var CVH = {
createFunction: function (validationFunction, extParamOne, extParamTwo) {
var originalFunction = validationFunction;
var extOne = extParamOne;
var extTwo = extParamTwo;
return function (src, args) {
return originalFunction(src, args, extOne, extTwo);
}
}
}
var CustomValidatorHelper = CVH;
function notEmpty(source, args, tbID, spID)
{
var textBoxId = document.getElementById(tbID);
var spanID = document.getElementById(spID);
if (textBoxId.Value == null || textBoxId.Value == "") {
textBoxId.IsValid = false;
textBoxId.className = "form-control redBorder"
spanID.className = "redText";
alert(textBoxId.getAttribute('value'));
}
else {
textBoxId.IsValid = true;
textBoxId.className = "form-control"
spanID.className = "";
alert(textBoxId.getAttribute('value'));
}
}
So notEmpty is being called correctly and it is receiving the values for tbID and spID.
Problem is, when I do enter data in the TextBox and the code is executed, I still get not value. As in textBoxId.Value is NULL even with data in the box.
The Texbox is set to Static:
<asp:TextBox ID="tbFirstName" runat="server" class="form-control" autocomplete="name" MaxLength="20" ClientIDMode="Static" />
And it's rendering correctly:
<input name="ctl00$MainContent$tbFirstName" type="text" maxlength="20" id="tbFirstName" class="form-control" autocomplete="name" />
Any suggestions as to why it can't read the data in the TextBox?
So the error was in trying to check the value of textbox directly as opposed of using args:
function notEmpty(source, args, tbID, spID)
{
var textBoxId = document.getElementById(tbID);
var spanID = document.getElementById(spID);
if (args.Value == "")
{
args.IsValid = false;
textBoxId.IsValid = false;
textBoxId.className = "form-control redBorder"
spanID.className = "redText";
}
else
{
args.IsValid = true;
textBoxId.IsValid = true;
textBoxId.className = "form-control"
spanID.className = "";
}
}
So the code is still the same, for exception of changing textbox.value for args.value.

How can I check if the input is empty in JavaScript? [duplicate]

This question already has answers here:
How do I check for an empty/undefined/null string in JavaScript?
(52 answers)
Closed 7 years ago.
I am trying to make a factorial calculator. How can I check if the input is empty or not? I tried 'null'. But it didn't work or I couldn't use it properly.
sorry for the stupid question. I am newbie in JavaScript
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function () {
if( !(isNaN(input))) {
var result = 1;
for(var i = 1; i <= input; i++ ) {
result = result * i
}
return result;
}
else if (input == null){
return "Please input a number"
}
else{
return "Please input a number"
}
}
document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p>
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function() {
if (input.trim() == '') {
return "Please input a number"
} else if (!(isNaN(input))) {
var result = 1;
for (var i = 1; i <= input; i++) {
result = result * i
}
return result;
}
}
document.getElementById("input2").value = ever();
}
<p>Input:
<input type="text" id="input1" />
</p>
<p>Input:
<input type="text" id="input2" />
</p>
<button onclick="myFriday()">Calculate</button>
<p>RESULT: <span id="result" style="color:red"></span>
</p>
is that what you looking for?
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function () {
if(input.match(/\D/) == null){ // changes made here
var result = 1;
for(var i = 1; i <= input; i++ ) {
result = result * i
}
return result;
}
else{ // one else is enough
return "Please input a number"
}
}
document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p>
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>
When you use .value you get a string value in return.
This means that when you enter nothing in the input it'll return ""
So you should change this piece of code
input == null
Into this
input === ""
Note that I also wrote === instead of ==
Using === in javascript is faster than == when the objects are of the same type.

Js validate multipe input fields with same name

Ok i have multy fields with same name, and i want to check is all fields are not empty. My code works if i have only one input, but i have no idea how to do that with more inputs
<input class = "new_input" type=text name="name[]"/>
<input class = "new_input" type=text name="name[]"/>
function validation(){
var x = document.forms["form"]["name"].value;
if(x ==='')
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
return false;
}
else
{
return true;
}
}
for example if enter only one field, validation will work, and i want to check all fields
Using just JS you could do something like
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<button onclick="validate()">Validate</button>
<script type="text/javascript">
function validate() {
var inputs = document.getElementsByTagName("input");
var empty_inputs = 0;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('name') == 0) { // check all inputs with 'name' in their name
if (inputs[i].value == '') {
empty_inputs++;
console.log('Input ' + i + ' is empty!');
}
}
}
if (empty_inputs == 0) {
console.log('All inputs have a value');
}
}
</script>
You have tagged jquery, so I have given something which works in jquery
http://jsfiddle.net/8uwo6fjz/1/
$("#validate").click(function(){
var x = $("input[name='name[]']")
$(x).each(function(key,val){
if($(val).val().length<=0)
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
}
});
});
Try this:
function validate(){
var error = 0;
$.each( $("input[name='name[]']"), function(index,value){
if( value.value.length == 0){
$("#warning").html("Morate uneti vrednost!").css('color','red');
error = 1;
return;
}
});
if(!error){
$("#warning").html("");
}
}
Check it out here: jsFiddle

Categories