I have text boxes where id for these boxes are from 1 to 20. These boxes are created in PHP for loop.
How can i check using javascript if these textboxes are empty. and throw an error on each box.
foreach(i = 0, i<20, i++)
{
<input type = "Text" id="q_i">
}
Use jQuery?
$('input[type=text]').each(function(){if ($(this).val() == '') alert("Your Message Here");});
or, if there are other inputs you don't want to process:
$('[id^="q_"]').each(function(){if ($(this).val() == '') alert("Your Message Here");});
Without jQuery (and using jQuery would be easier):
foreach(i = 0, i<20, i++)
{
if (document.getElementById('q_' + i).length == 0) {
alert('box ' + i + 'is empty!');
}
}
document.getElementsById('q_'+i)[0].value.length > 0
in a for loop ought to roughly do it.
(though dropping jQuery into your project would probably be a better plan)
Then you could iterate over a class. i.e.
foreach(i = 0, i<20, i++)
{
<input type = "Text" id="q_i" class="q">
}
and in your Javascript:
$("q").each(function(index,object){
if(object.value().length <= 0) alert('empty!');
});
Here is a basic form validation that might be what you're looking for
It uses an invisible error message that shows up when you leave an empty field after you push the button. It doesn't accept white spaces. You can validate it multiple times and it behaves as expected
Here's the jquery part:
$(document).ready(function() {
$("button").click(function()
{ $('span[id^=q_]').addClass("hidden");
$('input[id^=q_]').each(function()
{if ($(this).val().replace(/ /g,'') == '')
{ $("#"+$(this).attr('id')).removeClass("hidden");
}
});
});
});
html part:
<style>.hidden{display:none;}
.visible{display:block;}
</style>
<span id="q_1" class="hidden">Missing text</span>
<input type = "Text" id="q_1">
Not very pretty but it does the job
Related
Very much appreciated if you can help me since I am a newbie on this.
I have a huge html table with more than 10 columns and around 20 rows.
I want to do a javascript cycle to verify the inputs of all the rows. My strategy was to insert Ids in each in which each row's id always increases +1. For example:
<td><input id="ingredient_percentage_1" type="text" name=" " form="form1" />%</td>
<td><input id="ingredient_percentage_2" type="text" name=" " form="form2" />%</td>
The code I've done is like this:
function verifyPercentages(){
var total = 0;
var i;
if (batch.value === "") {
alert ("Please insert value in Batch Size field");
return false;
}
else {
for (i=1; i<19; i++){
var percentage = document.getElementById('ingredient_percentage_'+i);
if( (((i>1) && (i<5)) || (i==11) || (i==13)) && (percentage.value == "")) {
alert ("Mandatory fields are not filled up");
return false;
}
if ((i>6) && (i<9) && (percentage.value == "")) {
alert ("Please select an option in the Product type field above");
return false;
}
if ((i>8) && (i<11) && (percentage.value >= 1)) {
alert ("Please make sure that the percentages for oil are less than 1%");
return false;
}
if ((i>14) && (i<17) && (percentage.value >= 1)) {
alert ("Please make sure that (...)");
return false;
}
if (percentage == null) continue;
}
calculatePercentages();
}
}
But I feel that is not very optimized. Is there a more efficient/clean way to do this?
Many thanks
Not wanting to interfere with your tech choices, but you could do this very easily (and robust!) with built in html5 validation. It will work on all modern browsers. You can do more this way than you probably believe. One example of how an email input field in a form could be validated:
<input
id="useremail"
type="text"
placeholder="your.email#example.com"
required
minlength="6"
maxlength="90"
pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$"
title="Wrong email address format">
Result when error is thrown on Chrome/Brave/Chromium:
A more precise error text above, albeit onerous, would be "The email must contain between 5 and 89 alphanumeric characters plus the '#'".
In order to run your function when the form fully validates you can add it into your submit event like so:
const submitButton = document.querySelector('.btn-submit')
submitButton.addEventListener('click', (e) => {
e.preventDefault()
calculatePercentages()
})
One alternative is to use Javascript's querySelectorAll with enumeration. Also, many other approaches. In the example below I provide alternative ways to iterate over the HTML elements. I comment where the respected logic should go
The bottom example uses the querySelectorAll to match partially matching id string name values.
The below selector example means to locate an element where the attribute id that does begin with the string "ingredient_".
Implementations Documentation
Document Query Selector All
Document Query Selector
Note
^ matches the start
* matches any position
$ matches the end
Edits: Comparison element.value == "" may cause unexpected type coercion. That is why you may notice the if statement logic changed a little from your initial code provided.
function verify() {
elements = document.querySelectorAll(`[id ^= "ingredient_`);
Array.prototype.forEach.call(elements, callback);
function callback(element, i) {
if ((((i > 1) && (i < 5)) || (i === 11) || (i === 13)) && (element.value === "")) {
// Logic
}
if ((i > 6) && (i < 9) && (element.value === "")) {
// Logic
}
if ((i > 8) && (i < 11) && (element.value >= 1)) {
// Logic
}
if ((i > 14) && (i < 17) && (element.value >= 1)) {
// Logic
}
// Debug
console.log('i:', i, 'id:', element.id, 'value:', element.value)
}
}
verify();
<td><input id="ingredient_percentage_1" type="text" name=" " value="1" form="form1" />%</td>
<td><input id="ingredient_percentage_2" type="text" name=" " value="2" form="form2" />%</td>
My code's function is to alert user if the ptype textfield is empty.
$("input[name*='ptype']").each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
However, I need to add another criteria where another field amount is not 0. So that the function get triggered when ptype="" && amount!=0. I'm very new in jQuery, and I'm not sure how to use AND operator in here. I've tried to do some based on other questions but it seems not working.
$("input[name*='ptype'][amount!='0']").each(function() {
$("input[name*='ptype'] , [amount!='0']").each(function() {
What am I missing ?
You can do it with && sign. Code depends on where your amount field is located and what it is. If I guess right it should be something like this:
$("input[name*='ptype']").each(function() {
if ($(this).val() == "" && $(this).parent().find(input[name='amount']).val() != 0) {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
That code $("input[name*='ptype'][amount!='0']").each(function() { is valid. You have to check the CSS selectors list.
The problem maybe in your *= selection. input[name*="ptype"] means Selects every element whose name attribute value contains the substring "ptype".
$('input[name*="ptype"][amount!="0"]').each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
Take a look at this test https://jsfiddle.net/xpvt214o/211871/
« where another field» is the key in question.
So you need a selector to check if a selected element is empty and another element is not zero.
Holà!
Logic problem here.
with $(selector) you can look up for some elements.
There is no AND / OR in selectors for many sets of matching element.
A selector is ONE set of matching elements.
No way this selector can check for an attribute value of another set.
So you have to know your markup and navigate a bit... And take care of variable types.
$("input[name*='ptype']").each(function() {
if ( parseInt( $(this).next("input").val() ) != 0) {
$(this).css({"background-color" : "red"});
alert("Enter Value!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ptype: <input type="text" name="ptype"><br>
amount: <input type="text" name="amount" value="1">
You have to look for another element's value here, from my understanding. So you have to know what is that "other" element and the methods to use may vary a lot depending on your HTML...
You can use this function in your button.
function check(e){
var verror = false;
$("input[name*='ptype']").each(function(index, value) {
var amount = $($("input[name='amount[]']").get(index)).val();
var ptype = $(this).val();
if(ptype.length <= 0 && amount.length > 0 ){
verror = true;
$(this).focus();
return false;
}
});
if(verror){
e.preventDefault();
alert("Enter Value!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="1"> <br>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="2"> <br>
<button type="button" onclick="check(event)">Click</button>
</form>
I am adding multiple controls on an .aspx page from the .vb page based on certain conditions.
My code looks like following:
Dim sb As New StringBuilder
sb.Append("<table border='0'cellpadding='0' cellspacing='0' width='50%' class ='tabledata' id='tblContent'>")
For Each item As myObject In myLst
sb.Append("<tr><td style='width:50%;' valign='top'>")
sb.Append("<textarea id=txt_comments" & i & " name='txt_comments' rows='5' cols='60'></textarea></td>")
sb.Append("<td style='width:15%' valign='top' align='center'><select ID = validate" & i & " name=ValidateValues style ='border:1;width:150px'><option value = ''>Select</option><option value = 'Yes'>Yes</option><option value = 'No'>No</option><br /><br /></td>")
sb.Append("</tr><tr>")
Next
sb.Append("</table>")
myContent.InnerHtml = sb.ToString
So here I am creating <textarea> and <select> dynamically and adding them to my div(myContent)
<div id="structuredContent" runat="server">
</div>
I have a button next where I need to validate for few conditions.
My validation rule is:
User has to select either yes or no from the dropdown(<select>)
If user select 'yes', they have to enter text in
<textarea>(minimum1 character, maximum 1000 characters)
If user select 'No', <textarea> should be disabled.
I am trying to validate like following:
function validateComments() {
var errorcheck = 0;
$("[id^=txt_comments]").each(function () {
var comment = $.trim($(this).val());
$("[id^=validate]").each(function () {
debugger;
var value = $(this).val();
if (comment == 0 && value == "Yes") {
debugger;
errorcheck = 1;
}
});
}); if (errorcheck == 1) {
//show error message
}
else {
ErrorHide();
return true;
}
}
I am able to validate only for one control(which is textarea) from the above code.
The textbox and respective dropdown should be validated along.
How do I add validation for dropdown and can I combine with in the same function.
Any help?
Thanks in advance.
I don't know how do you expect this like if (comment == 0) { to work.
You'll always get a string as a value and checking it with 0 would always return false. Rather you need to check it with "".
And to enable/disable textarea you'll have to attach an event to select tag and do whatever you want to do.
here is an example
$("#d").change(function(){
if($(this).val() === 'n'){
$("#t").prop('disabled', 'disabled')
}else{
$("#t").prop('disabled', false)
}
});
$('body').on('click', '#b', function() {
var text = $.trim($("#t").val());
if(text === "" && !$("#t").prop('disabled')){
alert("yo! not valid")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="d">
<option value="0">Select</option>
<option value="y">Yes</option>
<option value="n">No</option>
</select>
<textarea maxlength="50" id="t"></textarea>\
<button id="b">Validate</button>
My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/
The following function loops through form elements to validate they've been filled in. The bestresult element is optional and if there's no user input, value of 0 should be inserted into to the form element. When I submit the form, fields with empty elements are submitted to the server instead of alerting user to provide values. Any thoughts?
function validateForm()
{
//Validates that form elements are not empty
for(var i=0; i < document.results.elements.length; i++)
{
if(document.results.elements[i].value == null ||
document.results.elements[i].value == "")
{
if(document.results.elements[i] == document.results.besttime)
{
document.results.elements[i].value = 0;
}else
{
alert("Error " + document.results.elements[i].getAttribute("name") + " must be given a value");
return false;
}
}
}
The function itself is fine. I've discovered there's been a problem with a regular expression which is not included in the code snippet