Change input table to be "readonly" while select option matches the keyword. I just want to disable certain tabs while selecting a keyword.
script:
<script>
function block_SN(){
var selects = document.querySelectorAll("select[id=select_host]");
var serials = document.querySelectorAll("select[id=serial_number]");
for (var index = 0; index < selects.length -1; index++) {
if (selects[index].value.match(/keyword/))
serials[index].readOnly = true;
}
}
</script>
HTML:
<div class="form-group">
<input id="serial_number" name="serial_number" value="{{entry.serial_number}}" >
</div>
</td>
<td>
<div class="form-group">
<select id="select_host" name="select_host" class="selectpicker form-control" value="{{entry.hostname}}" onChange="this.form.submit();block_SN()">
{% for entry in hosts %}
<option value="{{entry.hostname}}">{{entry.hostname}}</option>
{% endfor %}
<option selected="selected">{{entry.hostname}}</option>
</select>
</div>
</td>
querySelectorAll should be perform either on tag or class.....but here in your code your performing on id(every html tag can have unique id)....
Add class to your input and select box serial_number and select_host respectively(you can also use name based querySelectorAll).
<script>
function block_SN(){
var selects = document.querySelectorAll(".select_host");**//changed**
var serials = document.querySelectorAll(".serial_number");**//changed**
for (var index = 0; index < selects.length -1; index++) {
if (selects[index].value.match(/keyword/))
serials[index].readOnly = true;
}
}
</script>
<div class="form-group">
<input id="serial_number" class="serial_number" name="serial_number" value="{{entry.serial_number}}" ><!-- added class serial_number-->
</div>
</td>
<td>
<div class="form-group">
<!-- added class select_host -->
<select class="select_host" id="select_host" name="select_host" class="selectpicker form-control" value="{{entry.hostname}}" onChange="this.form.submit();block_SN()">
{% for entry in hosts %}
<option value="{{entry.hostname}}">{{entry.hostname}}</option>
{% endfor %}
<option selected="selected">{{entry.hostname}}</option>
</select>
</div>
</td>
For this HTML Code is like:
<select id="sel_id">
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
</select>
<input type = "text" id = "text1" />
And JS Code is like this:
$(document).ready(function () {
$("#sel_id").change(function () {
var x = $(this).val();
alert("Selected Option other than Three. Input Box is still not Disabled");
alert($(this).val());
if (x == "three") {
alert("Selected Option Three. Input Box is now Disabled");
$(text1).attr("disabled", true);
}
});
});
Here, When the "Three" Option from select is selected then only Input TextBox is disabled.
Update 1: Use onchange="myFunction()" Event on select to get realtime change in Textbox.
Related
In my Django app (using {% load crispy_forms_tags %}) I have a following dropdown menu:
<div id="div_id_report_division" class="form-group">
<label for="id_report_division" class=" requiredField">Test<span class="asteriskField"></span</label>
<div class="">
<select name="report_division" class="select form-control" required="" id="id_report_division">
<option value="" selected="">---------</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
<option value="5">E</option>
</select> </div> </div>
I wish to remove option number 5 on page load. My Javascript on post.html with everything is:
<script type="text/javascript">
function on_load(){
/*
option 1.:
document.querySelector('id_report_division option[value=5]').remove();
option 2.:
var x = document.getElementById('id_report_division');
x.remove(5);
option 3.:
document.querySelector('#id_report_division option[value=5]').remove();
const first = document.querySelector("[id='id_report_division']");
*/
document.querySelector("[id='id_report_division' option[value=5]]").remove();
}
on_load();
</script>
How can I easly remove this option? It would be better if I could remove option where text is E, in case that value changes. But there will always be only one text 'E', no need to itterate.
You can iterate the select options list, check the inner text and remove like so:
var selectobject = document.getElementById("id_report_division");
for (var i=0; i<selectobject.length; i++) {
if (selectobject.options[i].text == 'E')
selectobject.remove(i);
}
i'm trying to show new select input contains (states) options, when user select specific option a (USA) country, and when select another country non (USA) don't show the states select options i want in this case still hidden.
Route
Route::get('/ajax-form', [AjaxController::class, 'index'])->name('ajax.index');
Route::get('/getState/{id}', [AjaxController::class, 'getState'])->name('ajax.state');
Controller
class AjaxController extends Controller
{
public function index()
{
$countries['data'] = Country::orderby('name')
->select('id', 'name')
->get();
return view('ajax.index', compact('countries'));
}
public function getState($countryId = 0)
{
$states['data'] = State::orderby('name')
->select('id', 'name')
->where('country_id', $countryId)
->get();
return response()->json($states);
}
Blade form with script:
#extends('layouts.app')
#section('form')
<form>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputCountry">Country</label>
<select class="country" id="inputCountry" class="form-control">
<option selected>Choose...</option>
#if ($countries['data'] && $countries['data']->count() > 0)
#foreach ($countries['data'] as $country)
<option value="{{ $country->id }}">{{ $country->name }}</option>
#endforeach
#endif
</select>
</div>
</div>
<div id="stateShow" class="form-row hidden">
<div class="form-group col-md-6">
<label for="inputState">State</label>
<select id="inputState" class="form-control">
<option value='0' selected>Choose...</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
#stop
#section('script')
<script type="text/javascript">
$(document).ready(function () {
$('#inputCountry').change(function() {
var id = $(this).val();
// Empty the States dropdown without first
$('#stateShow').show();
$('#inputState').find('option').not(':first').remove();
// ajax request
$.ajax({
url: 'getState/' + id,
type:'get',
dataType: 'json',
success: function(response) {
var len = 0;
if(response['data'] != null) {
len = response['data'].length;
}
if(len > 0) {
// Read data in the state option that related with country
for(var i = 0; i < len; i++) {
var id = response['data'][i].id;
var name = response['data'][i].name;
var option = "<option value='" + id + "'>" + name + "</option>";
$('#inputState').append(option);
}
}
}
});
});
});
</script>
#stop
the above script doing, when i select any country, the hidden (states) select is shown, i want it shows only when i select (USA) and non that still hidden
could you help me
In your inputCountry select-box i am assuming {{ $country->name }} is country name so you can use $(this).find("option:selected").text() to get this value and then compare it with USA if they are equal show your div else hide it.
Demo Code :
$('#inputCountry').change(function() {
var id = $(this).val();
var text = $(this).find("option:selected").text().trim() //get text
if (text == "USA") {
$('#stateShow').show(); //show
$('#inputState').find('option').not(':first').remove();
//your ajax call put here ....
} else {
$('#stateShow').hide(); //hide
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputCountry">Country</label>
<select class="country" id="inputCountry" class="form-control">
<option selected>Choose...</option>
<option value="{{ $country->id }}">Abc</option>
<option value="{{ $country->id }}">USA</option>
</select>
</div>
</div>
<div id="stateShow" class="form-row hidden">
<div class="form-group col-md-6">
<label for="inputState">State</label>
<select id="inputState" class="form-control">
<option value='0' selected>Choose...</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
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>
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'm pretty new to JS, and I want to add many options to multiple select. But the problem is that when I'm trying to show them only the last record is triggering the function (showing). But when I'm doing console.log it is showing every thing perfectly.
This is my HTML:
<form class="cart" method="post" action="{{ route('cart.add') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="product_size" class="grey">Model</label>
<span class="red">*</span>
<select class="form-control" id="productModel" name="product" onchange=" addRelatedproducts();">
<option value="">Wybierz model produktu...</option>
#foreach($productModels as $productModel)
<option value="{{$productModel->id}}">{{$productModel->modelName}} - {{$productModel->modelPrice}} #if($productModel->modelPriceCurrency === 1) PLN #else EUR #endif</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleSelect1">Ilość:</label>
<select class="form-control" id="exampleSelect1" name="quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div>
<div class="form-group" id="relatedProductsDiv" style="display: none;">
<label for="exampleSelect1">Produkty powiązane:</label>
<select id="select" multiple="multiple" class="relatedProducts" name="relatedProduct">
</select>
</div>
</div>
This is my JS:
function addRelatedproducts(){
var model = [
<?php foreach($productModels as $productModel):?>
<?=$productModel?>,
<?endforeach;?>
];
var relatedProducts = [
<?php foreach($relatedProductArray as $relatedProduct): ?>
<?=$relatedProduct ?>,
<?endforeach; ?>
];
var e = document.getElementById("productModel");
var selectedModelId = e.options[e.selectedIndex].value;
var select = document.getElementById("select");
for (var i = 0; i < relatedProducts.length + 1; i++) {
select.remove(relatedProducts[i].relatedProductName);
if(parseInt(relatedProducts[i].model_id) === parseInt(selectedModelId)){
console.log(relatedProducts[i])
console.log(selectedModelId)
document.getElementById("relatedProductsDiv").style.display = "";
var option = document.createElement("option");
option.value = relatedProducts[i].id;
option.text = relatedProducts[i].relatedProductName;
select.add(option);
}
else{
document.getElementById("relatedProductsDiv").style.display = "none";
}
}
}
I don't really know why it isn't working. Can anybody help me with this problem?
select.remove(relatedProducts[i].relatedProductName);
select.remove expects an option index as an argument. And I suppose when it receives a product name string (probably not a number) apparently it evaluates it as NaN and just removes the very first option in the select on every step. So it comes up with an empty select in the end.
Maybe the better approach would be to clear all the select options right before iterating relatedProducts and then to populate only with the needed ones?
while(select.options.length) {
select.remove(0);
}
for (var i = 0; i < relatedProducts.length + 1; i++) {
if(parseInt(relatedProducts[i].model_id) === parseInt(selectedModelId)){
console.log(relatedProducts[i])
// ....