Validate select Input fields based on what is selected in option menu - javascript

OK so I have a table/form that i need to validate, making sure that there are no blank input fields when submitted. The catch is that I only need certain fields validated based on the selected option at the top of the table.
Needed for: Op1 -> Name, city, state, phone, zip.
Needed for: Op2 -> Name, city, state, phone, zip, ssn.
Needed for: Op3 -> Name, city, state, phone, zip, ssn.
Needed for: Op4 -> Name, city, state, phone, zip, DOB, other.
I'm wondering if I am going about this the right way or maybe there is a better way to go about this.
side note: the option values are dynamically created from the back-end and I cant add any id/values to the option tags.
<div class="container">
<form action="">
<table id="mytable1">
<tr>
<td>
<select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="">Name</label>
<input type="text" class="name">
</td>
</tr>
<tr>
<td>
<label for="">City</label>
<input type="text" class="city">
</td>
</tr>
<tr>
<td>
<label for="">Phone</label>
<input type="text" class="phone">
</td>
</tr>
<tr>
<td>
<label for="">State</label>
<input type="text" class="state">
</td>
</tr>
<tr>
<td>
<label for="">zip</label>
<input type="text" class="pos">
</td>
</tr>
<tr>
<td>
<label for="">SSN:</label>
<input type="text" class="add1">
</td>
</tr>
<tr>
<td>
<label for="">DOB:</label>
<input type="text" class="add1">
</td>
</tr>
<tr>
<td>
<label for="">other:</label>
<input type="text" class="add1">
</td>
</tr>
</table>
</form>
<button onclick="">Submit</button>
<p>Values: </p>
</div>
and the joining JavaScript
$(document).ready(function () {
$('select').on('change', function () {
$( "p" ).append($( "input" ).map(function() {
return $( this ).val();
}).get().join( ", " ) );
$('table').append($('input').map(function () {
console.log($(this).val());
}).get().join(', '));
let selValue = $('select option:selected').text();
if(selValue == 'Option 1'){
//check if required fields are blank, if so throw error
console.log('value 1 is selected');
}else if(selValue == 'Option 2'){
//check if required fields are blank, if so throw error
console.log('value 2 is selected');
} else if(selValue == 'Option 3'){
//check if required fields are blank, if so throw error
console.log('value 3 is selected');
}else if(selValue == 'Option 4'){
//check if required fields are blank, if so throw error
console.log('value 4 is selected');
}else {
//submit form.
//$("form").submit();
}
});
If there is any other needed info please let me know, I post it as soon as possible.

There were few issues that you need to take care of -
1) the form tag closing should also include the submit button.
2) If you're using that button to submit the form, then add type="submit" as an attribute to the form.
check this fiddle for the validation - https://jsfiddle.net/8o0smzth/3/
I have commented out some of part of your code. Please don't hesitate to ask if you have more questions.

Related

how to disable one of the input field if it does not qualify

My problem is how to disable one of the input field if it does not qualify in the following cases: if the user select a cash-In, the input field with the attributes name of credit must be disabled, so that the user can not fill it. vice versa if the user select a cash-Out, then input field with debit attributes name should be disabled.
I tried to create those script, but it does not run properly.
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$('#acc').click(function(){
var account = $("select#acc").val();
if (account == "db"){
$('#credit').prop('disabled', true);
}
else if (account == "cr"){
$('#debit').prop('disabled', true);
}
});
</script>
<table>
<tr><td>Account</td><td>Debet</td><td>Credit</td></tr>
<tr>
<td>
<select id="acc" name="acc" required="required">
<option value=""></option>
<option value="db">Cash-In</option>
<option value="cr">Cash-Out</option>
</select>
</td>
<td><input type="text" id="debit" name="debit" /></td>
<td><input type="text" id="credit" name="credit" /></td>
</tr>
</table>
use .change() event instead of .click() event.
$('#acc').change(function(){
var account = $("select#acc").val();
if (account == "db"){
$('#credit').prop('disabled', true);
$('#debit').prop('disabled', false);
}
else if (account == "cr"){
$('#debit').prop('disabled', true);
$('#credit').prop('disabled', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr><td>Account</td><td>Debet</td><td>Credit</td></tr>
<tr>
<td>
<select id="acc" name="acc" required="required">
<option value="">Select</option>
<option value="db">Cash-In</option>
<option value="cr">Cash-Out</option>
</select>
</td>
<td><input type="text" id="debit" name="debit" /></td>
<td><input type="text" id="credit" name="credit" /></td>
</tr>
</table>
Use this
$('#acc').click(function(){
var account = $("select#acc").val();
if (account == "db"){
$('#credit').attr('disabled', 'disabled');
$('#debit').removeAttr('disabled');
}
else if (account == "cr"){
$('#debit').attr('disabled', 'disabled');
$('#credit').removeAttr('disabled');
}
});
Use change() event, Then switch debit and credit field disabling if the user selected either of the two.
In your case, and you also said, that the field must be enable if the user selected the requirement,
So you should also add a condition that will force the user to select, or else he cannot use the field.
Look at this LIVE DEMO
$('#acc').change(function(){
var account = $(this).val();
if (account == "db"){
$('#credit').prop('disabled', false);
$('#debit').prop('disabled', true);
}
else if (account == "cr"){
$('#debit').prop('disabled', false);
$('#credit').prop('disabled', true);
}
else{
$('#debit, #credit').prop('disabled', true);
}
});

Display HTML on the basis of dropdown menu selected

I have a dropdown menu and on the basis of the item selected I want to display a small part of HTML page.
<select id='menuHandler'>
<option value='abc'> abc</option>
<option value='xyz'>xyz</option>
</select>
IF the selected value is "abc" then a popup button is displayed with the following code:
<button id='runForm' onClick=""> Run form </button>
<div id ="runFormPopup" style=" display:none;">
<table CELLPADDING="10" CELLSPACING="5" class='border'>
<tr>
<td colspan='3'>Run form Generation</td>
</tr>
<tr>
<td width="200" class='border'>
<span>Input Data</span><br>
<input type="checkbox" name="vehicle" >Process log(s)<br>
Summary data<br>
<input type="checkbox" name="vehicle" >Thickness data<br>
<input type="checkbox" name="vehicle" >Particle data
</td>
<td class='border'>
<span>Steps(s)</span>
<input type="checkbox" >
<input type="checkbox" >
<input type="checkbox" >
</td>
</tr>
<tr>
<td> Run form filename </td>
<td><input type="text" ></td>
<td><button class="editbtn">Generate</button></td>
</tr>
</table>
</div>
else if the value selected is "xyz" this should be displayed.
<form action="${ctx}/home/step50/generateReport" method="GET" id="form_generate">
<input style="margin-top: 20px;" type="submit" id="btnGenerate" class="small button active" value="Generate"/>
</form>
how can I do it.
Listen to the change event of the #menuHandler select element, and add the conditional logic there.
Example Here
$('#menuHandler').on('change', function () {
if (this.value === "abc") {
$('#runFormPopup, #runForm').show();
$('#form_generate').hide();
} else {
$('#runFormPopup, #runForm').hide();
$('#form_generate').show();
}
});
..or a shorter version:
Example Here
$('#menuHandler').on('change', function () {
var condition = this.value === "abc";
$('#runFormPopup, #runForm').toggle(condition);
$('#form_generate').toggle(!condition);
});
Try something like this.
$('#menuHandler').change(function(){
var selectedValue = $(this).val();
if(selectedValue === 'abc') {
$('#runFormPopup').show();
$('#form_generate').hide();
}
else {
$('#runFormPopup').hide();
$('#form_generate').show();
}
});
From a high-level perspective:
Create a listener on the button and listen for a click
Dynamically get the value
Either create the content for which you are looking, or insert content into a dynamically-created <div> (overlay, pop-up, etc.)
Following these steps, you should be OK.

Input fields get (readonly) after hit submit button

I have a script which is coded in PHP and smarty and I want to make some changes in this script like in user profile setting when a user click on profile setting and fill the profile data like (full name , email , bank account number , bank name , branch code , tile etc) after fill this information and click the save button the script save all setting but I want to make some of form input fields (readonly) after user submitted his/her data I want make this data (readonly) (bank name , account number , branch code , title) I mean about readonly that after user fill this and save it in profile its show to user (readonly) user can't change it only I can change it from database .
Below is the form code
<form id="settingsform" onsubmit="return submitform(this.id);">
<input type="hidden" name="a" value="submit" />
Bank Name:
</td>
<td><input type="text" name="bank" id="bank" value="{$user_info.bank}"></td>
</tr>
<tr>
<td align="right" width="50%">
Bank Account Number:
</td>
<td><input type="text" name="baccount" id="baccount" value="{$user_info.baccount}"></td>
</tr>
<tr>
<td align="right" width="50%">
Bank Account Title:
</td>
<td><input type="text" name="btitle" id="btitle" value="{$user_info.btitle}"></td>
</tr>
<tr>
<td align="right" width="50%">
Bank Branch Code:
</td>
<td><input type="text" name="bcode" id="bcode" value="{$user_info.bcode}"></td>
</tr>
<input type="submit" name="btn" value="{$lang.txt.send}" class="orange" />
also i am already trying like this below
<script>
function hide(){
document.getElementById("bank").disabled = true;
document.getElementById("baccount").disabled = true;
document.getElementById("btitle").disabled = true;
document.getElementById("bcode").disabled = true;
}
</script>
and
<input type="button" onClick="hide()" value="save">
<input type="text" name="country" value="Norway" readonly>
http://www.w3schools.com/tags/att_input_readonly.asp
Then simply do a check if the POST/GET is set for the field you want to have readonly on ->
<input type="text" name="country" value="Norway" <?php isset($_POST['country']) ? echo 'readonly' : ''; ?> >
UPDATE
<input type="text" name="country" value="Norway" <?php isset($user_info.bank) ? echo 'readonly' : ''; ?> >
Just replace the variable inside of the isset() with the variable of the field, depending on how you initialize the variables you might need to use
empty()
instead, to do so just simply replace isset() with !empty()
The reason for the ! sign is to tell the code to execute the first bit (the echo part) if the variable ISN'T empty
UPDATE 2
<input type="text" name="country" value="Norway" {if isset($user_info.bank) } readonly {/if} >
Above code should work with smarty how ever, the idea is simple, simply have a "if" sentence that checks whether the variable is set/have data, and if it does, then echo 'readonly' in the input field
Try to use attr() in submitform() like,
function submitform(id){
....
....
$('#bank,#baccount').attr('readonly','readonly');
return false;
}
Updated,
function hide(){
$("#bank,#baccount,#btitle,#bcode").prop('disabled', true);
}
Or try,
function hide(){
$("#bank,#baccount,#btitle,#bcode").attr('disabled', 'disabled');
}

hide and show input text based on drop down selection however

hide and show input text based on drop down selection however the "input text" doesn't show anymore when i submit the form and I didn't complete the form validaton.
i am using jquery, and i can show and hide, works perfectly, but this part is bugging me alot.
my customers will not complete all the form fields, so when they submit the form, i would like them to SEE the input text based on their drop down selection, RATHER, the input text is missing.
$(document).ready(function() {
$('#shipping').change(function() {
if ( $("#shipping").val () == "LA")
{
$('#mydiv').show();
}
else
$("#mydiv").hide();
});
});
<select name="shipping" id="shipping">
<option value="LA">LA</option>
<option value="NYC">NYC</option>
</select>
<tr id="mydiv" style="display:none">
<td><input type="text" name="testing"></td>
</tr>
<tr>
<td><input type="text" name="testing2"></td>
</tr>
<tr>
<td><input type="text" name="testing3"></td>
</tr>
<input type="submit" value="Submit" />
what you want to validate.
if textbox is hidden , it should be part of validation or not
if that is part of validation use
$('#id').prop("required", "true");
else
$('#id').removeAttr("required");
Instead of inline styles for this try using a class for hiding it initially like,
<tr id="mydiv" class="hidden">
<td><input type="text" name="testing"></td>
</tr>
CSS: .hidden{display:none;}
and then do,
$(document).ready(function() {
$('#shipping').change(function() {
if ( $("#shipping").val () == "LA")
{
$('#mydiv').show();
}
else
$("#mydiv").hide();
});
});
(OR)
Try to remove 'hidden' class when u want to show the #mydiv
$(document).ready(function() {
$('#shipping').change(function() {
if ( $("#shipping").val () == "LA")
{
$('#mydiv').removeClass('hidden');
}
else
$("#mydiv").addClass('hidden');
});
});
It will work.!!
Look at the jsFiddle here. It works.
I don't see the <table> tag in your html, which is a problem.
<select name="shipping" id="shipping">
<option value="select">Select</option>
<option value="LA">LA</option>
<option value="NYC">NYC</option>
</select>
<table>
<tr id="mydiv" style="display:none">
<td>
<input type="text" name="testing" value="show/hide"/>
</td>
</tr>
<tr>
<td>
<input type="text" name="testing2"/>
</td>
</tr>
<tr>
<td>
<input type="text" name="testing3"/>
</td>
</tr>
</table>
<input type="submit" value="Submit" />
Javascript:
$('#shipping').change(function () {
if ($("#shipping").val() == "LA") {
$('#mydiv').show();
} else $("#mydiv").hide();
});
If you are looking to have the div show when the page reloads with that information you will need to check for the selected information when the page is loading.
Don't make the default display none. Hide it when you load the page.
$(document).ready(function() {
$("#mydiv").hide();
var shipLocation = $("select#shipping").val();
if ( shipLocation == "LA")
{
$('#mydiv').show();
}
then add your shipping change method.

jQuery validation plugin shows validation message too early

I have a search form where different groups of checkboxes are shown depending on what the user chooses in a drop-down. I want to use jQuery validation plugin to check that the user has (a) chosen something in the drop-down, and (b) checked at least one checkbox.
I've gotten this to work, except that the validation message for the checkboxes is behaving strangely. The user can choose a value in the drop-down without problems, but as the user clicks anything on the page (even an empty area), the validation error message for the checkboxes is displayed. Does anyone know what may be causing this?
Here is my JS code for the validation plugin. I chose to have the all validation messages show up next to the drop-down (which has name='to'), rather than next to the checkboxes (which all have class='from_checkbox').
$(document).ready(function(){
// Method for verifying that at least one checkbox has been checked
jQuery.validator.addMethod("atLeastOneChecked", function(value, element, params) {
return $('.from_checkbox:checked').length > 0;
}, jQuery.format("From?"));
// Tell jQuery validation plugin to validate the search form with the proper rules
$("#search_form").validate({
rules: {
'to': {
required: true,
atLeastOneChecked: true
}
},
messages: {
'to': {
required: "To?"
}
}
});
});
Much of the html is generated by php, but the output looks something like this:
<form action="results.php" method="post" id="search_form">
<table>
<tr>
<td>Destination</td>
<td>
<select name="to" onchange='changeFromDiv(options[selectedIndex].value)'>
<option disabled="disabled" selected value="">--select--</option>
<option value="1">Country 1</option>
<option value="2">Country 2</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" id="from_label">Which cities can you travel from?</td>
</tr>
<tr>
<td colspan="2">
<div style="display:none" class="from_div" id="from_1">
<input name="from[3]" type="checkbox" value="3" class="from_checkbox" /> City 3<br />
<input name="from[4]" type="checkbox" value="4" class="from_checkbox" /> City 4<br />
<input name="from[8]" type="checkbox" value="8" class="from_checkbox" /> City 8<br />
</div>
<div style="display:none" class="from_div" id="from_2">
<input name="from[1]" type="checkbox" value="1" class="from_checkbox" /> City 1<br />
<input name="from[6]" type="checkbox" value="6" class="from_checkbox" /> City 6<br />
</div>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" id="submit_button" value="Find best route" onclick="showLoading()" />
</td>
</tr>
</table>
</form>
When you initialize the plugin, just include a setting for the "onfocusout" option:
$("#search_form").validate({
rules: {
'to': {
required: true,
atLeastOneChecked: true
}
},
messages: {
'to': {
required: "To?"
}
},
onfocusout: false
});
That will tell the plugin not to perform validation checks on the "blur" events from elements involved. It'll wait until the form is submitted. There's also an "onkeyup" flag, which probably isn't relevant to you since you're not working with text inputs.

Categories