Javascript Drop Down - javascript

I'm working on a form that has multiple drop downs which get checked whether the user has selected something or not. Most fields are mandatory so upon clicking submit, red text replaces the black, showing which have to be filled in. It isn't validating for some reason or doing what it is i'm trying to accomplish. Other fields that have a id such as 'literature' work fine but this doesn't. Could it be because it's numeric?
Javascript:
var lit = document.getElementById("012");
var hasLeadLiterature = false;
for (j = 0;) {
if (lit[j].selected === true) {
hasLeadLiterature = true;
break;
}
}
if (!hasLeadLiterature){
changeCSS("lbl_literature", "errored");
ErrorText=ErrorText+"11";
}
------
if (submitcount != 0){
alert("This form has already been submitted. Thank you!");
return;
}
/** Submit form check */
if (ErrorText == ""){
submitcount++; form.submit();
} else{
return;
}
------
HTML:
<TR>
<TD width="30%" valign="middle" ALIGN="left"><LABEL id="lbl_literature" for="lbl_literature" class="normal">How would you prefer to receive<br /> literature?: <SPAN class="required">*</SPAN></LABEL></TD><TD width="70%" valign="top" ALIGN="LEFT">
<TABLE>
<TR>
<td class="text_input"> <!-- 012 -->
<select id="012" name="012" title="Literature Preference">
<option value="None">--None--</option>
<option value="Print">Print</option>
<option value="Digital">Digital</option>
</select>
</td>
</TR>
</TABLE>
</TD>
</TR>
Any help would be much appreciated!!
Thanks in advance!

I believe there is a problem with your for loop, it is not looping anything, have you checked it does loop?
I suggest you read up about how to use a for loop, correct code will be more like:
for (var i=0; i<lit.length; i++)
Because this loop is not valid hasLeadLiterature never changes which by the nature of your code bypasses everything.

It looks like your validation is checking the opposite condition. Take a look:
for (j = 0;) {
if (lit[j].selected === true) {
hasLeadLiterature = true;
break;
}
}
If you get rid of the unnecessary loop structure, you're doing this:
if (lit[0].selected === true) {
hasLeadLiterature = true;
}
In this case, lit[0] is the first, empty option element in the select element. So your condition is saying that if the empty option is selected, the form validates. Shouldn't you reverse that condition? Something like this:
if (lit[0].selected === false) {
hasLeadLiterature = true;
}

Related

JavaScript submits form despite return false statement

I have a python flask webapp and JavaScript front-end. In my front end I am doing all form validations, before submitting it. One such validation is to check the value of a name input field against a list of names(array) I am passing to the template already on GET request. The code below works fine unless it's the last element in the array !!! Then it alerts properly, yet still submits the form. In other words - when rendering the page I am passing the list with all names existing in the database. Then if the same name is provided in the input field, I expect alert and stop execution. In my case, it works fine for all but the last element in the passed array. Then it alerts, yet still submits the form.
My HTML:
function submitServiceForm() {
if ($('#ingested_product_name').val() == '') {
alert("you must specify a product name");
return false;
} else if ($('#ingested_product_features').val() == '') {
alert("you must specify at least one feature");
return false;
} else if ($('#selected_quality_1').val() == null && !$('#no_qualities').is(':checked')) {
alert("you must select at least one Quality");
return false;
} else if ($('#selected_aspect_1').val() == null && !$('#no_qualities').is(':checked')) {
alert("you must select at least one Aspect");
return false;
} else if ($('#ingesting_service').val() == '') {
alert("you must select an ingesting service");
return false;
} else {
let no_qa_check = document.getElementById('no_qualities');
if (no_qa_check.checked) {
let allIngestInPlatform = {
{
allIngestInPlatform | safe
}
};
for (let i = 0; i < allIngestInPlatform.length; i++) {
if ($('#ingested_product_name').val() == allIngestInPlatform[i]['ingested']) {
alert("an Ingested Product with the same name already exists on that platform");
return false;
} else {
document.getElementById('ingested_product_form').submit();
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<table class="table">
<tr>
<td>
<button type="button" onclick="return submitServiceForm();" class="btn btn-primary">Add Ingested Product</button>
</td>
</tr>
</table>
</div>
Returning false in a submit button click doesn't do anything. A submit button click has a default action of submitting the form. You would need to specifically return false in the onsubmit event instead:
<form .. onsubmit="return submitServiceForm();">
Nowadays people also often prefer to avoid inline Javascript, so with jQuery, that might look more like this:
// Use a more specific selector than this
$('form').on('submit', function(){
return submitServiceForm();
});
Alternatively if you'd like to keep it in onclick, you can use event.preventDefault() instead.
// use a more specific selector than .btn-primary
$('.btn-primary').click(function(e){
if(!submitServiceForm()){
e.preventDefault();
}
});
Change this line on your code
From
for (let i = 0; i < allIngestInPlatform.length; i++)
To
for (let i = 0; i <= allIngestInPlatform.length; i++)

Form validation linking fields as required

I am looking to do some client size validation. Below you will find an example of my template.
When this form is submitted it is okay for a line to be empty. However I want to be sure if even one item in a line is selected/has an entry that all lines will have an entry. For example. There should always be either Nothing OR require a Date, start Time, stop time, and class. (the class is populated by a button in another location) The validation will be used to warn the individual if they are missing anything and if they submit we will disregard the record as incomplete.
I have looked at jquery Validation as we are already using it on other forms in our project but, I have been unable to find a way to link row items together.
<form>
<table id="payableEventTable" class="table table-condensed table-striped">
<thead>
<tr>
<th>Date</th>
<th>Class/Scenario</th>
<th>Start</th>
<th>Stop</th>
<th>Break</th>
</tr>
</thead>
<tbody id="payableEventTableBody">
<c:forEach begin="0" end="5" varStatus="i">
<tr>
<td><input type="date" class="input-small" name="claimForm.payableEvents[${i.index}].eventDate" /></td>
<td>
<select class="classSelect" name="claimForm.payableEvents[${i.index}].event">
<option></option>
</select>
</td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStartTime" /></td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStopTime" /></td>
<td>
<select>
<option value="0" selected>No Break taken</option>
<option value="15">15 Minutes</option>
<option value="30">30 Minutes</option>
<option value="45">45 Minutes</option>
</select>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
Technology we are willing to use. HTML, CSS, javaScript, jQuery, (lightweight plugins for jquery). We also have to make sure the solution works back to IE8.
Edit:
I built a JSFiddle. To help with visualization.
Edit:
I have come up with an answer. However, if anyone is able to improve on my answer, streamline it/make it look nicer I would still be willing to give out the Bounty to that person.
Here is my suggestion: To make your code more legible, you can combine the three functions validateRow(), isRowEmpty(), isRowComplete() into one simpler validateRow() function. Also it is a lot faster, because you only need to go through all elements and check their values once instead of twice.
I also created a simple to use validateForm() function to tidy things up.
The validateForm() function can now be used in an event handler:
// Event Handler
$('#validate').bind('click', function(e){
e.preventDefault();
if(validateForm()) {
alert("next");
//$('#claimWizard').wizard('next');
}
});
// Form Validation
var validateForm = function(){
var valid = true;
$('#payableEventTableBody tr').each(function() {
if (validateRow($(this))) {
$(this).removeClass("error");
}
else {
valid = false;
$(this).addClass('error');
}
});
return valid;
}
var validateRow = function(row){
var state = null,
valid = true;
row.find('input, select').each(function() {
var value = $(this).val(),
isEmpty = (value != 0 && value !== '');
//if its the first element just save the state
if(state === null) {
state = isEmpty;
}
// if this field has not the same state as the rest
else if(state !== isEmpty) {
valid = false;
}
})
return valid;
}
And here's your fiddle with my code implemented: http://jsfiddle.net/KNDLF/
So, what I came up with:
Three methods: isRowValid(), isRowEmpty(), isRowComplete()
The rows need to be either empty or complete.
//The following code is part of my logic on continuing
var valid = true;
$('#payableEventTableBody tr').each(function() {
$(this).removeClass('error');
if (!isRowValid($(this))) {
valid = false;
$(this).addClass('error');
return;
}
});
if (valid) {
$('#claimWizard').wizard('next');
}
//The following is my validation methods
<script type="text/javascript">
function isRowValid($tr) {
return (isRowEmpty($tr) || isRowComplete($tr));
}
function isRowEmpty($tr) {
var isEmpty = true;
$tr.find('input, select').each(function() {
var value = $(this).val();
if (value != 0 && value !== '') {
isEmpty = false;
}
});
return isEmpty;
}
function isRowComplete($tr) {
var isComplete = true;
$tr.find('input, select').each(function(){
var value = $(this).val();
if(value === ''){
isComplete = false;
}
});
return isComplete;
}
</script>
This should be good to start with
http://jsfiddle.net/rJaPR/
$('#validate').bind('click', function(e){
e.preventDefault();
$('#payableEventTable tr').each(function(){
var tr = $(this);
var newRowValue=0;
$(tr).find('input, select').each(function(){
var value = $(this).val();
switch(newRowValue){
case 0:
// first input/select
newRowValue = ((value!=0 && value!='') ? 1 : -1);
break;
case 1:
// there are some values in this row
if (value==0 || value=='')
tr.css('backgroundColor', 'red');
break;
case -1:
// this row should be empty
if (value!=0 && value!='')
tr.css('backgroundColor', 'red');
break;
}
})
})
})

javascript validation of radio buttons in a form

hope someone can shed light on the below code which alerts always the error below. The code was devised to validate one radio button is selected otherwise return false to the current page otherwise proceed with the form action. Thanking in you in advance!!
function onDisplayItemsForm(){
var re = false; // used to determine when a button is checked
var radIdSelected = frmDisplayItems;
// traverse the radio buttons
// if one is checked sets re to true, and stops the iteration
for(var i=0; i<radIdSelected.length; i++)
{
if(radIdSelected[i].checked == true)
{
re = true;
break;
}
if (!radIdSelected[i].checked)
{
alert("Please select product");
return false;
}
return true;
}
};
The form is as follows:
<form name="frmDisplayItems" action="showItem.php" onsubmit="return onDisplayItemsForm();" >
<table width="50%" border="1">
<th>Country of Origin</th>
<th>Select</th>
</tr>
<td><input name=\"radId\" type=\"radio\" value=\"$id\" /></td>
</tbody>
</table>
<p><input name="btnSubmit" type="submit" value="Select"/> </p>
</form>
<
It's the value of re that you want to check after the loop has finished:
if (!re)
{
alert("Please select product");
return false;
}
return true;

Why isn't this simple javascript working?

This javascript all but works with exception of radiobuttonlist.
<script language="javascript" type="text/javascript">
function validate() {
if (document.getElementById("<%=txtballotName.ClientID%>").value == "") {
alert("Ballot Name can not be blank");
document.getElementById("<%=txtballotName.ClientID%>").focus();
return false;
}
if (document.getElementById("<%=txtballotCity.ClientID %>").value == "") {
alert("Ballot City can not be blank");
document.getElementById("<%=txtballotCity.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=txtballotState.ClientID%>").value == "") {
alert("Ballot State cannot be blank");
document.getElementById("<%=txtballotState.ClientID%>").focus();
return false;
}
if (document.getElementById("<%=txtballotZip.ClientID%>").value == "") {
alert("Zip Code cannot be blank");
document.getElementById("<%=txtballotZip.ClientID%>").focus();
return false;
}
if (document.getElementById("<%= txtreceivedby.ClientID %>").checked == false) {
alert("Request Received By can not be blank");
document.getElementById("<%=txtreceivedby.ClientID%>").focus();
return false;
}
return true;
}
The radiobuttonList looks like this:
<tr>
<td>
<label for="txtreceivedby_0">FAX</label>
<input id="txtreceivedby_0" type="radio" name="txtreceivedby" value="Fax" />
</td>
<td>
<label for="txtreceivedby_1">EMAIL</label>
<input id="txtreceivedby_1" type="radio" name="txtreceivedby" value="Mail" />
</td>
<td>
<label for="txtreceivedby_2">PHONE</label>
<input id="txtreceivedby_2" type="radio" name="txtreceivedby" value="Phone" />
</td>
</tr>
So far, the other form field are validating except the txtreceivedby radio button. I am not getting any errors but it isn't validating either.
Thanks in advance
You can create a short little utility function that will get you the value of any radio group:
function getRadioValue(name) {
var items = document.getElementsByName(name);
for (var i = 0; i < items.length; i++) {
if (items[i].checked) {
return(items[i].value);
}
}
}
You can then get the checked item in your radio group like this:
var val = getRadioValue("txtreceivedby");
Working Demo: http://jsfiddle.net/jfriend00/PHXaC/
ASP's radiobuttonlist render as a table containing radio button items. Therefore, it is a bit complicated to get the checked status of radio button.
You might find various sources if you google for "ASP radiobuttonlist and javascript". I have tested some of them and not every of them worked well specially if your page created from Master page.
However, I have tried in my own way and here it is:
<asp:RadioButtonList ID="txtReceivedBy" runat="server">
<asp:ListItem Text="Fax" Value="0"></asp:ListItem>
<asp:ListItem Text="Email" Value="1"></asp:ListItem>
<asp:ListItem Text="Phon" Value="2"></asp:ListItem>
</asp:RadioButtonList>
<input type="button" onclick="alert(checkedRadio());" value="Test RadioButtonChecked Status" />
and the javascript I have used to get the cehcked status is here
function checkedRadio() {
var rtn = false;
var i = 0;
var radioBoxesContainer = document.getElementById("<%=txtReceivedBy.ClientID%>");
if (radioBoxesContainer) {
var radioBoxes = radioBoxesContainer.getElementsByTagName("input");
if (radioBoxes && radioBoxes.length > 0) {
for (i - 0; i < radioBoxes.length; i++) {
if (radioBoxes[i].checked) {
rtn = true;
break;
}
}
}
}
return rtn;
}
if you are interested to get a live demo,
you can find it here http://plugins.amiwithyou.com/sof/
In a nutshell major headache; if you'd page me, I'd go with a nice good ol' fashion <select> box.
But to be useful, you need to have a look with view source at exactly what the ASP code plasts out to the browser. I don't know ASP but I bet it's either outputting 3 different ids on each radio, or the same id (#txtreceivedby) on all three of them.
Whatever it gives out, the validation code if(bla_bla_blah.checked===false) is wrong because it only targets just one in the set of radios and even with that fixed, that radio might not return .checked===false cross-browser.

My table is not hiding when using Javascript

I want to hide or show my spinner depending on what is selected in the radio button. The spinner is displayed in a table. If the user chose yes (radio button), it will display the table which the spinner is in, if the user chose no (radio button), it will hide the table the spinner is in.
I researched on Google the best way to use style in JavaScript and the one I most commonly found was using (variable).style.(css property).
I have tried this but it hasn't worked. What I want to know is that am I coding this wrong (it is not showing anything in error console and it seems right with the examples I have followed) or do I need to do it another way when it comes to display and hiding tables?
Below is my HTML code:
<table id="tblWeight">
<tr>
<th>6: Provide a Total Weight for your Session</th>
<td><input type="radio" name="weightChoice" value="yes" onClick="getWeight()"/> Yes</td>
<td><input type="radio" name="weightChoice" value="No" onClick="getWeight()"/> No</td>
</tr>
</table>
<div id="radioAlert"></div>
<br/>
<table>
<tr>
<th>Weight (%):</th>
<td class="spinner"><input type="text" class="spinnerWeight" name="txtWeight" id="txtWeight"></td>
<td><button class="scrollBtn" id="btnWeightUp" type="button"><img src="Images/black_uppointing_triangle.png" alt="Increase" /></button>
<button class="scrollBtn" id="btnWeightDown" type="button"><img src="Images/black_downpointing_triangle.png" alt="Decrease" /></button></td>
</tr>
</table>
<div id="weightAlert"></div>
<br/>
<table><tr><th>7: Module:</th>
<td><?php echo $moduleHTML; ?></td>
</tr>
</table>
Below is JavaScript code:
function getWeight() {
var weightChoice = document.getElementsByName("weightChoice");
var textWeight = document.getElementById("txtWeight");
var tableWeight = document.getElementById("tblWeight");
if(weightChoice[0].checked == true){
tableWeight.style.visibility=="visible";
textWeight.value == 0;
} else {
tableWeight.style.visibility=="hidden";
textWeight.value == 0;
}
}
Your assignment statements are written with doubled "=" characters, which makes them not be assignment statements.
if(weightChoice[0].checked == true){
tableWeight.style.visibility = "visible";
textWeight.value = 0;
}else{
tableWeight.style.visibility = "hidden";
textWeight.value = 0;
}
The "==" is a comparison operator, so your statements were not syntactically erroneous and thus no errors were reported.
You're using == to assign, when == is an equality comparison operator. It should be =:
function getWeight() {
var weightChoice = document.getElementsByName("weightChoice");
var textWeight = document.getElementById("txtWeight");
var tableWeight = document.getElementById("tblWeight");
if(weightChoice[0].checked) {
tableWeight.style.visibility = "visible";
textWeight.value = 0;
} else {
tableWeight.style.visibility = "hidden";
textWeight.value = 0;
}
}
Also, == true, which I removed, is never necessary. I repeat - never. Anywhere you use == true, just take it out.

Categories

Resources