[Visualforce page] I have 3 input fields with class name rowStyle3 and it accepts numberic character only.
When the user enters a non-numeric character, I want the only invalid input field is cleared.
please help me to correct code snippet below.
Thanks a lot
<script>
$(document).ready(function() {
$(document).on("change", ".rowStyle3", function() {
$('.rowStyle3').each(function() {
var num = $(this).val();
if(num != "" && isNaN(num)){
$(".rowStyle3").val(''); -> All values of input fields will be cleared if one of them is invalid
alert("Allow numbers only !");
}
});
});
});
</script>
This should do the trick.
$(document).ready(function() {
$(document).on("change", ".rowStyle3", function() {
$('.rowStyle3').each(function(row) {
var num = row.val();
if(num != "" && isNaN(num)){
row.val('');
alert("Allow numbers only !");
}
});
});
});
Instead of doing $.(this) you can use the enumerated value of the foreach.
You can use ValidityState to check whether input element is invalid or not:
if (!inputElement.validity.valid) {
inputElement.value = '';
}
This checks whether the inputElement input is invalid, if so, it clears it. InputElement should be something like (given that your input id is name):
inputElement = document.getElementById("name")
Related
how to get the search input to recognize that there is a string of input?
the code below works but even without entering any input it still does the search if I click search or enter. In other words even if the search input is blank it still searches. This is just a project, anyone has any ideas?
<input type="text" id="textInput" name="" class="query">
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
Simply check for a (valid) length, either greather than zero or greater than maybe three characters for any meaningful results (depends on your searches).
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
if(query.value.trim().length){ // maybe length>3 ?
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
You have to check if the value of input exists or it is not empty.
You can also check:
input.value.length
input.value !== ""
input.value
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function() {
let url = 'https://www.google.com/search?q=' + query.value;
window.open(url, '_self');
}
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13 && input.value) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
<input type="text" id="textInput" name="" class="query">
<button class="searchBtn">Search</button>
Working Fiddle
If you wrap your inputs in a <form></form> you can use HTML5's built in validation.
In my example:
pattern="[\S]+" means all characters except space are valid
required means the input length must be at least 1 valid character
Also, I'm toggling the button's disabled property based on the input's validity. In my opinion it makes for a better user experience letting the user know something is incorrect BEFORE clicking the button.
let button_search = document.querySelector('button.search');
let input_query = document.querySelector('input.query');
button_search.addEventListener('click', function() {
if (input_query.validity.valid) {
window.open('https://www.google.com/search?q=' + input_query.value, '_self');
}
});
input_query.addEventListener('keyup', function(event) {
button_search.disabled = !input_query.validity.valid; //visual indicator input is invalid
if (event.keyCode === 13) {
button_search.click();
}
});
<form>
<input class="query" pattern="[\S]+" required>
<button class="search" disabled>Search</button>
</form>
Last thought, unless there is a specific reason you need to run your code in separate scopes, you can put all of your code in a single <script></script>
From this example
I tried to validate user input when a button was clicked.
$("#check_data").click(function () {
var $userInput = $('#user_input'); //from HTML input box id="user_input"
var pattern = " /*My user input always be like "AB1234567"*/ ";
if ($userInput.val() == '' || !pattern.test($userInput.val())) {
alert('Please enter a valid code.');
return false;
}
});
My user input input always be like "AB1234567" with this exact same characters but different 7 digits number.
I'm new to Javascript and Jquery, if you have any better way to validate user input, please suggest it.
Thank you.
You can use below regex Expression to check
/[A-Za-z0-9]/g
Your code could be like this
var _pattern=/[A-Za-z0-9]/g
if($userInput.val().match(_pattern))
{
//your code goes here..
}
Thanks
You can use the below pattern to check
/^AB\d{7}$/
You can change code to
var pattern = '/^AB\d{7}$/';
if ($userInput.val() == '' || !pattern.test($userInput.val()))
{
alert('Please enter a valid code.');
return false;
}
\d{7} matches 7 digits in the range [0-9]
You can follow below code for this:
if ($userInput.val().match(/[^a-zA-Z0-9 ]/g))
{
// it is a valid value.
} else {
// show error here
}
Hope it helps you.
Try this one.
$("#check_data").click(function(){
var $userInput = $('#user_input').val();
var pattern = /^AB[0-9]{7}?/g;
if(!$userInput.match(pattern)){
alert('Please enter a valid code.');
return false;
}
});
I have the following code which checks if the values of inputs, textareas and selects are blank, but rather than making functions for each I've tried to store them all into one variable using an array.
But, when the click handler is activated, something is causing the error message to appear even when all inputs on the page are filled in.
Anyone know what might be causing this?
HTML:
$('#saveInvoice').click(function(e) {
e.preventDefault();
var $fields = [ $('input'), $('textarea'), $('select') ];
var $emptyFields = $fields.filter(function() {
return $.trim(this.value) === "";
});
if (!$emptyFields.length) {
saveInvoice();
} else {
alert('Unable to save invoice. There are incomplete item fields.');
}
});
Replace this.value with this.val()
Try the following ...
$('#saveInvoice').click(function(e) {
e.preventDefault();
var $fields = [ $('input'), $('textarea'), $('select') ];
var $emptyFields = $fields.filter(function(element) {
return $.trim(element.val()) === "";
});
if (!$emptyFields.length) {
saveInvoice();
} else {
alert('Unable to save invoice. There are incomplete item fields.');
}
});
you should be getting the value of array elements
You have two problems.
first : Jquery selectors. You've taken array of elements. $('input') gives you nodelist of all the inputs. you need to specify index of input you want to access value. for example $("input")[0] gives you first input found on your page.
second : You need to pass item to filter callback function. inside callback of filter this refer to window.
$('#saveInvoice').click(function(e) {
e.preventDefault();
var $fields = [ $('input')[0], $('textarea')[0], $('select')[0] ];
var $emptyFields = $fields.filter(function(ele) {
console.log(ele.value);
return $.trim(ele.value) === "";
});
if (!$emptyFields.length) {
//saveInvoice();
} else {
alert('Unable to save invoice. There are incomplete item fields.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Input : <input type=""><br>
TextArea: <textarea></textarea><br>
Select: <select><option value="1">A</option></select>
<button id="saveInvoice">Save</button>
</form>
I am managing to check the value inside a postcode input field using the following:
html:
<input type="text" class="cart-postcode2" size="10" tabindex="22">
JQuery:
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.indexOf('BT') >= 0) {
alert("is ireland");
}
})
This is working great however I want it to only alert if it starts with BT and does not contain BT in any part of the value, does anyone know if this is possible?
So typing BT2 9NH will alert "Ireland" but typing OX2 8BT will not
You can check if string starts with BT, as indexOf() will give index zero if value stats with BT
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.indexOf('BT') == 0) {
alert("is ireland");
}
})
a regex solution:
$('.cart-postcode2').keyup(function(){
var value = $(this).val();
if (value.match(/^BT/)) {
alert("is ireland");
}
})
I have HTML form with input fields. Some of inputs can be empty, i.e. the value is "".
<input name="commentary" value="">
Just now, when commentary field is not set, it appears in submit url like: &commentary=
How I can remove empty inputs from the submit url, so when the commentary input is empty it would not be passed at all.
Thank you very much.
Update
Thanks to minitech answer, I could resolve it. JavaScript code is below:
$('#my-form-id').submit(function() {
var commentary = $('#commentary').val();
if (commentary === undefined || commentary === "") {
$('#commentary').attr('name', 'empty_commentary');
} else {
$('#commentary').attr('name', 'commentary');
}
});
The only reason I have prefixed field name with "empty_" is that IE passes empty name in URL anyway.
This can only be done through JavaScript, as far as I know, so if you rely on this functionality you need to restructure. The idea, anyway, is to remove the name attribute from inputs you don’t want included:
jQuery:
$('#my-form-id').submit(function () {
$(this)
.find('input[name]')
.filter(function () {
return !this.value;
})
.prop('name', '');
});
No jQuery:
var myForm = document.getElementById('my-form-id');
myForm.addEventListener('submit', function () {
var allInputs = myForm.getElementsByTagName('input');
for (var i = 0; i < allInputs.length; i++) {
var input = allInputs[i];
if (input.name && !input.value) {
input.name = '';
}
}
});
You might also want to reset the form afterwards, if you use a listener and cancel.
I prefer not to alter the input elements (changing their names, or flagging them as disabled and so), because if you go back you could get a broken form.
Here is my solution instead, which relies on FormData:
window.addEventListener('load', function() {
let forms = document.getElementsByClassName('skipEmptyFields');
for (let form of forms) {
form.addEventListener('formdata', function(event) {
let formData = event.formData;
for (let [name, value] of Array.from(formData.entries())) {
if (value === '') formData.delete(name);
}
});
}
});
You probably don't want to match radio buttons. And if the form contains select's, you'll need to match them too.
With jQuery, you might use something like this:
$('#form-id').submit(function() {
$(this).find('input[type!="radio"][value=""],select:not(:has(option:selected[value!=""]))').attr('name', '');
});
Instead of using a submit-type input, use a button-type input for form submission. The JavaScript handler for the button-type input should call form's submit() method after checking that commentary is non-empty. You should also alert the user to their mistake (better with a red text on the page rather than the pop-up produced by alert()).
Remember that you should not rely solely on client-side input validation, though since it is always possible to send the form from a modified page or directly in HTTP.
Thankyou #Ryan
This is my full solution for this.
I use Jersey and #BeanParam and this fixes the problem of "" & null inputs
$('#submitForm').click(function() {
var url = "webapi/?";
var myForm = document.getElementById('myFormId');
var allInputs = myForm.getElementsByTagName('input');
for (var i = 0; i < allInputs.length; i++) {
var input = allInputs[i];
if (input.value != "" && input.name != "submitForm") {
url += input.name +'='+input.value+'&';
}
}
console.log(url);
$.ajax({
method : "GET",
url : url,
data : {
// data : "json",
// method: "GET"
},
success : function(data) {
console.log("Responce body from Server: \n" + JSON.stringify(data));
$("#responce").html("");
$("#responce").html(JSON.stringify(data));
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log('Error: ' + errorThrown);
}
});
});