Javascript validation working, but the form doesn't submit - javascript

I have this form where for example in Type A you can write only numbers that start with 1, and so on:
<form accept-charset="UTF-8" action="verify.php" id="form" method="post">
<label id="type" for="type" class="">Type</label>
<select class="" id="Type" name="type">
<option id="a" value="1">Type A</option>
<option id="b" value="2">Type B</option>
<option id="c" value="3">Type C</option>
<option id="d" value="4">Type D</option>
<option id="e" value="5">Type E</option>
</select>
<label for="type_number" class="inner_text">Type Number</label>
<input name="type_number" type="text" class="false" id="type_number" />
<input type="button" id="Confirm" value="Confirm" />
</form>
And this Javascript:
document.getElementById('Confirm').onclick = function () {
var letter = document.getElementById("type_number").value.match(document.getElementById("Type").value);
if (letter !== null) {
letter = letter[0].toLowerCase();
this.value = letter + this.value.substring(1);
}
else {
alert('Number is not correct!');
}
}
The validation work, but doesn't submit, when a good answer is writed the 'Confirm' get renamed to '1onfirm', only that happen.
Check the jsfiddle too: http://jsfiddle.net/focusoft/hSmFS/1/
Thanks.

Either submit the form in javascript function or change the confirm button type to submit.
change your javascript function
document.getElementById('Confirm').onclick = function () {
var letter = document.getElementById("type_number").value.match(document.getElementById("Type").value);
if (letter !== null) {
letter = letter[0].toLowerCase();
this.value = letter + this.value.substring(1);
document.forms[0].submit();
}
else {
alert('Number is not correct!');
}
}

Change this:
<input type="button" id="Confirm" value="Confirm" />
for this:
<input type="submit" id="Confirm" value="Confirm" />

Related

enabled submit button if radio button field data and other field data found using jquery

I have few fields on this code snippet. Here I have radio button If Field_One is checked show mentioned input field (country select, first name, last name, mobile, email, trans id) same like if Field_Two is checked show mentioned field (reference no, id no and trans id)
Here Trans ID. First Name, Last Name is mandotory for both radio button and its a required field. But I have added few required field without last name.
And Field_Two radio field will show field like reference id and id no. I want if only one field is required field and if only one field is filled up then its ok from both reference id and id no.
But My code is not working properly See the below snippet
One thing if First Country is Africa then show another Dropdown box with Country2 but its also required when Africa is selected but Africa not selected its not required.
$(document).ready(function () {
function make_required_inputs(el) {
let value = el.val();
let div = $('div.' + value);
$('input[required]').removeAttr('required');
div.find('input.required').attr('required', true);
$('input[name="trxid"]').attr('required', true);
}
function validation() {
let valid = true;
$.each($('input[required]'), function () {
if ($(this).val() == '') valid = false;
});
if (valid) {
jQuery('#button1').attr('disabled', false);
} else {
jQuery('#button1').attr('disabled', true);
}
}
$('input[type="radio"]').click(function () {
if ($(this).attr("value") == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide();
$("#country").show();
}
if ($(this).attr("value") == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide();
$("#country").hide();
}
validation();
});
let checked = $('input[name="myfield"]:checked');
let value_checked = checked.attr("value");
if (value_checked == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide();
}else if (value_checked == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide();
}
$('input[type="radio"]')
make_required_inputs($('input[name="myfield"]:checked'));
$('input[name="myfield"]').on('change', function () {
make_required_inputs($(this));
validation();
});
$('input').keyup(function (e) {
validation();
});
jQuery("#country").change(function(){
jQuery(this).find("option:selected").each(function(){
var optionValue = jQuery(this).attr("value");
if(optionValue=='za'){
jQuery("#country2").show();
} else{
jQuery("#country2").hide();
}
});
}).change();
jQuery("#country2").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="myfield" value="Field_One" checked="true" /> Field_One
<input type="radio" name="myfield" value="Field_Two" /> Field_Two
<br><br>
<select name="country" class="required" id="country">
<option>Select</option>
<option value="us">US</option>
<option value="uk">UK</option>
<option value="za">Africa</option>
</select>
<br><br>
<select name="country2" class="required" id="country2">
<option>Select</option>
<option value="eg">Egypt</option>
<option value="ng">Nigeria</option>
<option value="gh">Ghana</option>
<option value="za">South Africa</option>
</select>
<br><br>
<input type="text" name="first_name" class="required" placeholder="First Name" />
<br><br>
<input type="text" name="last_name" placeholder="Last Name"/>
<br><br>
<div class="Field_One">
<input type="text" name="mobile_no" placeholder="Mobile no"/>
<br><br>
<input type="text" class="required" name="email" placeholder="Email"/>
</div>
<br>
<div class="Field_Two">
<input type="text" name="reference_no" class="required" placeholder="Reference no" /><br><br>
<input type="text" name="id_no" class="required" placeholder="ID no" />
</div><br>
<input type="text" name="trxid" class="required" placeholder="Trans ID" />
<input type="submit" id="button1" value="Submit" disabled/>
Update:
$(document).ready(function () {
function validation() {
let valid = true;
$.each($('input[required]:not([name="reference_no"],[name="id_no"]),select[required]'), function () {
if ($(this).val() == '') valid = false;
});
let one = 0;
if ($('input[one="true"][required]').length == 0) {
one = 1;
} else {
one = 0;
$.each($('input[one="true"][required]'), function () {
if ($(this).val() !== '') one++;
});
}
if (valid && one > 0) {
jQuery('#button1').prop('disabled', false);
} else {
jQuery('#button1').prop('disabled', true);
}
}
function required(value) {
$('input.required,select.required').prop('required', true);
if (value == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide().find('input,select').prop('required', false);
$("#country").show().addClass('required').prop('required', true);
}
if (value == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide().find('input,select').prop('required', false);
$("#country").hide().removeClass('required').prop('required', false);
jQuery("#country2").hide().removeClass('required').prop('required', false);
}
validation();
}
$('input[type="radio"]').click(function () {
required($(this).val());
});
let value_checked = $('input[name="myfield"]:checked').attr("value");
required(value_checked);
$('select,input').on('change keyup', function () {
validation();
});
jQuery("#country").change(function () {
var optionValue = jQuery(this).find("option:selected").attr("value");
if (optionValue == 'za') {
jQuery("#country2").show().addClass('required').prop('required', true);;
} else {
jQuery("#country2").hide().removeClass('required').prop('required', false);;
}
validation();
}).change();
jQuery("#country2").hide().removeClass('required').prop('required', false);
});
let valid2 = true;
$.each($('#domain_name,select[required]'), function () { if ($(this).val() == '') valid2 = false; }); if (valid2) { jQuery('#domsBtn').prop('disabled', false); } else { jQuery('#domsBtn').prop('disabled', true); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="myfield" value="Field_One" checked="true" /> Field_One
<input type="radio" name="myfield" value="Field_Two" /> Field_Two
<br><br>
<select name="country" class="required" id="country">
<option value="">Select</option>
<option value="us">US</option>
<option value="uk">UK</option>
<option value="za">Africa</option>
</select>
<select name="country2" class="required" id="country2">
<option value="">Select</option>
<option value="eg">Egypt</option>
<option value="ng">Nigeria</option>
<option value="gh">Ghana</option>
<option value="za">South Africa</option>
</select>
<br><br>
<input type="text" name="first_name" class="required" placeholder="First Name" />
<br><br>
<input type="submit" id="firstCheck" value="First Name Check" disabled />
<br><br>
<input type="text" name="last_name" placeholder="Last Name" />
<br><br>
<div class="Field_One">
<input type="text" name="mobile_no" placeholder="Mobile no" />
<br><br>
<input type="text" class="required" name="email" placeholder="Email" />
</div>
<br>
<div class="Field_Two">
<input type="text" name="reference_no" one="true" class="required" placeholder="Reference no" /><br><br>
<input type="text" name="id_no" one="true" class="required" placeholder="ID no" />
</div><br>
<input type="text" name="trxid" class="required" placeholder="Trans ID" />
<input type="submit" id="button1" value="Submit" disabled />

Javascript Validate Input fields + Select Field

I am using a very easy (but functional for my needs) Javascript script to validate input fields.
Here my main code:
<script language = "javascript">
function manage(txt) {
var bt = document.getElementById('send');
if (txt.value && txt2.value && txt3.value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>
Here are my fields
<input type="text" name="FNAME" id="txt" class="input" size="20" placeholder="First Name *" onkeyup="manage(this)">
<input type="text" name="LNAME" id="txt2" class="input" size="20" placeholder="Last Name *" onkeyup="manage(this)">
<input type="text" name="EMAIL" id="txt3" class="input" size="20" placeholder="Email *" onkeyup="manage(this)">
and here my Submit button:
<input type="submit" name="submit" id="send" class="button button-primary" value="Subscribe" disabled>
What this does is to leave the submit button disabled until all fields have some value entered and works absolutely fine, however I also have a new and additional select option being:
<select name="Countries">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
......
</select>
I've tried to apply the following changes:
<script language = "javascript">
function manage(txt) {
var bt = document.getElementById('send');
if (txt.value && txt2.value && txt3.value && txt4.value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>
<select name="Countries" id="txt4" onkeyup="manage(this)">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
......
</select>
However it does not seem to work. Some expert advise would be greatly appreciated. Thank you very much.
The proper form is
if (txt.value!='' && txt2.value!='' && txt3.value!='' && txt4.value!='')
You don't want to set the onkyeup event, but onchange. More universal event is oninput.
You should also check the required form elements tag attribute, which can provide you similar functionality without javascript. See here.
First of all, listening keyup event on your select will work only in case if select was changed by the keyboard. In case if it was changed by mouse, your event won't be fired. Better to listen onchange
On another hand, you should check the emptiness of all text fields, as you do for txt4.value!='':
if (txt.value!='' && txt2.value!='' && txt3.value!='' && txt4.value!='') {
...
}
Now it will work.
function manage(txt) {
var bt = document.getElementById('send');
if ( txt.value != '' && txt2.value != '' && txt3.value != '' && txt4.value != '' ) {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
<input type="text" name="FNAME" id="txt" class="input" size="20" placeholder="First Name *" onkeyup="manage(this)">
<input type="text" name="LNAME" id="txt2" class="input" size="20" placeholder="Last Name *" onkeyup="manage(this)">
<input type="text" name="EMAIL" id="txt3" class="input" size="20" placeholder="Email *" onkeyup="manage(this)">
<select name="Countries" id="txt4" onchange="manage(this)">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
</select>
<input type="submit" name="submit" id="send" class="button button-primary" value="Subscribe" disabled>
I have done this type of functionality before. So I'm sharing my code here.
HTML Code
<form method="Post" class="form">
<input type="text" name="FNAME" id="txt" class="input" size="20" placeholder="First Name *" onblur="manage(this)">
<input type="text" name="LNAME" id="txt2" class="input" size="20" placeholder="Last Name *" onblur="manage(this)">
<input type="text" name="EMAIL" id="txt3" class="input" size="20" placeholder="Email *" onblur="manage(this)">
<select name="Countries" id="txt4" onchange="manage(this)" class="input">
<option value="">Select Country</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
</select>
<input type="submit" name="submit" id="send" class="button button-primary" value="Subscribe" disabled>
</form>
Javascript Code:
<script>
function manage($e){
var input = document.getElementsByClassName("input");
var status=false;
for(var i=0;i<input.length;i++){
if(input[i].value.trim()!='' && input[i].value.trim()!=null && input[i].value.trim()!=undefined){
status = true;
} else {
status = false;
break;
}
}
console.log(status);
if(status===true){
var email = document.getElementById("txt3").value;
if(!(/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.trim()))){console.log('1');
document.getElementById('send').disabled = true;
} else {console.log('2');
document.getElementById('send').disabled = false;
}
} else {
document.getElementById('send').disabled = true;
}
}
</script>
There are many ways to resolve this type of functionality but for this case, I have used the above code to achieve the goal. If you have any queries, please let me know. Thanks.

Do not repeat yourself best practices showing and hiding fields

I am trying to figure out the best way to show and hide fields that are being reused. Cleaning up the code so that I do not repeat myself "DRY". Will someone please assist me in the best practices of doing so?
What I have is a select that allows the user to choose from two different reports.
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option id ="checklistreport" value="checklistreport" >Checklist Stats</option>
<option id ="locationreport" value="locationreport" >Location Stats</option>
</select>
Then each report have a lot of similar fields. How can I have them use the same fields but hide/show the differences and go to the correct form "action" based which report is chosen.
Location Report
<form name="generatereport" method="post" action="_location_queries.cfm">
<select name="Location" id="loc" multiple="multiple" required size="9">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="10" readonly></textarea>
<br /><br />
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
<br /><br />
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
<br /><br />
<input type="submit" name="submit" value="Continue" />
</form>
<script type="text/javascript">
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
</script>
Checklist Report
<form name="generatereport" method="post" action="_checklists_queries.cfm">
<select name="Location" id="loc" multiple="multiple" required size="8">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="7" readonly></textarea>
<br /><br />
<cfquery name="GetActiveEmps" datasource="tco_associates">
SELECT assoc_userid, assoc_last, assoc_first FROM tco_associates
WHERE assoc_status = 'ACTIVE'
and assoc_last NOT LIKE 'Test%'
and len(assoc_last) > 0
ORDER BY assoc_last
</cfquery>
<select name="EmployeeName" id="EmployeeName" multiple="multiple" required size="8">
<cfoutput query="GetActiveEmps">
<option value="#assoc_userid#">#Trim(assoc_last)#, #Trim(assoc_first)#</option>
</cfoutput>
</select>
<button id="add1" type="button">ADD ALL</button>
<button id="rem1" type="button">REMOVE ALL</button>
<textarea id="selected1" rows="7" readonly></textarea>
<br /><br />
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
<br /><br />
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
<br /><br />
<input type="submit" name="submit" value="Continue" />
</form>
<script type="text/javascript">
// JS for Showing Chosen Locations in textarea
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
// End JS for Showing Chosen Locations in textarea
// JS for Showing Chosen Associates in textarea
var opts1 = document.querySelectorAll('#EmployeeName option');
document.getElementById('add1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = true;
}
reflectChange1();
});
document.getElementById('rem1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = false;
}
reflectChange1();
});
document.getElementById('EmployeeName').addEventListener('change', reflectChange1);
function reflectChange1() {
document.getElementById('selected1').value = '';
for ( var i=0; i<opts1.length; i++ ) {
if(opts1[i].selected)
document.getElementById('selected1').value += opts1[i].text+'\n';
}
}
// End JS for Showing Chosen Associates in textarea
</script>
Many of these fields are the same is there a way i can just have one set and show them if either option is chosen and not have two different sets?
This is what I have tried:
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option id ="checklistreports" value="checklistreports" >Checklist Stats</option>
<option id ="locationreports" value="locationreports" >Location Stats</option>
</select>
<script>
$(document).on('change', '#reporttype', function() {
var value = $(this).val();
//var checklistreport = $("#checklistreport");
//var locationreport = $("#locationreport");
var location = $("#location");
var employeelist = $("#employeelist");
var chosendates = $("#chosendates");
var formattype = $("#formattype");
var submitbtn = $("#submitbtn");
if (value == "checklistreports") {
//checklistreport.show();
//locationreport.hide();
location.show();
employeelist.show();
chosendates.show();
formattype.show();
submitbtn.show();
} else if (value == "locationreports") {
//checklistreport.hide();
//locationreport.show();
location.show();
employeelist.hide();
chosendates.show();
formattype.show();
submitbtn.show();
} else {
//checklistreport.hide();
//locationreport.hide();
location.hide();
employeelist.hide();
chosendates.hide();
formattype.hide();
submitbtn.hide();
}
});
</script>
<br /><br />
<!--<div id="locationreport" style="display: none;">-->
<form name="generatereport" method="post" action="_location_queries.cfm">
<!--<div id="checklistreport" style="display: none;">-->
<form name="generatereport" method="post" action="_checklists_queries.cfm">
</form>
<div id="location" style="display: none;">
<select name="Location" id="loc" multiple="multiple" required size="9">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="10" readonly></textarea>
</div>
<br /><br />
<div id="employeelist" style="display: none;">
<cfquery name="GetActiveEmps" datasource="tco_associates">
SELECT assoc_userid, assoc_last, assoc_first FROM tco_associates
WHERE assoc_status = 'ACTIVE'
and assoc_last NOT LIKE 'Test%'
and len(assoc_last) > 0
ORDER BY assoc_last
</cfquery>
<select name="EmployeeName" id="EmployeeName" multiple="multiple" required size="9">
<cfoutput query="GetActiveEmps">
<option value="#assoc_userid#">#Trim(assoc_last)#, #Trim(assoc_first)#</option>
</cfoutput>
</select>
<button id="add1" type="button">ADD ALL</button>
<button id="rem1" type="button">REMOVE ALL</button>
<textarea id="selected1" rows="10" readonly></textarea>
</div>
<br /><br />
<div id="chosendates" style="display: none;">
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
</div>
<br /><br />
<div id="formattype" style="display: none;">
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
</div>
<br /><br />
<div id="submitbtn" style="display: none;">
<input type="submit" name="submit" value="Continue" />
</div>
</form>
<script type="text/javascript">
// JS for Showing Chosen Locations in textarea
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
// End JS for Showing Chosen Locations in textarea
// JS for Showing Chosen Associates in textarea
var opts1 = document.querySelectorAll('#EmployeeName option');
document.getElementById('add1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = true;
}
reflectChange1();
});
document.getElementById('rem1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = false;
}
reflectChange1();
});
document.getElementById('EmployeeName').addEventListener('change', reflectChange1);
function reflectChange1() {
document.getElementById('selected1').value = '';
for ( var i=0; i<opts1.length; i++ ) {
if(opts1[i].selected)
document.getElementById('selected1').value += opts1[i].text+'\n';
}
}
// End JS for Showing Chosen Associates in textarea
</script>
Not sure how I choose which action for the form. Depending on which report is chosen.
https://jsfiddle.net/bobrierton/o2gxgz9r/10018/
You have a few options here:
Option #1:
Always show the "common" inputs, and only hide the inputs that are conditional upon selection, that way your code is cleaner because you only have to manage the conditional elements (not all of them as you are doing now)
Option #2:
Use CF includes to hold your "common" elements, and "conditional" elements, combining them where necessary to build the correct list.
Option #3:
Use JavaScript to hold your "common" elements, and "conditional" elements, and render the composed list based on your conditions.
var location = $('select[name=Location]');
// This lists could hold anything you want, jQuery elements
// references, strings, etc.
var lists = {
common: ['a', 'b', 'c'],
locationreports: ['location #1', 'location #2'],
checklistreports: ['checklist #1', 'checklist #2']
};
$('#reporttype').on('change', function() {
var value = $(this).val();
// Grab a copy of the common list to begin with
var options = [].concat(lists.common);
// Now combine the conditional options
if (value === "checklistreports" || value === "locationreports") {
options = options.concat(lists[value]);
}
// Now you have a complete list of options to show based
// your conditions, so now you can just show them all, or
// do whatever you want with this new list.
location.empty();
options.forEach(function($element) {
// Do something with the list
location.append('<option value="' + $element + '">' + $element + '</option>');
})
There are lots of other options, but between using and combining includes, or composing objects together you should be able to customize a nice DRY workflow.

SerializeObject and SerializeArray doesn't show on console.log

My JSFiddle here
I know there has been loads of posts about this here in SO but I'm wondering why these (SerializeObject/Serialize/SerializeArray()) doesn't show on my console.log after onclick.
HTML:
<form action="#" method="post" id="testform" name="testform">
<input class="input_rid" type="text" name="rid" id="rid" value="" placeholder="rid" required>
<input class="input_recipient_id" type="text" name="recipient_id" id="recipient_id" value="" placeholder="recipient_id" required>
<select class="select_eml" name="email_type" id="email_type" required>
<option value="" selected="selected" disabled="disabled">
Email type
</option>
<option value="Body">Body</option>
<option value="Body & Attachment">Body & Attachment</option>
<option value="Link">Link</option>
<option value="Internal Attachment">Internal Attachment</option>
<option value="External Attachment">External Attachment</option>
</select>
<select class="select_tcb" name="to_cc_bcc" id="to_cc_bcc">
<option value="" selected="selected" disabled="disabled">
To_CC_BCC
</option>
<option value="to">To</option>
<option value="cc">CC</option>
<option value="bcc">BCC</option>
</select>
<input class="input_sd" type="date" name="start_dte" id="start_dte" value="" placeholder="start_dte" required>
<input class="input_ed" type="date" name="end_dte" id="end_dte" value="" placeholder="end_dte">
<input class="button small radius right inline" type="button" onclick="return test();" value="Save to Console Log">
</form>
JS:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
function test() {
var v = $("#testform").serializeObject();
console.log(v);
console.log($("#testform").serialize());
console.log($("#testform").serializeArray());
}
The problem here is that the test function is declared inside a window load scope and when you click on that button the interpreter can't find the invoked function.
To get that example working, move the function declaration outside the $(window).on('load') scope or just declare it globally:
window.test = function() {
var v = $("#testform").serializeObject();
console.log(v);
console.log($("#testform").serialize());
console.log($("#testform").serializeArray());
}

Javascript Form validation not working for select element

So I'm trying to change a select box's style if the value is not changed ie. the user has not selected anything. That yesnoCheck is a function which shows an additional input field if the choice "other" is selected. I don't think it affects this form validation though. This same kind of validation works fine with an input field but it won't work with a select box.
I've also treid selectedIndex == 0 but it doesn't work either.
HTML:
<form name="myForm" method="post" action="" onsubmit="return(validate());">
<label for="lastname">Sukunimesi:</label>
<input type="text" id="lastname" name="lastname" /><br />
<select id="car" name="car" onchange="javascript:yesnoCheck()">
<option id="noCheck" value="none">Valitse automerkkisi</option>
<option id="noCheck" value="1">Lada</option>
<option id="noCheck" value="2">Mosse</option>
<option id="noCheck" value="3">Volga</option>
<option id="noCheck" value="4">Vartburg</option>
<option id="yesCheck" value="other">Muu</option>
</select>
<input type="submit" value="Submit" />
</form>
JS:
<script type="text/javascript">
function yesnoCheck() {
if (document.getElementById("yesCheck").selected) {
document.getElementById("ifYes").style.display = "block";
}
else document.getElementById("ifYes").style.display = "none";
}
function validate() {
if (document.myForm.lastname.value.length < 3) {
document.getElementById("lastname").className = "required";
return false;
}
if (document.myForm.car.value == "none") {
document.getElementById("car").className = "required";
return false;
}
alert ("Everything is fine!");
}
</script>
Your code works check your form name and make sure your form exists before the script is run.
function check(){
if (document.myForm.car.value == "none") {
document.getElementById("car").style.border = "1px solid #900";
document.getElementById("car").style.backgroundColor = "#ff9";
return false;
}
}
<form name="myForm">
<select id="car" name="car" onchange="javascript:yesnoCheck()">
<option id="noCheck" value="none">Valitse automerkkisi</option>
<option id="noCheck" value="1">Lada</option>
<option id="noCheck" value="2">Mosse</option>
<option id="noCheck" value="3">Volga</option>
<option id="noCheck" value="4">Vartburg</option>
<option id="yesCheck" value="other">Muu</option>
</select>
</form>
<button onclick="check()">Run script</button>
So the solution was to delete return false; from the function.

Categories

Resources