I have the following select with a submit button.
I would really like for the option selected to redirect to my route without me needing to press a submit button, so I could get rid of it.
<form action="{{ url_for("perfumes.filters") }}" class="search-form">
<div class="form-group">
<label for="exampleFormControlSelect1">Filter by Type</label>
<select class="form-control" id="filter_query" name="filter_query" onchange="checkSelected()">
<option selected='true' name="" value="" id="">Please select a type</option>
{% for type in types %}
<option value="{{type['type_name']}}" id="{{type['type_name']}}" name="{{type['type_name']}}">{{type['type_name']}}</option>
{% endfor %}
<option value="{{ url_for('types.new_type') }}">Create new type...</option>
</select><br>
<button class="btn btn-primary btn-sm" type="submit">Submit</button>
</div>
</form>
The last option (Create New Type) is already redirecting to its corresponding route with this function.
function checkSelected() {
const selected = document.getElementById("filter_query");
const option = selected.options[selected.options.length - 1];
if (option.selected == true) {
window.location = option.value;
}
}
What would be the best way to adapt that function so I can suppress the "Submit" button and have the redirect automatically triggered on selection?
UPDATE:
This is all now working well, but I get a console error when the option outside the loop gets selected
<form id="form" action="{{ url_for("perfumes.filters") }}" class="search-form">
<div class="form-group">
<label for="exampleFormControlSelect1">Filter by Type</label>
<select class="form-control" id="filter_query" name="filter_query">
<option selected='true' name="" value="" id="">Please select a type</option>
{% for type in types %}
<option value="{{ url_for('perfumes.filters', filter_query=type['type_name']) }}">{{type['type_name']}}</option>
{% endfor %}
<option value="{{ url_for('types.new_type') }}">Create new type...</option>
</select><br>
<button class="btn btn-primary btn-sm" type="submit">Submit</button>
</div>
</form>
And the script:
function checkSelected() {
if (this.value) window.location = this.value;
}
const EL_select = document.querySelector("#filter_query");
EL_select.addEventListener("change", checkSelected);
If I got your question correctly, you want to:
Last option (having a value of i.e: "some/route") should navigate to that route
All other options (which value is not empty) should submit the form immediately
If so than this might help:
function checkSelected() {
if (this.value === "some/route") return (window.location = this.value);
if (this.value) this.form.submit();
}
const EL_select = document.querySelector("#filter_query");
if (EL_select) EL_select.addEventListener("change", checkSelected);
<form>
<select class="form-control" id="filter_query" name="filter_query">
<option selected value="">Please select a type</option>
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="etc">etc</option>
<option value="xxx">Create new type...</option>
</select>
</form>
PS:
Stop using inline JS (onchange="checkSelected()")
SELECT should have the name attribute, not OPTION elements
You can invoke submit() method programmatically when option change.
const form = document.querySelector("form");
const select = document.querySelector("select");
select.addEventListener("change", (event) => {
const value = event.target.value;
console.log(value);
form.submit();
})
<form id="form" action="{{ url_for("perfumes.filters") }}" class="search-form">
<select name="filter_query" id="select">
<option>Select Option</option>
<option>Option 1</option>
<option>Option 2</option>
<select>
</form>
I assume that you want to redirected to some /filte_selected/<id> type of URL, on selecting an option.
You can do the following change for option tag:
<option value="{{ url_for('filter_selected', id=type['type_name']) }}" id="{{type['type_name']}}" name="{{type['type_name']}}">{{type['type_name']}}</option>
You can change your scrip to:
<script>
function checkSelected() {
var selectedValue = document.querySelector('#options').value
if (selectedValue) {
window.location = selectedValue;
}
}
</script>
You can actually pull the selected value directly off of the select element. Then, simply redirect users to that value.
function checkSelected() {
const value = document.querySelector("#select-id").value;
console.log(value);
// window.location = value;
}
<select id="select-id" onchange="checkSelected()">
<option value="option 1">option 1</option>
<option value="option 2">option 2</option>
</select>
Related
I'm basically trying to create a form , with 2 dropdowns and pass the values from select as URL parameters through a from submit button ,
<form action="">
<select id="Select1">
<option value="1">Tshirt</option>
<option value="2">Hat</option>
<option value="3">Sweater</option>
<option value="4">Hoodie</option>
</select>
<select id="Select2">
<option value="1">Red</option>
<option value="2">Yellow</option>
<option value="3">Pink</option>
</select>
<input type="submit" value="Submit">
</form>
If none of the dropdowns are selected , the url should be : domain.com
If the first value is selected , the url should be : domain.com/Tshirt
Otherwise if both options are selected , the url should be : domain.com/Tshirt/Red
Thanks a lot !
Add click event listener on submit button and get text property of selected dropdown option.
const submitBtn = document.querySelector("#submitBtn");
submitBtn.addEventListener("click", () => {
const select1 = document.querySelector("#Select1");
const select2 = document.querySelector("#Select2");
const val1 = select1.options[select1.selectedIndex].text ?? "";
const val2 = select2.options[select2.selectedIndex].text ?? "";
const url = `domain.com/${val1}/${val2}`;
console.log(url);
})
<html>
<head></head>
<body>
<select id="Select1">
<option value="1">Tshirt</option>
<option value="2">Hat</option>
<option value="3">Sweater</option>
<option value="4">Hoodie</option>
</select>
<select id="Select2">
<option value="1">Red</option>
<option value="2">Yellow</option>
<option value="3">Pink</option>
</select>
<input id="submitBtn" type="submit" value="Submit">
</body>
</html>
Right now I have a list of forms being displayed by Django:
{% for form in forms %}
<form method="post" class="{{ form.css_class }}"novalidate>
{% csrf_token %}
{% include 'bs4_form.html' with form=form %}
<input type="hidden" name="selected_form" value="{{ forloop.counter0 }}">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endfor %}
I also have a dropdown being rendered above the forms:
<label>Choose a component to modify:
<select class="rule-component" name="component">
<option value="">Select One …</option>
<option value="0">Option 0</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</label>
My question is, how would I go about displaying no form when the page is entered, and a single form that corresponds with the dropdown value when that is selected?
I've attempted something with JavaScript, but I'm not very familiar with it and I'm not sure how to get this to interact with the django templating language. The code below allows me to log the form element I want to display by linking it with the forloop.counter:
<script type="text/javascript">
const formElement = document.querySelector(".rule-component")
formElement.addEventListener('change', (event) => {
const selectElement = document.querySelector("form input[value='" + formElement.value + "']").parentNode;
console.log(selectElement)
const result = document.querySelector('.result');
result.textContent = `You like ${selectElement.className}`;
});
</script>```
I figured it out, was just some JavaScript that needed to be linked up to an array, 'ids' with the css_classes in the Django forms:
<script type="text/javascript">
const ids=["jira-label", "label-rule-category"]
const dropDown = document.getElementById("rule-component");
dropDown.onchange = function() {
for(var x = 0; x < ids.length; x++) {
console.log(ids[x])
document.getElementById(ids[x]).style.display = "none";
}
console.log(this.value)
document.getElementById(this.value).style.display = "block";
}
</script>
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).
In this case, only primary dropdown will change, other dropdowns' values will change automatically according to it (so users wont be changing them) I'm trying to get the Option's TEXT value using PHP with $_POST. But i can only get it when i manually changed the other dropdown .
I have tried to use the trigger() method, but it fails to get the option text value. Any idea why the code fails to work. Thank you.
function setDropDown() {
var index_name =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.querySelectorAll('.secondary');
for (var i = 0; i < others.length; i++) {
others[i].selectedIndex = index_name;
}
}
<!-- try to get the option text value and pass it to input field-->
<!-- Then in the php code use $_POST[] to retrieve the input value-->
function setTextField(ddl) {
document.getElementById('make_text').value = ddl.options[ddl.selectedIndex].text;
}
$("select").trigger("change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<div><b>Primary dropdown:</b>
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</div>
<div>
<b>Other dropdown 1</b>:
<select class='secondary' id="Qualifications" name="Qualifications" onChange="setTextField(this)">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select></div>
<input id="make_text" type="hidden" name="make_text" value="" />
<div> <b>Other dropdown 2</b>:
<select class='secondary' id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</form>
PHP Code
$value =$_POST['make_text'];
Html element <select> onchange doesn't fire for programmatic changes, you need to fire it yourself with
$(".secondary").trigger("change");
or by Id
$("#Qualifications").trigger("change");
The problem is that your hidden <input> never had the value. if you remove the hidden it on your code you can check it.
So when you POSTED the values the value on make_text was empty string. So if you fire the trigger after the for loop then it will work.
function setDropDown() {
var index_name = document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.querySelectorAll('.secondary');
for (var i = 0; i < others.length; i++) {
others[i].selectedIndex = index_name;
}
$("#Qualifications").trigger("change");
}
function setTextField(ddl) {
document.getElementById('make_text').value = ddl.value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<div><b>Primary dropdown:</b>
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</div>
<div>
<b>Other dropdown 1</b>:
<select class='secondary' id="Qualifications" name="Qualifications" onChange="setTextField(this)">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select></div>
<input id="make_text" name="make_text" value="" />
<div> <b>Other dropdown 2</b>:
<select class='secondary' id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</form>
I have to say that I don't see any need to use a hidden input text to POST data to PHP because you can just post the value of the <select> and retrieve it in PHP like this $force = $_POST["ForceSelection"];.
Otherwise, if you want to continue what you started, you can change your setDropDown() function to this :
function setDropDown() {
#Get the selected value of the ForceSelection select :
var index_name = $('#ForceSelection').val();
#Change the value of the other secondary select :
$(".secondary").each(function( index ) {
$(this).val(index_name).change();//This will change the value and trigger the change event.
});
}
I'm having trouble with validating my dropdown list with javascript. What I want is to display an error message underneath the field inside span tags if the user hasn't selected any options. I've checked almost every tutorials out there but no luck.
Here is the code for the form:
<form name="subform" id="subform" action="submit.php" onsubmit="return checkForBlank()" method="POST" enctype="multipart/form-data">
<div class="md-form">
<input type="text" id="subcim" name="subcim" class="form-control"><span class="error_form" id="subcim_error_message"></span>
<label for="subcim" class="">Title</label><br>
</div>
<div class="md-form">
<select class="mdb-select" id="subcat" name="subcat"><span class="error_form" id="subcat_error_message"></span>
<option value="0" selected>Please select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<label id="subcat_info">Category</label><br>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Submit</button>
</form>
and here is the Javascript code (the first if statement validates the input field in the form:
function checkForBlank() {
if(document.getElementById("subcim").value == "") {
document.getElementById("subcim_error_message").textContent="You must add a title!";
return false;
} else if(document.getElementById("subcim").value.length < 5 || document.getElementById("subcim").value.length > 80) {
document.getElementById("subcim_error_message").textContent="The title must be between 5 and 80 characters!";
return false;
}
var result = document.getElementById('subcat').value;
if (result === "0") {
document.getElementById("subcat_error_message").textContent="You must select an option!";
return false;
}
}
I'm using
onsubmit="return checkForBlank()"
inside the form tag.
When I submit the form without selecting an option, the form seems to be submitted properly, but it does not display the error message.
Any help is appreciated
function Validate() {
var subcat= document.getElementById("subcat");
if (subcat.value == "") {
//If the "Please Select" option is selected display error.
alert("Please select an option!");
return false;
}
return true;
}
onsubmit ="return Validate()"
function Validate() {
var subcat= document.getElementById("subcat");
if (subcat.value == "0") {
//If the "Please Select" option is selected display error.
alert("Please select an option!");
return false;
}
return true;
}
onsubmit ="return Validate();"
Change your syntex from
<div class="md-form">
<select class="mdb-select" id="subcat" name="subcat"><span class="error_form" id="subcat_error_message"></span>
<option value="0" selected>Please select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<label id="subcat_info">Category</label><br>
</div>
To syntex as below
<div class="md-form">
<select class="mdb-select" id="subcat" name="subcat">
<option value="0" selected>Please select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<span class="error_form" id="subcat_error_message"></span>
<label id="subcat_info">Category</label><br>
</div>
The only mistake that you are doing is putting your error span within your select tag it self which is not a predefined HTML format for select tag. As you can see that after putting your span tag out side your select tag every thing will work as you want.
Html
<div class="md-form">
<select class="mdb-select" id="subcat" name="subcat">
<option value="0" selected>Please select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<span class="error_form" id="subcat_error_message"></span>
<label id="subcat_info">Category</label><br>
</div>
JavaScript
function Validate() {
var subcat= document.getElementById("subcat");
if (subcat.value == "0") {
//If the "Please Select" option is selected display error.
document.getElementById("subcat_error_message").innerHTML="Error Message";
//OR
document.getElementById("subcat_error_message").textContent="Error Message";
return false;
}
return true;
}
onsubmit ="return Validate();"