I'm creating a registration form with ColdFusion. One of the requirement is for user to select a value from a drop down. When one of the option is selected, the next textbox field need to be fill in so this field becomes required field. If user does not select any option from a drop down then this texfield can be left blank.
I'm not good with Javascript, is there a way to get some free sample?
Here is my form fields:
<cfselect name="OtherContact" class="inputSelect">
<option value="">--- Select other contact ---</option>
<option value="HomePhone">Home Phone</option>
<option value="HomeFax">Home Fax</option>
<option value="HomeEmail">Home Email</option>
</cfselect>
<cfinput type="text" name="OtherContactId" value="#Form.OtherContactId#" class="inputText">
What you need to do is before the form is submitted to see if the dropdownlist selected index is different from 0, if it is, then the text of your textbox must be different from an Empty String. This is an example:
// this is the javascript function that will make sure your criteria is found, if it does, it will return true, false otherwise
function validateSubmit(){
var OtherContact= document.getElementById('<%=OtherContact.ClientID%>')
if (OtherContact.selectedIndex !== 0){
if (document.getElementById('<%=OtherContactId.ClientID%>').value === ""){
return false;
}
}
return true;
}
So, before you submit (or do whatever you want to do after the validation), you can do this:
// function that submits
function submit(){
if (validateSubmit()){
// your code in case validation is passed.
}
else{
// your code in case validation is not passed.
}
}
Good luck.
Related
I have some code in which two select boxes are present. One select is dynamically changing its value with respect to the first one. The first select box is this in which some values are coming from backend using PHP.
<select class="form-control" name="tsm_id" id="tsm_id">
<option value=""><b>SELECT TSM</b></option>
<?php echo fill_year($connect); ?>
</select>
A second select box is this which is dependent on the first one. When any value in the first box is selected this select box change its value dynamically.
<select class="form-control" name="sr_id" id="sr_id">
<option value="" selected>SELECT SR</option></select>
But the problem is this that when I select any value in first select box then the selected value SELECT SR disappears and only values from backend comes there. I want that if anyone select value from first select box then SELECT SR remains there as selected value the rest values comes below that. I am using javascript code to append those options.
$(document).ready(function(){
$('#tsm_id').change(function(){
var tsm_id = $(this).val();
$.ajax({
url:"http://localhost/salesforce/fetch_sr.php",
method:"GET",
data:{tsm_id:tsm_id},
dataType:"json",
success:function(data){
// var data=JSON.stringify(data);
$('#sr_id').html('');
for (var i in data)
{
$("#sr_id").append("<option value="+data[i].employee_id+">"+data[i].employee_name+"</option>");
}
}
});
});
});
Can anyone tell me what am I doing wrong in this.
What i want is if someone selects value from the first select box then second select box remains same as in image with selected value set to SELECT SR and the options should be appended below it.
I want something like this:
I don't want like this if I am selecting a value from the first select box then the second select box displaying options, not the default value.
Presently I am getting like this:
$('#sr_id').html('');
This is removing the default option on ajax success.
You might want to use:
$('#sr_id').html('<option value="" selected>SELECT SR</option>');
You're currently removing all options in your ajax callback before you loop out the new ones.
If you change
$('#sr_id').html('');
to
$('#sr_id').html('<option value="" selected>SELECT SR</option>');
that option will always be the first (and selected) value.
So I have an odd behavior that I want to implement on my dropdown. I have two scenarios and both will have different default selected values.
Scenario 1: If user role is admin, then dropdown will not be disabled and 'Select Location' placeholder will show up as selected default.
Scenario 2: if user role is clerk, then dropdown will be disabled and the selected value will be a specific location from the dropdown selection.
While I got the role permission and disabled/enabled thing setup, I'm not sure how to dynamically change the selected value of the dropdown. This is inside reactive forms form group, so not sure I can use ngModel or can I?
Here's my dropdown:
<select [ngModel]="null" formControlName="location" required >
<option value="null" disabled>{{'SelectLocation' | translate}}</option>
<option selected *ngFor="let store of location" [ngValue]="store._storeKey">{{ store._storeName }}</option>
</select>
Here's the check I have that disables/enables the dropdown:
checkUserPermissions() {
if (this.userPermissions._userPrivilegeKey === 100) {
//TODO: Default to store2 of list for example
this.transactionForm.controls['location'].value = stores._store; // This is right?
this.transactionForm.controls['location'].disable();
} else if (this.userPermissions._userPrivilegeKey === 200) {
//TODO: Default to select location placeholder (currently working)
this.transactionForm.controls['location'].enable();
}
}
You should use the patchValue function instead of directly assigning the value when dealing with forms
this.transactionForm.controls['location'].patchValue(stores._store)
I want to validate a form, when it gets submitted. I need to check the following things:
Whether the user has selected any option from the dropdown.
Whether the user has entered a value larger than the max-value
If any of this conditions is not matched, I want to show an error message in a modal window...
How can I achieve this behaviour? Below is a code snippet:
//This function sets max value, based on selected option's data-max
$('select').change(function(e) {
var selectedIndex = $('select').prop("selectedIndex");
var selectedOption = $('select').find("option")[selectedIndex];
$('input[type=number]').attr('max', $(selectedOption).data('max'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="./cart_update.php">
Select Size:
<select size="1" name="options" class="selectsize">
<option value="">-- Select --</option>
<option value="30" data-max="50">30</option>
<option value="31" data-max="50">31</option>
<option value="32" data-max="40">32</option>
<option value="33" data-max="50">33</option>
<option value="34" data-max="50">34</option>
</select>
Quantity
<input type="number" class="cart_qty" name="product_qty" size="1" value="1" min="1" max="100" />
<button class="orange medium full add-to-cart" type="submit">Add To Cart</button>
</form>
As you didn't give any information on whether you validate the form data within the backend as well, I assume that you don't.
Validating form data only on the client side (i.e. within the client's webbrowser) is not advisable. That is because clients can easily manipulate the javascripte code you're using to validate data. By doing so, it is possible to import fraudulent data into your application (and many many more bad things could happen).
Validating data on the client side should only be used to give your users a quick feedback on whether the entered information is correct and in accordance to your definitions. Real data validation, before you further use it within your application (i.e. store it within a database, or what ever), should happen on the server side.
I advise you reading these articles to further deep dive into the topic of data validation:
Data form validation (mozilla.org)
If you're using PHP as a server-side language: PHP 5 Form Validation (w3schools.com) or if you're using javascript as a server-side language: How to Easily Validate Any Form Ever Using AngularJS(thecodebabarian.com)
Web Form Validation: Best Practices and Tutorials (smashingmagazine.com)
Coming to your question (and assuming you read the articles and now want to validate the data only for the user's sake), here's kind of a commented working code snippet:
$(document).ready(function () {
// Whenever your form is submitted, execute this function
$('#ourForm').submit(function (e) {
// Prevent the browser from executing the default behaviour -> submitting the form
e.preventDefault();
// Now check the user's entered information for accordance to your definitions
// #1: Check whether any checkbox is ticked
var checkBoxValue = $('#ourCheckbox').val();
// If checkBoxValue is undefined, there is no checkbox selected,
if (!checkBoxValue) {
// There is no checkBox ticked, throw error
alert('Please select a checkbox!');
return false;
}
// #2: Check whether entered value is smaller than the data-max field of the selected checkbox
// Receive the user's entered value
var enteredValue = $('#ourInputfield').val();
// Receive the max value specified by you from the data-max field
var maxValue = $('#ourCheckbox option:selected').attr('data-max');
// If the entered value is bigger than the max-data value
if (enteredValue > maxValue) {
// The entered value is bigger than the data-max field of the selected checkbox, throw error
alert('Your entered value is to large, please choose a value lower than ' + checkBoxValue.value);
return false;
}
// Validating your form data is finsihed, go on with the real work
alert('Your data looks fine, whoooo!');
});
});
Here's a working JSFiddle: https://jsfiddle.net/77v1z18v/1/
I have an address form and I want to have a select box for states if the country is the U.S. and change it to a textbox if it's a foreign country so that the state/province can be typed in.
I generate the code in PHP (such as the states select and country select) and I was thinking of outputting both the select and textbox and initially hiding and disabling the textbox, then if the user changes the country unhide and enable the textbox and hide and disable the select.
My question is, is it valid if both inputs have the same name, assuming one of them will be disabled when the form is submitted?
As a bonus question, is there a better way of doing this?
Yes, it is possible and it is the best way to do this, since disabled inputs are not sent along in the request and it generates a valid and semantic HTML.
As show in w3:
When set, the disabled attribute has the following effects on an element:
Disabled controls do not receive focus.
Disabled controls are skipped in tabbing navigation.
Disabled controls cannot be successful.
[...]
In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.
Assuming you use jQuery, you could do something like this:
HTML:
<select id="countries">
<option>Countries</option>
</select>
<select id="states" style="display: none"> <!-- States in US -->
<option>States</option>
</select>
<textarea id="address" style="display: none">
</textarea>
JS:
// Cache states list and address box beforehand so we don't have to query every time.
var $states = $("#states"),
$address = $("#address");
$("#countries").change(function () { // Bind to change event for checking if US selected
var isUnitedStates = $(this).val() == "United States";
if (isUnitedStates) { // US is selected, show States
$states.attr("id", "address").show()
$address.attr("id", "_address").hide()
} else { // US is not selected, show Address box
$states.attr("id", "_address").hide()
$address.attr("id", "address").show()
}
})
This is not very convenient but if you really want to make sure, this is an option for you.
Couldn't find anything quite what I was looking for but if I've missed something obvious I'm sorry. I'm basically trying to have a JavaScript function check that each of a number of select boxes have unique values before the form is submitted to then be entered into a database.
There could be any number of select boxes but all follow a similar naming format in the form of:
operator_address_type_0
operator_address_type_1
operator_address_type_2
etc.
I was just wondering how a JavaScript function could be set up to loop through all of the select boxes and alert the user and stop the submitting if any are found to have the same value.
Thanks for any help.
EDIT:
Here is some simplified HTML of my current select boxes. I've had to simplify it a lot as the table that they are in is all loaded via AJAX from querying a database.
<select name="operator_address_type_0">
<option value="Main">Main</option>
<option value="Payment">Payment</option>
<option value="Poster">Poster</option>
</select>
<select name="operator_address_type_1">
<option value="Main">Main</option>
<option value="Payment">Payment</option>
<option value="Poster">Poster</option>
</select>
It is like that but there could be more options in the future, I just want to check that there is only one main address, one payment address, one poster address etc.
Something like the following?
function checkDuplicates() {
var selects = document.getElementsByTagName("select"),
i,
current,
selected = {};
for(i = 0; i < selects.length; i++){
current = selects[i].selectedIndex;
if (selected[current]) {
alert("Each address type may not be selected more than once.");
return false;
} else
selected[current] = true;
}
return true;
}
Demo: http://jsfiddle.net/GKTYE/
This loops through the selects and records the selected index of each, stopping if a duplicate is found. This assumes all the selects have the same options in the same order. To test the actual selected values:
current = selects[i].options[selects[i].selectedIndex].value;