Form Validation Loop to check all text and select not empty - javascript

function validatForm(){
$("#add_form input[type=text]").each(function() {
if(this.value == null || this.value == '') {
$(this).addClass("alert_focus");
alert('Required Field Cannot Be Emmpty')
$("html, body").animate({ scrollTop: $(this).offset().top }, 500);
}
});
<form id="add_form">
<table>
<tr>
<th>Select*</th>
<th>Field A*</th>
<th>Field B*</th>
<th>Field C*</th>
<tr>
</tr>
<td><select class="select" name="select1">
<option value="" selected>Please Select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</td>
<td><input type="text" name="a_field1" /></td>
<td><input type="text" name="b_field1" /></td>
<td><input type="text" name="c_field1" /></td>
</tr>
<tr>
<td><select class="select" name="select2">
<option>Please Select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</td>
<td><input type="text" name="a_field2" /></td>
<td><input type="text" name="b_field2" /></td>
<td><input type="text" name="c_field2" /></td>
</tr>
<tr>
<td><select class="select" name="select3">
<option>Please Select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</td>
<td><input type="text" name="a_field3" /></td>
<td><input type="text" name="b_field3" /></td>
<td><input type="text" name="c_field3" /></td>
</tr>
............ and so on.
</table>
Submit
<input type="hidden" value="submit" value="submit" />
</form>
The above works well so far for input[type="text"].
Is there anyway I can check if any of the select is empty/not_selected and identify that element?
I have tried:
$(".select").each(function() {
if (!$(".select option:selected").length) {
alert('Required Field Cannot Be Emmpty')
$("html, body").animate({ scrollTop: $(this).offset().top }, 500);
}
});
return false;
But it doesn't seems to work.
Your help is appreciated :)
Many Thanks
With the help from RobG, here is the script that works:
<script>
function validatForm(){
$("#add_cat input[type=text]").each(function() {
if(!this.value) {
$(this).addClass("alert_focus");
alert('Required Field Cannot Be Emmpty');
$("html, body").animate({ scrollTop: $(this).offset().top }, 500);
}
});
$('#add_cat select').each(function(i, select){
if (select.selectedIndex <= 0) {
alert('Please select an option');
}
return false;
});
};
</script>

If you want to iterate over the select elements, the selector is: 'select'.
jQuery's each is different to the built–in Array forEach method, the parameters are index, element rather than element, index which might be expected.
You can compare the select's value to '' (empty string), however since nearly all browsers will select the first option by default, a better strategy is to set the first option to the default selected and check that, e.g.
<select name="...">
<option value="" selected>Select one
<option value="one">one
</select>
then:
$('select').each(function(i, select){
if (select.selectedIndex <= 0) {
alert('Please select an option');
}
});
The selected index will be -1 if no option is selected, that shouldn't happen often but needs to be accommodated.

You need to use element selector(select) not class selector(.select), then you can see whether it have a value instead of checking whether there is a selected option
$("select").each(function () {
if (!$(this).val().length) {
alert('Required Field Cannot Be Emmpty')
$("html, body").animate({
scrollTop: $(this).offset().top
}, 500);
}
});

Related

How can I add/remove select boxes from DOM when all select boxes have one name so that upon Submit I get value from active select box?

TL;DR: I want to be able to make a selection using currently-active HTML select box, when I have multiple select boxes with the same name, but only one of them is to be active at any one time.
--
My question is this - I have multiple filename select boxes, that upon submit, always send the value of the last select box that is at the bottom of HTML that has filename name in HTTP Request. I want to find a way to send only the filename that is associated with the currently-active a_XX_row box, and not any others.
i.e. I select id of 40, I should only see the box that says "A-40 Designer and Specs", and not the 800 box. When I press submit I want POST['filename'] to have the "A-40 Designer and Specs", but instead I always get the "A-800 Designer E.xlsm", because it is the last select in the HTML file.
$('#modelid').on('change', function() {
if (this.value == 40)
$('.a_40_row').show();
else
$('.a_40_row').hide();
if (this.value == 800)
$('.a_800_row').show();
else
$('.a_800_row').hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--
<option value="40">40
<option value="800">800
</select>
</td>
</tr>
<tr class="a_40_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option selected>A-40 Designer and Specs B.xlsm</option>
<option>A-40 Designer and Specs A.xlsm</option>
</select>
</td>
</tr>
<tr class="a_800_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option>A-800 Designer E.xlsm</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
don't show/hide selects form.
you just need to update the second select when the first is changed
the way to do that:
const
myForm = document.forms['my-form']
, filenames =
[ { model: '40', cod: 'A-40-B', fn:'A-40 Designer and Specs B.xlsm' }
, { model: '40', cod: 'A-40-A', fn:'A-40 Designer and Specs A.xlsm' }
, { model: '800', cod: 'A-800-E', fn:'A-800 Designer E.xlsm' }
]
myForm.modelid.onchange = () =>
{
myForm.filename.innerHTML = ''
filenames
.filter(x=>x.model===myForm.modelid.value)
.forEach( filename=>
{
myForm.filename.add( new Option(filename.fn,filename.cod))
}
)
}
select,
button {
display : block;
float : left;
clear : left;
margin : .3em;
}
select {
min-width : 8em;
padding : 0 .3em;
}
<form name="my-form">
<select name="modelid" >
<option value="" selected disable >--select--</option>
<option value="40" > 40 </option>
<option value="800" > 800 </option>
</select>
<select name="filename"></select>
<button type="submit">submit</button>
</form>
Two options,
Enable/disable the element as you show it.
Populate one field with what you need.
Option 1 :
$('#modelid').on('change', function() {
//Set visibility
$('.a_40_row').toggle(this.value == 40);
//Toggle disabled
$('.a_40_row [name=filename]').prop("disabled", this.value != 40);
$('.a_800_row').toggle(this.value == 800)
$('.a_800_row [name=filename]').prop("disabled", this.value != 800);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--</option>
<option value="40">40</option>
<option value="800">800</option>
</select>
</td>
</tr>
<tr class="a_40_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename" disabled>
<option selected>A-40 Designer and Specs B.xlsm</option>
<option>A-40 Designer and Specs A.xlsm</option>
</select>
</td>
</tr>
<tr class="a_800_row" style="display: none;">
<td>Version</td>
<td>
<select name="filename" disbled>
<option>A-800 Designer E.xlsm</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>
Option 2 : - This uses HTML 5 which has issues in IE 10 and less
$('#modelid').on('change', function() {
$(".row").show();
var selVal = $(this).val();
//Go through the options
$("[name=filename] option").each(function(){
//Dont use jquerys data here, it will convert to a number when it can
//Get array of values where can display from the data attribute
var arrDisplay = this.dataset.display.split(",");
//Add the hidden property if not contained in array -- wont work in IE 10 and older
$(this).prop("hidden", !arrDisplay.includes(selVal));
//Set a default
$(this).prop("selected", $(this).data("optiondefault") && !arrDisplay.includes(selVal) )
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form><table>
<tr>
<td>
<select name="id" id="modelid">
<option value="0">--select--</option>
<option value="40">40</option>
<option value="800">800</option>
</select>
</td>
</tr>
<tr class="row" style="display: none;">
<td>Version</td>
<td>
<select name="filename">
<option data-display="40" data-optiondefault="true">A-40 Designer and Specs B.xlsm</option>
<option data-display="40">A-40 Designer and Specs A.xlsm</option>
<option data-display="800" data-optiondefault="true">A-800 Designer E.xlsm</option>
<option data-display="40,800">Hybrid</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit"></td>
</tr>
</table></form>

Using javascript to make something required

As part of the form I have created users can select whether they want their order posted or to collect them. The appropriate div is shown when they make their choice from the radio buttons, i.e when they choose postage the inputs for them to enter their delivery address appears, and if they select collection a drop down box appears for them to pick the shop where they want to collect.
So am I trying to make it that the inputs or the drop down box be required by using JavaScript but what I am doing is not working and I can't see why as I have done similar things before and it has worked with no issues.
This is the html:
<p>Would you like postage(£7.25 extra) or to collect from one of our shops?</p>
<label class="checkbox-inline"></label>
<input type="radio" required name="delivery[]" onchange="calc()" class="deliv" id="delivery" data-descTarget="k_0" value="7.25">Postage
<label class="checkbox-inline"></label>
<input type="radio" name="delivery[]" class="deliv" onchange="calc()" id="collection" data-descTarget="k_1" value="0"/>Collection
<div id="k_0" class="desc">
<label>Please enter your delivery address</label>
<table border="0" cellpadding="0" id="table2">
<tr>
<td align="right">Name</font></td>
<td><input type="text" name="name1" id="name" size="15" tabindex="1"></td>
</tr>
<tr>
<td align="right">Email</font>
(Your confirmation will be sent here): </td>
<td><input type="text" name="email1" id="email" size="20" tabindex="1"></td>
</tr>
<tr>
<td align="right">Phone number:</td>
<td><input type="text" name="number1" id="number" size="15" tabindex="1"></td>
</tr>
<tr>
<td align="right">Address:</td>
<td><input type="text" name="address1" id="address" size="15" tabindex="1"></td>
</tr>
<tr>
<td align="right">Town:</td>
<td><input type="text" name="town1" id="town" size="15" tabindex="1"></td>
</tr>
<tr>
<td align="right">Postcode:</td>
<td><input type="text" name="postcode1" id="postcode" size="15" tabindex="1"></td>
</tr>
<tr>
<td align="right">County:</td>
<td><input type="text" name="county1" id="county" size="15" tabindex="1"></td>
</tr>
</table>
</div>
<div id="k_1" class="desc">
<div class="select-style">
<label>Collection Point</label>
<select id="collect" name="collect">
<option value="None" selected="selected">Select One</option>
<option value="Alford" >Alford</option>
<option value="Auld Toon" >Auld Toon</option>
<option value="Banff" >Banff</option>
<option value="Emmas">Emmas</option>
<option value="Insch" >Insch</option>
<option value="Kemnay" >Kemnay</option>
<option value="Market Place" >Market Place</option>
<option value="Mastrick"> Mastrick</option>
<option value="Meldrum Bakery" >Meldrum Bakery</option>
<option value="North Street" >North Street</option>
<option value="Rousay" >Rousay</option>
<option value="Seafield Street" >Seafield Street </option>
<option value="St Machar" >St Machar </option>
<option value="St Swithin" >St Swithin Street </option>
<option value="Stonehaven" >Stonehaven</option>
<option value="Torry" >Torry</option>
<option value="Keystore Old Aberdeen" >Keystore Old Aberdeen</option>
<option value="Keystore Old Meldrum" >Keystore Old Meldrum </option>
<option value="Highclere" >Highclere</option>
</select>
</div>
</div>
<input type='submit' id='submit' name="submit" onClick="checkValue()" class="submit" value='Submit' />
This is the script that hides the divs until the appropriate radio button is selected:
<script type="text/javascript">
$(document).ready(function() {
$("div.desc").hide();
$("input[name$='delivery[]']").click(function() {
var choice = $(this).attr("data-descTarget");
$("div.desc").hide();
$("#" + choice).show();
});
});
</script>
This is what I have tried for making the fields required:
function checkValue() {
if (document.getElementById('delivery').checked) {
document.getElementsByName("name1").required = true;
document.getElementsByName("email1").required = true;
document.getElementsByName("number1").required = true;
document.getElementsByName("address1").required = true;
document.getElementsByName("town1").required = true;
document.getElementsByName("postcode1").required = true;
document.getElementsByName("county1").required = true;
document.getElementById("collect").required = false;
} else if (document.getElementById('collection').checked) {
document.getElementById("collect").required = true;
document.getElementsByName("name1").required = false;
document.getElementsByName("email1").required = false;
document.getElementsByName("number1").required = false;
document.getElementsByName("address1").required = false;
document.getElementsByName("town1").required = false;
document.getElementsByName("postcode1").required = false;
document.getElementsByName("county1").required = false;
}
}
Where have I gone wrong with the checkValue script?
I've used JQuery here as you are using it already, but this function will update the inputs like you are looking for and to make it easier to update and add/remove fields I used an array of input id's to loop through rather than hardcoding each one as you are.
function updateRequiredFields (isCollecting){
var deliveryFields = ["name","email","number", "address", "town", "postcode", "county"];
for(var x = 0; x < deliveryFields.length; x++){
$("#" + deliveryFields[x]).attr("required", !isCollecting);
}
$("#collect").attr("required", isCollecting);
}
Edit: Update for comment.
Your Inputs aren't wrapped inside of a form, after wrapping them in a form it works as intended.
I'd say its because you're sending info to an attribute of an array instead of the element itself. When you ask JS to receive true for the required attribute, you're sending to the array, since getElementsByName returns a collection of elements. You gotta iterate through those.
function changeRequireForAll(els, required) {
for(var i = 0; i < els.length; i++) {
if(els[i]) {
els[i].required = required;
//you could do els[i].setAttribute('required', required); too
}
}
}
//And you call it as
changeRequireForAll(document.getElementsByName("county1"), false);
That way, you just send your element collection and it will change all instances that matches your query. Even if your collection returns a single element, its still a single-item-array

Select dropdown fails to trigger the jquery function

When Y is selected, both of the input field should display "completed",and when user select "N", both of the input field should be blank but for some reason the code fail, any idea. Many Thanks
if($('.finished1').val(''))
{
$('.finished').val('');
}
else if($('.finished1').val('Y'))
{
$('.finished').val('completed');
}
else{
$('.finished').val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<select class="finished1">
<option value="" ></option>
<option value="Y" > Y</option>
<option value="N" > N</option>
</select>
<table>
<td><input type="text" class="finished"></td>
<td><input type="text" class="finished"></td>
</table>
Try this code JSFiddle
$('.finished1').on('change',function(){
if($(this).val() == 'N' || $(this).val() == ''){
$('.finished').val('');
}else{
$('.finished').val('completed');
}
});
You should use jquery's Change API to capture any change in the select input then you can check the selected value and respond accordingly
$('.finished1').on('change', function(){
if($(this).val() == 'Y')
$('.finished').val('completed');
else
$('.finished').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<select class="finished1">
<option value="" ></option>
<option value="Y" > Y</option>
<option value="N" > N</option>
</select>
<table>
<td><input type="text" class="finished"></td>
<td><input type="text" class="finished"></td>
</table>
You'll first need to evaluate the value of the select box through a change event handler and from there you can use switch statement to determine what to do from there.
$(function() {
$('.finished1').on('change', function() {
switch (this.value) {
case 'Y':
$('.finished').val('completed');
break;
case 'N':
case: '':
$('.finished').val('');
break;
default:
//
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<select class="finished1">
<option value="" ></option>
<option value="Y" > Y</option>
<option value="N" > N</option>
</select>
<table>
<td><input type="text" class="finished"></td>
<td><input type="text" class="finished"></td>
</table>
You should use a function that will detect the change in dropdown selected item.
If its detected it will check the values again and if need chang it to what is selected.
$(function () {
$('.finished1').change(function () {
if($('.finished1').val(''))
{
$('.finished').val('');
}
else if($('.finished1').val('Y'))
{
$('.finished').val('completed');
}
else{
$('.finished').val('');
}
});
});

jQuery selector not on id

I am trying to make a selector in jQuery but all my attempts failed. Can you help me?
I have a table like this
<tr>
<td>1</td>
<td><input id="AmontTuy1Diam" class="selectdiam"></td>
<td><input id="AmontTuy1Long" class="selectlong"></td>
<td><select class="MatSelectList" id="AmontTuy1Type">
<option value="0"> </option>
<option value="7">Value 1</option>
<option value="8">Value 2</option>
</select></td>
<td><input id="AmontTuy1Rugo" class="selectrugo"></td>
</tr>
And then I have an action on the change of the select list and I want change the value of the input in the last td without accessing it by id.
$(".MatSelectList").change( function() {
$(this).closest('tr').find(':last-child').val('test'); //doesn't work
});
I can't access it by id because the change function is executed on a class, and I have several table with this type of change value to do.
Any idea
You're trying to set the val of the td, you need to select the input:
$(this).closest('tr').find('td:last input').val('test');
$(".MatSelectList").change( function() {
$(this).closest('tr').find('td:last input').val('test'); //does work
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td><input id="AmontTuy1Diam" class="selectdiam"></td>
<td><input id="AmontTuy1Long" class="selectlong"></td>
<td><select class="MatSelectList" id="AmontTuy1Type">
<option value="0"> </option>
<option value="7">Value 1</option>
<option value="8">Value 2</option>
</select></td>
<td><input id="AmontTuy1Rugo" class="selectrugo"></td>
</tr>
</table>
Here is working example FIDDLE
$('.MatSelectList').change( function() {
$(this).closest('tr').find('td:last input').val($('option:selected').attr('value'));
});

jQuery to iterate through table and select dropdown lists

I have what I thought would be a simple task.
A table of drop down lists, and a text box at the end of each line.
All I want to do is loop through each row of the table, get the "hours dropdown value" and multiply by the "rate dropdown value" - and place the result in the text box.
I just keep getting undefined when trying to get the dropdownlist values.
My HTML is:
<table class="hours-table">
<tr>
<th>Hours</th>
<th>Hourly Rate</th>
<th>Date Total</th>
</tr>
<tr>
<td>
<select id="HoursSelected1" name="HoursSelected" class="hours">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td>
<select id="RateSelected1" name="RateSelected" class="rate">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td class="date-total">
<input type="text" class="date-total" name="date-total-01" value="" />
</td>
</tr>
<tr>
<td>
<select id="HoursSelected2" name="HoursSelected" class="hours">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td>
<select id="RateSelected2" name="RateSelected" class="rate">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td class="date-total">
<input type="text" class="date-total" name="date-total-01" value="" />
</td>
</tr>
<tr>
<td>
<select id="HoursSelected3" name="HoursSelected" class="hours">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td>
<select id="RateSelected3" name="RateSelected" class="rate">
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
<td class="date-total">
<input type="text" class="date-total" name="date-total-01" value="" />
</td>
</tr>
</table>
<p><a class="calculate" href="#" title="calculate row">Calculate</a>
</p>
My jQuery is:
$(document).ready(function () {
$('.calculate').on('click', function () {
$('.hours-table tr').each(function () {
var hours = $(this).find('select.hours').val();
var rate = $(this).find('select.rate').val();
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
});
return false;
});
});
Can anyone see where I've gone wrong please? There is a fiddle here: http://jsfiddle.net/Lr5pq/26/
Thank you, Mark
You have 2 problem in your code, first is neglecting the first row (the header row in the table) in your calculation, second using return false; which is deprecated and we use e.preventDefault();, instead, you can fix them like:
$('.hours-table tr').each(function () {
var hours = $(this).find('select.hours').val();
var rate = $(this).find('select.rate').val();
if (hours !== undefined && rate !== undefined) {
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
}
});
e.preventDefault();
BTW, if I were I would changed it like:
$(document).ready(function () {
$('.calculate').on('click', function (e) {
$('.hours-table tr').each(function () {
var hours = $(this).find('select.hours>option:checked').val();
var rate = $(this).find('select.rate>option:checked').val();
//this is for your header row
if (hours !== undefined && rate !== undefined) {
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
}
});
e.preventDefault();
});
});
as you see, we can use :checked instead of :selected, to select the selected option in a select node.
and it is your working jsfiddle
Try this:
$(document).ready(function () {
$('.calculate').on('click', function () {
$('.hours-table tr').each(function () {
var hours = $(this).find('select.hours > option:selected').val();
var rate = $(this).find('select.rate > option:selected').val();
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
});
return false;
});
});

Categories

Resources