jQuery validation plugin shows validation message too early - javascript

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.

Related

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

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.

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');
}

Adding a item into a cart automatically using javascript

Hi i have a cart that i want to add a form automatically this code seems to kinda do the trick only the problem is i have to hit F5 for it to add the amount i am quite new to this and cant figure out where i have gone wrong.
<form method="post" action="level3.php" class="jcart" id="foo">
<fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="ABC-8" />
<input type="hidden" name="my-item-name" value="Level 1" />
<input type="hidden" name="my-item-price" value="95.00" />
<input type="hidden" name="my-item-url" value="" />
<table>
<tr>
<td width="65%">
<strong>Level 1 all for £95</strong>
</td>
<td width="15%" align="right">
£95.00
</td>
<td>
<input type="text" hidden ="true" name="my-item-qty" value="1" size="3" hidden="true" />
</td>
<td width="20%" align="center">
<input type="submit" name="my-add-button" id="my-add-button" value="add" class="button" />
</td>
</tr>
</table>
<input type="hidden" name="visited" value="" />
</fieldset>
That is the form that submits the amount into the check out.
<script>
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1)
{
url = document.URL+"#";
location = "#";
} else {
location.reload(true);
document.getElementById("my-add-button").click();// Simulates button click this has to be in as it links to another piece of java that adds the item to the check out with out this it wont add the item
document.foo.submit(); // Submits the form without the button
}
});
</script>
document.getElementById("my-add-button").click();
The code above links to the code below that adds the items from to my knowledge
$('.jcart').submit(function(e) {
add($(this));
e.preventDefault();
});
Thank you in advance for any help or suggestions
If i understand correctly, you increase some value of cart in PHP and than want to update quantity on page without refreshing page.
I made little JSFiddle: http://jsfiddle.net/7SbBA/
Basically use ajax:
$.ajax({
url: 'example.com',
data: /* pass product id here */
success: function(){
/* update quantity you want */
}
});
There is some html change too.
UPDATE
If you want updated total values on page load, just £<span class='amount'><?php echo $product['quantity'] * $product['price'] ?></span> and there is no need to use jquery/js for that. But if you still want dynamically update on window load, i updated my JSFiddle v.2

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.

Categories