How to validate that the user selected in select form - javascript

I have select form:
<form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt">
<select style="background: transparent; border-bottom:5px;" name="subname" class="required">
<option value="" > Choose subject </option>
<option value="aaa" > AAA </option>
<option value="bbb" > BBB </option>
</select>
<input type="submit" value="post" name="txt" class="btn" id="post_button" onClick="time_get()">
</form>
I want to put alert label if the user pressed "post", but didn't choose a subject
Edit- thanks to maihan's answer I could fix it:
function time_get()
{
var selected = document.getElementById("select_post_id");
var selectedVal = selected.options[selected.selectedIndex].value;
if(selectedVal != ""){
//do whatever
}else{alert('select an option');}
}

Place the logic in time_get() function you have.
if(document.getElementsByTagName(select).value ==''){
alert("Select an option")
}

You can add an event handler on the form to prevent submitting it if the select has no value, then show an alert or add/unhide a warning <label>.
$('form#post_txt').submit(function(event){
var subname = $('select[name="subname"]').val()
if(subname === null || subname === "") {
event.preventDefault();
//warn user
}
});
I would also recommend adding selected="selected" as an attribute on your first select option, so that it will be selected from the start, instead of a blank select.

Maihan's answer is great, but just to improve, I would make the value of 'Choose Subject', 'NULL' and then validate using the if statement
<form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt">
<select style="background: transparent; border-bottom:5px;" name="subname" class="required">
<option value=NULL > Choose subject </option>
<option value="aaa" > AAA </option>
<option value="bbb" > BBB </option>
</select>
<input type="submit" value="post" name="txt" class="btn" id="post_button" onClick="time_get()">
Then... js...
function time_get(){
if(document.getElementByClassName(required) != NULL){
//do whatever
}else{alert('select an option')}
}

Related

Redirect on submit based on search query and location

I am trying to add a search feature based on a text input and a drop-down.
So I am trying to make it work with the following form fields:
Text input {text_1}
Drop-down (2 options)
Submit button
If first option is selected in the drop-down the form should be submitted to https://url1/?={text_1}, if second option is selected it should be submitted to https://url2/?={text_1}.
I have written so far:
<form>
<input type="text" id="text_1" name="text_1" value="test" data-alias="" class="form-control">
<select id="selectlist_1" name="selectlist_1" data-alias="" class="form-control">
<option value="option_1" >Option_1</option>
<option value="option_2" >Option_2</option>
</select>
<button type="submit" id="button_1" name="button_1" class="btn btn-primary" >Submit</button>
</form>
Otherwise, there is also this example: https://hii.com/careers/
I give you an example:
<script>
function go(v){
if (v.url.value===1){
v.action="http://www.google.com"
}else {
v.action="http://www.apple.com"
}
}
</script>
<form onsubmit="go(this)">
<input type="text" name="text_1" value="txt">
<select name="url">
<option value="1">Google</option>
<option value="2">Apple</option>
</select>
<input type="submit" value="submit">
</form>
Augment a simple form with the controls you want, with a script that sets up a behaviour where the form's action attribute value changes with the selection in the drop-down control:
<form>
<input name="foobar" />
<select name="fruit">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
</select>
<script>
(script => {
const fruit_control = script.closest("form").elements.fruit;
fruit_control.addEventListener("change", ev => {
ev.target.form.action = ({
"apples": "https://url_1",
"oranges": "https://url_2"
})[ev.target.value];
});
})(document.currentScript);
</script>
</form>
The value of the text input control will be sent with the query string, i.e. as ?foobar=... at the end of the URL, as the form is submitted, to the URL that's correspondent with the option selected in the drop-down.
Whether you have a submit button at the end of the form, or not, makes no difference to the behaviour of the form because a form may be submitted even without a submit button.
I found a working solution after doing some searches.
Here is solution in case anyone need it.
jQuery('#search_page_form').submit(function() {
// get all the inputs into an array.
var stext = jQuery('#search_page_form #looking-for').val();
var cars = jQuery('#search_page_form #cars').val();
var url = '';
if(cars == 'nns'){
var url = 'https://careers.huntingtoningalls.com/search/?searchby=location&createNewAlert=false&q='+stext;
}else if(cars == 'mt'){
var url = 'https://tsd-careers.hii.com/en-US/search?keywords='+stext;
}else if(cars == 'is'){
var url = 'https://careers.huntingtoningalls.com/search/?searchby=location&createNewAlert=false&q='+stext+'&locationsearch=Pascagoula%2C+MS&geolocation=';
}else if(cars == 'ch'){
var url = 'https://careers.huntingtoningalls.com/search/?searchby=location&createNewAlert=false&q='+stext+'&locationsearch=Newport+News%2C+VA&geolocation=';
}
if(url != ''){
window.open(url, '_blank');
}else{
alert('Please select Division');
}
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="search_page_form" onsubmit="return false;">
<div class="form-group">
<label for="looking-for">What are you looking for ?</label>
<input type="text" id="looking-for" name="looking-for" class="form-control" placeholder="Enter keywords....">
</div>
<div class="form-group">
<select id="cars" name="cars" class="form-control nice-select">
<option selected="" value="">Division</option>
<option value="nns">NEWPORT NEWS SHIPBUILDING</option>
<option value="mt">MISSION TECHNOLOGIES</option>
<option value="is">INGALLS SHIPBUILDING</option>
<option value="ch">CORPORATE HEADQUARTERS</option>
</select>
</div>
<div class="form-group">
<input type="submit" value="SEARCH" class="btn white-btn search_btn">
</div>
</form>

Change form action based on form select field

I can't get the form action to change based on a user's drop-down selection. What I want to do is have the form redirect to a different page, then the default for the form if a user selects "Student Loans" from the select field named "agency".
In other words, what I want to do is that if someone select "student loans" for the agency, I want the page to submit to /quote/quotes-sl.php instead of quote/quotes.php (the default of the form).
Here is my form code:
<form id="tdhcustom-pre-1-form" accept-charset="UTF-8" onsubmit="submit_function(this)" action="/quote/quotes.php" method="post" name="tdhcustom-pre-1-form">
<input id="edit-lead-source-description" name="lead_source_description" type="hidden" value="test" />
<label class="edit-owed" for="edit-owed"> Amount Owed: <span class="form-required" title="This field is required.">*</span>
</label><select id="owed" class="form-select required" name="owed">
<option selected="selected" value="">Select...</option>
<option value="$10,000 to $14,999">$10,000 to $14,999</option>
<option value="$15,000+">$15,000+</option>
</select>
<label class="edit-agency" for="edit-agency"> Problem With: <span class="form-required" title="This field is required.">*</span>
</label><select id="agency" class="form-select required" name="agency">
<option selected="selected" value="">Select Agency...</option>
<option value="Student Loan" data-action="/quote/quotes-sl.php">Student Loan</option>
<option value="FEDERAL">Federal Taxes</option>
<option value="STATE">State Taxes</option>
</select></div>
<input id="edit-submit" class="form-submit" height="31" name="submit" src="test.com/test.jpg" type="image" value="Submit" width="214" />
<input id="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" name="form_build_id" type="hidden" value="form-5ezy7kqpVIYFiVUgKIyxbp4n6MQ7ZqHuo33GJbq0QZE" />
<input id="edit-tdhcustom-pre-1-form" name="form_id" type="hidden" value="tdhcustom_pre_1_form" />
</form>
Here is the javascript:
<script>
function submit_function(form) {
var selected = document.getElementById('Agency');
var dataset = selected[selected.selectedIndex].dataset;
if (dataset.action) {
form.action = dataset.action;
}
return true;
};
</script>
Add trigger on selected option val = "Student Loan" , then change attribute "action" form to url "/quote/quotes-sl.php"
$('#agency').on('change',function(){
var selected = $(this).val();
if(selected == "Student Loan")
$('#tdhcustom-pre-1-form').prop('action',"/quote/quotes-sl.php");
});
CMIIW :D
You want to change the form action based on an onchange event from your <select> ... but you'll also want to remove the onsubmit attribute from your form, like so:
<form id="tdhcustom-pre-1-form" accept-charset="UTF-8" action="/quote/quotes.php" method="post" name="tdhcustom-pre-1-form">
Assuming you're going to have data attributes on all the options like this:
<select id="agency" class="form-select required" name="agency">
<option selected="selected" value="">Select Agency...</option>
<option value="Student Loan" data-action="/quote/quotes-sl.php">Student Loan</option>
<option value="FEDERAL" data-action="/quote/quotes-s2.php">Federal Taxes</option>
<option value="STATE" data-action="/quote/quotes-s3.php">State Taxes</option>
</select>
You can just replace your <script> block with:
<script>
(function() {
var theForm = document.getElementById('tdhcustom-pre-1-form');
var theSelector = document.getElementById('agency');
theSelector.onchange = function() {
theForm.action = theSelector[theSelector.selectedIndex].getAttribute('data-action');
}
})();
</script>
That's pure JavaScript - so without jQuery (or any other framework).

Validating Paired Form Fields

I am trying to create what I hope is a somewhat simple donation form. There are two options to choose from:
A drop down with a text field to enter an amount
A text field to write in an other designation along with a text field to enter an amount
I've been looking through a lot of different examples of code, but I'm not entirely sure how to search the technical name for what I need. I need to have an alert appear when nothing is entered as well as an alert when only one part of 1 or one part of 2 is entered. I know this is something I need JS for, but have zero experience with it.
I found several pages that were a little helpful with validation and alert messages for multiple fields, but I think I need to have an either/or type of alert (if that makes sense). EITHER you choose from the drop down and enter an amount OR you enter something in the "Other" text field and enter an amount.
You can see my code below. I included some JS I found and tried to modify that seemed to be closest to what I'm looking for, but with my limited knowledge of the language I know it's not correct (try not to judge me). I can get an alert message that works sometimes and not for everyone. And sometimes the alert still appears when it's filled out correctly.
I feel like my brain is fried at this point, so any help you can provide is greatly appreciated. Javascript is definitely going to the top of my "Must Learn" list after this. Thank you!
<script>
function validateForm() {
var x = document.forms["form1"]["FUND1"].value;
var x = document.forms["form1"]["FUND2"].value;
var x = document.forms["form1"]["GIFT_AMOUNT1"].value;
var x = document.forms["form1"]["GIFT_AMOUNT2"].value;
if (form1.FUND1.value == '' && form1.FUND2.value == '') {
alert("Please select a donation designation and an amount.");
return false;
}
if (form1.GIFT_AMOUNT1.value == '' && form1.GIFT_AMOUNT1.value == '') {
alert("Please select a donation designation and an amount.");
return false;
}
}
</script>
<form name="form1" method="POST" action="input.php" id="form1" onsubmit="return validateForm()" >
<div class="giving_dropdown body_copy">
<h3>Giving Opportunities</h3>
<select name="FUND1" class="drop_down" >
<option value="" selected class="body_copy"></option>
<option value="Option1" class="body_copy">Option1</option>
<option value="Option2" class="body_copy">Option2</option>
<option value="Option3" class="body_copy">Option3</option>
<option value="Option4" class="body_copy">Option4</option>
<option value="Option5" class="body_copy">Option5</option>
<option value="Option6" class="body_copy">Option6</option>
<option value="Option7" class="body_copy">Option7</option>
<option value="Option8" class="body_copy">Option8</option>
<option value="Option9" class="body_copy">Option9</option>
<option value="Option10" class="body_copy">Option10</option>
<option value="Option11" class="body_copy">Option11</option>
</select>
<input class="inputotherfund" name="GIFT_AMOUNT1" type="text" size="10" id="GIFT_AMOUNT1" value="0.00"/>
</div>
<div class="other_designation">
<h3>Other</h3>
<input name="FUND2" type="text" size="50" id="FUND2" class="inputotherfund" placeholder="Indicate where to direct donation"/>
<input class="inputotherfund" name="GIFT_AMOUNT2" type="text" size="10" id="GIFT_AMOUNT2" value="0.00"/>
</div>
<div style="clear:both; float:left;">
<p><input type="submit" value="Continue" class="continue_button" onclick="validateAndSend()"></p>
</div>
What you are doing is ok.
To improve what you are doing you can try this:
I'm paring FUND and GIFT_AMOUNT because I guess is what you are trying to do, now the alert will show when both 1s or 2s are empty.
function validateForm() {
var form1 = document.forms['form1']
if (form1.FUND1.value === '' || form1.GIFT_AMOUNT1.value === '') {
alert("please select a donation designation and an amount 1.");
return false;
}
if (form1.FUND2.value === '' || form1.GIFT_AMOUNT2.value === '') {
alert("please select a donation designation and an amount 2.");
return false;
}
return true;
}
In your form you need to initialize your GIFT_AMOUNT inputs with value="" otherwise if you compare '0.00' with '' always will be false.
<form name="form1" method="POST" action="input.php" id="form1" onsubmit="return validateForm()" >
<div class="giving_dropdown body_copy">
<h3>Giving Opportunities</h3>
<select name="FUND1" class="drop_down" >
<option value="" selected class="body_copy"></option>
<option value="Option1" class="body_copy">Option1</option>
<option value="Option2" class="body_copy">Option2</option>
<option value="Option3" class="body_copy">Option3</option>
<option value="Option4" class="body_copy">Option4</option>
<option value="Option5" class="body_copy">Option5</option>
<option value="Option6" class="body_copy">Option6</option>
<option value="Option7" class="body_copy">Option7</option>
<option value="Option8" class="body_copy">Option8</option>
<option value="Option9" class="body_copy">Option9</option>
<option value="Option10" class="body_copy">Option10</option>
<option value="Option11" class="body_copy">Option11</option>
</select>
<input class="inputotherfund" name="GIFT_AMOUNT1" type="text" size="10" id="GIFT_AMOUNT1" value="" />
</div>
<div class="other_designation">
<h3>Other</h3>
<input name="FUND2" type="text" size="50" id="FUND2" class="inputotherfund" placeholder="Indicate where to direct donation" />
<input class="inputotherfund" name="GIFT_AMOUNT2" type="text" size="10" id="GIFT_AMOUNT2" value="" />
</div>
<div style="clear:both; float:left;">
<p>
<input type="submit" value="Continue" class="continue_button" />
</p>
</div>
</form>
There is no need to call a function in your onclick property because you are calling the submit function already to improve this behavior you can do something like this:
function submitForm() {
if (validateForm()) {
// do some stuff
}
}
and change the onsubmit property from your form
<form ... onsubmit="submitForm()">
If you are starting with javascript will be a good idea to learn how to use the console in order to debug your scripts. This article is a good point to start and as a last tip check this out.

validation for select option not working

I doing a form for a small project, and having a trouble trying to validate the select option
hope someone can help
THanks in advance
HTML:
<form method="post" name="vehicleform" action=" " onSubmit="return (validateForm())">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
Phone Number <font size="1px">(ex. 123-456-7890)</font>: <input type="text" name="phonenumber"><br>
Location
<select name="location">
<option value="-1">Select one..</option>
<option value="lota">Lot A</option>
<option value="lotb">Lot B</option>
<option value="lotc">Lot C</option>
</select><br>
JS:
function validateForm(){
var d = document.forms['vehicleform']['location'].value;
if( document.vehicleform.location.value == "-1" )
{
alert("Please select your location");
return false;
}
}
There is no need for grouping in the listener, and passing this gives immediate access to the form:
<form ... onsubmit="return validateForm(this)">
You only need to check the selected index to see if something other than the first option (or no option all) is selected:
function validateForm(form) {
if (form.location.selectedIndex < 1) {
alert("Please select your location");
return false;
}
}
And as suggested in the comments, make the first option selected by default:
<select name="location">
<option value="-1" selected>Select one..
<option value="lota">Lot A
as browsers may not make any option selected by default and users won't see "Select one...". That should be a label anyway to assist with accessiblity.
http://jsfiddle.net/LVBSZ/1/
You have no submit button in your code and close tag for form. The other works for me
<script>
function validateForm() {
if (document.forms['vehicleform'].location.value == "-1") {
alert("Please select your location");
return false;
}
}
</script>
<form method="post" name="vehicleform" onSubmit="return validateForm()">
First Name:
<input type="text" name="fname">
<br>Last Name:
<input type="text" name="lname">
<br>Phone Number <font size="1px">(ex. 123-456-7890)</font>:
<input type="text" name="phonenumber">
<br>Location
<select name="location">
<option value="-1">Select one..</option>
<option value="lota">Lot A</option>
<option value="lotb">Lot B</option>
<option value="lotc">Lot C</option>
</select>
<br>
<input type="submit" value="Submit">
</form>

Display HTML while <option> is viable selection

I have something like the below:
<select name="blah">
<option disabled="disabled" selected="selected">Select an option</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select><br/>
<input type="submit" value="Submit"/>
I want it such that the submit button only appears if the user has selected an option with value >= 1 So on page load it will not display the submit button because the currently selected option has no value, but the moment a user selects a valid option, the submit button appears.
Is this something that can be accomplished with JS/JQ?
If you don't want to display submit button when page loads then add below css
input[type=submit] {display:none;}
To show submit button on value changes try below js code
$(function(){
$('select').change(function(){
var value = parseInt($(this).val().replace(/[^0-9-]/,""),10)
if(value >= 1)
{
$('input[type=submit]').show();
}
});
});;
Working Demo
Try following code in java script
function isSelected() {
var value =document.getElementById("blah").selectedIndex;
if(value >='1'){
document.getElementById('btnSubmit').style.display='block';
}else{
document.getElementById('btnSubmit').style.display='none';
}
}
Your HTML
<select id="blah" onChange="isSelected();">
<option disabled="disabled" selected="selected">Select an option</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select><br/>
<input type="submit" value="Submit" style="display:none" id="btnSubmit"/>
change this
<input type="submit" value="Submit"/>
to
<input type="button" value="Submit" id="submit"/>
in jQuery:
$(document).ready(function(){
$('#submit').click(function(){
if($('select[name="blah"]').val() > 1)
$('#yourform').submit();
else
alert('selected value > 1');
});
});
you form need to have an id for example, in my case yourform
DEMO

Categories