jQuery: if statement to select an option value - javascript

My aim is:
If I type a value bigger than 60, then I would like the option "Long"
to be selected.
If I type a value less than 60, then I would like the option "Short" to be selected.
With help of of jQuery, I would like for "result" to be automatically changed given the field "value"
I have a form, contains an input integer field, with id "value", and form has a option field with id "result".
Below is my try, but it does not work.
Thanks for your input.
var value = $('#value');
$(value).change(function() {
debugger;
if (Number($(this).val()) > 60) {
$('#result').prop('value') = "Long";
}
if (Number($(this).val()) < 60) {
$('#result').prop('value') = "Short";
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="value" class="col-form-label col-sm-4">Value</label>
<div class="col-sm-7"> <input type="number" name="value" class="numberinput form-control" id="value"> </div>
</div>
<div><i>Result:</i></div>
<div id="result" class="form-group row">
<div class="col-sm-12">
<select name="result" class="select2 form-control" style="width: 100%;" id="result">
<option value="Long">Long</option>
<option value="Short">Short</option>

You can set the selected value using .val(....).
var value = $('#value');
$(value).change(function() {
debugger;
if (Number($(this).val()) > 60) {
$('select').val("Long");
}
if (Number($(this).val()) < 60) {
$('select').val("Short");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="value" class="col-form-label col-sm-4">Value</label>
<div class="col-sm-7"> <input type="number" name="value" class="numberinput form-control" id="value"> </div>
</div>
<div><i>Result:</i></div>
<div id="result" class="form-group row">
<div class="col-sm-12">
<select name="result" class="select2 form-control" style="width: 100%;" id="result">
<option value="Long">Long</option>
<option value="Short">Short</option>
Beside that, you have some problems in the HTML, you've used the same ID (result) multiple times. IDs are meant to be unique.
As #Archer mentioned, none of the two current conditions will match if the value is 60, you will need to do a >= or <= comparison to account for those cases.

Three things I see here:
You're setting the value incorrectly. Instead of .prop('value') = 'Long', which isn't valid JavaScript, just use .val('Long').
You're re-using the "result" ID, so you're targeting the wrong element. IDs must be unique.
The HTML is incomplete. Might not be a cause of the problem, but certainly worth fixing.
So something more like this:
var value = $('#value');
$(value).change(function() {
debugger;
if (Number($(this).val()) > 60) {
$('#result').val('Long'); // 1. Setting the value correctly with jQuery
}
if (Number($(this).val()) < 60) {
$('#result').val('Short');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="value" class="col-form-label col-sm-4">Value</label>
<div class="col-sm-7"> <input type="number" name="value" class="numberinput form-control" id="value"> </div>
</div>
<div><i>Result:</i></div>
<div class="form-group row"> <!--- 2. Removing the errant ID --->
<div class="col-sm-12">
<select name="result" class="select2 form-control" style="width: 100%;" id="result">
<option value="Long">Long</option>
<option value="Short">Short</option>
</select> <!--- 3. Correcting the remaining HTML --->
</div>
</div>

// No need to wrap '#value' twice with jQuery function
$('#value').change(function() {
// You do not need two ifs, since the two value are exclusive
const option = $(this).val() > 60 ? "Long" : "Short";
// You had two different elements with the id "result"
// and .val is a function, you can pass the new value as argument
$('#selection').val(option);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="value" class="col-form-label col-sm-4">Value</label>
<div class="col-sm-7"> <input type="number" name="value" class="numberinput form-control" id="value" /> </div>
</div>
<div><i>Result:</i></div>
<div id="result" class="form-group row">
<div class="col-sm-12">
<select name="result" class="select2 form-control" style="width: 100%;" id="selection">
<option value="Short">Short</option>
<option value="Long">Long</option>
</select>
</div>
</div>

i think,it will help you
<script src="Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#value").on('input', function () {
var value = parseInt($("#value").val());
if (value > 60) {
$("#result").prop("value", "Long");
}
if (value <= 60) {
$("#result").prop("value", "Short");
}
});
});
</script>
<input type="number" name="value" class="numberinput form-control" id="value" />
<select name="result" class="select2 form-control" style="width: 100%;" id="result">
<option value="Short">Short</option> <option value="Long">Long</option>
</select>

Related

Form Submit clears values before passing data to server-side

There are couple of Javascript functions that validate the values for the two fields in question.
The functions are doing the job intended but when I submit the form, the two values validated by said functions are blank
here is the js code
<script>
function updateRequirements() {
var contract = document.getElementById("contract").value;
var expdate = document.getElementById("expdate");
console.log(contract);
if (contract == "YES") {
expdate.style.display = "block";
} else {
expdate.style.display = "none";
}
}
function dateRequirements() {
var contract = document.getElementById("contract").value;
var expdate = document.getElementById("expdate")
var expdateValue = expdate.value;
console.log(expdateValue);
if (contract == "YES") {
var today = new Date();
var exp = new Date(expdateValue);
var difference = exp - today;
if (difference > 365 * 24 * 60 * 60 * 1000) {
alert("The expiration date cannot be more than 365 days from today");
expdate.value = ""; // Clear the date field
}
}
}
</script>
Here is short version of the form:
[![<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-row">
<div class="form-group col-md-6">
<label asp-for="EntryADFormModel.FirstName" class="control-label"></label>
<input asp-for="EntryADFormModel.FirstName" class="form-control" />
<span asp-validation-for="EntryADFormModel.FirstName" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label asp-for="EntryADFormModel.LastName" class="control-label"></label>
<input asp-for="EntryADFormModel.LastName" class="form-control" />
<span asp-validation-for="EntryADFormModel.LastName" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label asp-for="EntryADFormModel.Contractor" class="control-label"></label>
<select name="contract" class="form-control" asp-for="EntryADFormModel.Contractor" id="contract" onchange="updateRequirements();">
<option value="SELECT" selected disabled>Select Answer</option>
<option value="YES">Yes</option>
<option value="NO">No</option>
</select>
<span asp-validation-for="EntryADFormModel.Contractor" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label asp-for="EntryADFormModel.AccountExpDate" class="control-label"></label>
<input asp-for="EntryADFormModel.AccountExpDate" class="form-control" id="expdate" name="expdate" onchange="dateRequirements()" />
<span asp-validation-for="EntryADFormModel.AccountExpDate" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>]
Here is the form with missing values after being submitted
Tag helper asp-for will dynamically generate the id and name attribute, but if you specify the name attribute in the html, the tag helper default generated name value will be overrided.
And your backend binds the model by name attribute, it needs name like: EntryADFormModel.PropertyName.
For your scenario, just remove the name attribute like below:
<select class="form-control" asp-for="EntryADFormModel.Contractor" id="contract" onchange="updateRequirements();">
<option value="SELECT" selected disabled>Select Answer</option>
<option value="YES">Yes</option>
<option value="NO">No</option>
</select>
<input asp-for="EntryADFormModel.AccountExpDate" class="form-control" id="expdate" onchange="dateRequirements()" />

Changing content of an single input field after cloning form fields

I am having an interface for my admins where they can add fields to a database. If they want to add several fields they can easily add a new line. This is done by cloning via JavaScript. Now there is one dropdown menu and based on the selection from the dropdown I want to write default values to the text-input fields for min[] and max[].
This works fine if I am having just one line. But if I clone it several times and make a selection (e. g. I am selecting the option "relative_number") in just one line (e. g.) the min and max fields are updated in every line. What can I do so that when the drop down is selected in a certain line only the min and max values in the same line are updated?
Here is my code:
<div class="wrapper">
<div class="entities_wrap">
<div class="row">
<div class="col-md-3">
<label>Name</label>
<input type="text" name="entity_name[]" value="" style="width: 275px;" class="form-control" id="entity_name[]" />
</div>
<div class="col-md-3">
<label>Field Name</label>
<input type="text" name="entity_field_name[]" value="" style="width: 275px;" class="form-control" id="entity_field_name[]" />
</div>
<div class="col-md-2">
<label>Category</label>
<select id="entity_field_type[]" name="entity_field_type[]" class="form-select"> <option value=""></option> <option value="absolute_number">absolute_number</option> <option value="relative_number">relative_number</option> <option value="likert_5">likert_5</option> <option value="likert_7">likert_7</option> <option value="string">string</option> </select>
</div>
<div class="col-md-1 minValue">
<label>Min</label>
<input type="text" class="form-control min" id="min[]" name="min[]" value=""/>
</div>
<div class="col-md-1">
<label>Max</label>
<input type="text" class="form-control max" id="max[]" name="max[]" value=""/>
</div>
<div class="col-md-1" style="vertical-align: middle;">
<label> </label>
<div style="margin: 0px 10px;">
<i class="fas fa-trash remove-item"></i></span>
</div>
</div>
<div class="col-md-1" style="vertical-align: middle;">
<label> </label>
<div style="margin: 0px 10px;">
<i class="fas fa-plus add-plus"></i> <span class="plus">Add Line</span>
</div>
</div>
</div><br>
</div>
</div>
<script>
$(document).ready(function () {
$(".add-plus").click(function(){
$(".entities_wrap:last").clone(true).appendTo(".wrapper");
});
$(".plus").click(function(){
$(".entities_wrap:last").clone(true).appendTo(".wrapper");
});
$(".remove-item").click(function () {
$(this).closest(".entities_wrap").remove();
});
});
$('select[id^="entity_field_type"]').on('change', function()
{
var sel_cat = this.value;
if(sel_cat == 'relative_number')
{
$('input[id^="min"]').val("0");
$('input[id^="max"]').val("100");
}
if(sel_cat == 'absolute_number')
{
$('input[id^="min"]').val("0");
$('input[id^="max"]').val("infinite");
}
// For the other options the code should work alike
});
</script>
Tried already different ways to solve it via DOM, identifying parent nodes, siblings and so on but I don't get it working.
Thanks a lot in advance for your help!
While you should definitely look at dynamically modifying the names and id's of your cloned inputs, the issue you are having relates to your selectors for min and max
In the case of your javascript
$('input[id^="min"]').val("0");
$('input[id^="max"]').val("100");
You are selecting all min and max on the page.
You need to find the related min and max, which means finding the closet .row to the select-box and then finding the child min/max
var $row = $(this).closest("div.row");
$row.find('input[id^="min"]').val("0");
$row.find('input[id^="max"]').val("100");
jQuery closest()
jQuery find()
Here is a functioning snippet example.
$(document).ready(function() {
$(".add-plus").click(function() {
$(".entities_wrap:last").clone(true).appendTo(".wrapper");
});
$(".plus").click(function() {
$(".entities_wrap:last").clone(true).appendTo(".wrapper");
});
$(".remove-item").click(function() {
$(this).closest(".entities_wrap").remove();
});
});
$('select[id^="entity_field_type"]').on('change', function() {
var sel_cat = this.value;
var $row = $(this).closest("div.row"); //find the parent row we are in.
if (sel_cat == 'relative_number') {
$row.find('input[id^="min"]').val("0"); //use that row to find the related min
$row.find('input[id^="max"]').val("100"); //use that row to find the related max
}
if (sel_cat == 'absolute_number') {
$row.find('input[id^="min"]').val("0");
$row.find('input[id^="max"]').val("infinite");
}
// For the other options the code should work alike
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.0/css/all.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="entities_wrap">
<div class="row">
<div class="col-md-3">
<label>Name</label>
<input type="text" name="entity_name[]" value="" style="width: 275px;" class="form-control" id="entity_name[]" />
</div>
<div class="col-md-3">
<label>Field Name</label>
<input type="text" name="entity_field_name[]" value="" style="width: 275px;" class="form-control" id="entity_field_name[]" />
</div>
<div class="col-md-2">
<label>Category</label>
<select id="entity_field_type[]" name="entity_field_type[]" class="form-select">
<option value=""></option>
<option value="absolute_number">absolute_number</option>
<option value="relative_number">relative_number</option>
<option value="likert_5">likert_5</option>
<option value="likert_7">likert_7</option>
<option value="string">string</option>
</select>
</div>
<div class="col-md-1 minValue">
<label>Min</label>
<input type="text" class="form-control min" id="min[]" name="min[]" value="" />
</div>
<div class="col-md-1">
<label>Max</label>
<input type="text" class="form-control max" id="max[]" name="max[]" value="" />
</div>
<div class="col-md-1" style="vertical-align: middle;">
<label> </label>
<div style="margin: 0px 10px;">
<i class="fas fa-trash remove-item"></i></span>
</div>
</div>
<div class="col-md-1" style="vertical-align: middle;">
<label> </label>
<div style="margin: 0px 10px;">
<i class="fas fa-plus add-plus"></i> <span class="plus">Add Line</span>
</div>
</div>
</div><br>
</div>
</div>

How to call JavaScript methods automatically anywhere in HTML?

My price input should be disabled or enabled automatically after selecting status. Now it turns in disabled after click on input (during wrong status) but it doesn't back to enabled when my status is good.
What is the right way to do it ?
HTML:
<div class="form-row">
<div class="form-group col-md-6 text-center">
<label for="cattery-status-create" th:text="#{cattery.status}"></label>
<select id="cattery-status-create" class="form-control">
<option th:each="status : ${catteryStatusCodeDict}" th:value="${status.code}" th:text="${status.value}"></option>
</select>
</div>
<div class="form-group col-md-6 text-center">
<label for="price-create" th:text="#{price}"></label>
<input id="price-create" onclick="setPriceInputDisabled()" type="number" class="form-control" max="10000" step="1">
</div>
</div>
JavaScript:
function setPriceInputDisabled(){
document.getElementById("price-create").disabled = false;
var catteryStatusCode = $("#cattery-status-create").find(":selected").val();
if (catteryStatusCode != 'S') {
document.getElementById("price-create").disabled = true;
}
}
Unsure why you are mixing JavaScript an jQuery. I would use one or the other, not both.
function setPriceInputDisabled(){
$("#price-create").prop("disabled", ($("#cattery-status-create").val() === "S"));
}
This will only enable the Input upon click event when Value is not "S".
The click event does not seem like the right callback to bind to. I suspect you want to modify the property when the Select element is changed. If the User selects a Value of "S"; the Input is disabled.
$(function() {
function setPriceInputDisabled() {
$("#price-create").prop("disabled", ($("#cattery-status-create").val() === "S"));
}
$("#cattery-status-create").change(setPriceInputDisabled);
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<div class="form-group col-md-6 text-center">
<label for="cattery-status-create" th:text="#{cattery.status}"></label>
<select id="cattery-status-create" class="form-control">
<option>A</option>
<option>S</option>
<option>D</option>
<option>F</option>
<option>G</option>
</select>
</div>
<div class="form-group col-md-6 text-center">
<label for="price-create" th:text="#{price}"></label>
<input id="price-create" type="number" class="form-control" max="10000" step="1">
</div>
</div>

What gets submitted to the database is just the entry of "other" and not what i typed in manually?

When i select the option value of "other" in my dropdown lis the form row below appears and allows me to type a manual cemetery but what gets submitted to the database is just the entry of "other" and not what i typed in manually?
<script>
function handleSelect() {
var selected = document.getElementById("mySelect").value;
var details = document.getElementById("other-details");
if (selected === "other") {
details.classList.remove("d-none");
details.classList.add("d-block");
} else {
details.classList.remove("d-block");
details.classList.add("d-none");
}
}
</script>
<div class="form-row">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<label class="control-label custom_label col-xs-12">Cemetery</label>
<select name="cemetery" class="form-control" id="mySelect" onchange="handleSelect();">
<option value="select" selected="selected">Select Cemetery</option>
<option value="Akatarawa">Akatarawa</option>
<option value="Taita">Taita</option>
<option value="Wainuiomata">Wainuiomata</option>
<option value="Whenua Tapu">Whenua Tapu</option>
<option value="Makara">Makara</option>
<option value="Karori">Karori</option>
<option value="St Johns">St Johns</option>
<option value="Awa Tapu">Awa Tapu</option>
<option value="Paraparaumu">Paraparaumu</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="form-row d-none" id="other-details">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<input type="text" id="other" class="form-control" name="" placeholder="Enter other Cemetery" />
</div>
</div>
</body>
Try setting name of the input to cemetery.
<input type="text" id="other" class="form-control" name="cemetery" placeholder="Enter other Cemetery" />
This may work, but not a good practise.
I suggest you to do something like following
HTML
<input type="text" id="other" class="form-control" name="other-cemetery" placeholder="Enter other Cemetery" />
PHP
if($_POST["cemetery"] == "other"){
$cemetery = $_POST["other-cemetery"];
}
Update: The first solution that I gave may not work in other cases. So add the following line to handleSelect() function. (Not selected case)
document.getElementById("other").value = document.getElementById("mySelect").value;
Thanks Dum, combining that link of JS and setting the Value of the "other" drop down to empty.
Example: <option value="">Other</option>
This has resolved my issue. Many thanks

Javascript disable/enable input field based on selection other field

I tried to follow answer here to do this in my code: How do I disable input field when certain select list value is picked but not working for me.
I have an HTML select field id 'TfL' with Yes/No answer, and next field 'TfLroad' is an input field. I want 'TfLroad' to load as disabled by default, then if 'TfL' changes from No to Yes, then 'TfLroad' should be enabled.
Whole page code below, JS at top of file, these two fields next to bottom, tx any suggestions!:
{% extends "base.jinja2" %}
{% block content %}
<script>
// value 0 for No answer to TfL road 1 for, in which case disabled, on change should
// enable TfLroad element by setting disabled = false, but not working yet!
document.getElementById("TfLroad").onload = function () {
document.getElementById("TfLroad").disabled = true;
}
document.getElementById('TfL').onchange = function () {
if(this.value = '0') {
document.getElementById("TfLroad").disabled = true;
}
else {
document.getElementById("TfLroad").disabled = false;
}
}
</script>
<h2 style="text-align:center">Add A 'Dummy' Street</h2>
<p>You can create a Dummy street here, which you will be able to search for in this application. This is to
demonstrate how a real Create & Update Process could work for this application, without corrupting the original
data. Dummy streets are indicated in search results.</p>
<form class="form-horizontal" action = "" method="post">
<fieldset>
<div class="form-group">
<div class="col-lg-6">
<label for="stname" class="control-label">Street Name</label>
<input class="form-control" id="stname" name="stname" pattern="^\S.{3,98}\S$"
title="Sorry, you must type from 5 to 100 characters, and no space at beginning or end."
placeholder="Full Street Name" required>
<!-- required attribute needed because empty string bypasses the pattern regex. -->
<span class="help-block">NB: No naughty word streets please, these will be deleted by admin!</span>
</div>
<!-- CR, CL, PR, 25, 16, 19, BE, KN, SC, TH, WA, WH -->
<div class="col-lg-3">
<label for="distr" class="control-label">Postal District</label>
<select class="form-control" id="distr" name="distr">
<option>Croydon (CR0, CR2, CR7 or CR9)</option>
<option>Coulsdon CR5</option>
<option>Purley CR8</option>
<option>London SE25</option>
<option>London SW16</option>
<option>Kenley CR8</option>
<option>South Croydon CR2</option>
<option>Thornton Heath CR7</option>
<option>Warlingham CR6</option>
<option>Whyteleafe CR3</option>
<option>Beckenham BR3</option>
</select>
<span class="help-block">NB: Original data uses postal district only, hence problem with several postcodes for Croydon.</span>
</div>
<div class="col-lg-3">
<label for="maint" class="control-label">Who looks after this street?</label>
<select class="form-control" id="maint" name="maint">
<option>Croydon Borough</option>
<option>Transport for London</option>
<option>Private Road</option>
</select>
</div>
</div>
<div class="form-group">
<h4 class="centre">Street Number Limits for this Street Section<br/><small>Please leave as None if all properties in this section have names</small></h4>
</div>
<div class="form-group">
<div class="col-lg-3">
<label for="onb" class="control-label">Odd Numbers From</label>
<input class="form-control" id="onb" name="onb" value="None" pattern="^\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None">
<span class="help-block">e.g. '1' or '111'</span>
</div>
<div class="col-lg-3">
<label for="one" class="control-label">Odd Numbers To</label>
<input class="form-control" id="one" name="one" value="None" pattern="^\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None">
<span class="help-block">e.g. '31' or '217'</span>
</div>
<div class="col-lg-3">
<label for="enb" class="control-label">Even Numbers From</label>
<input class="form-control" id="enb" name="enb" value="None" pattern="^\d*[02468]$|(None)" title="Even Numbers only please with no spaces, or None">
<span class="help-block">e.g. '2' or '110'</span>
</div>
<div class="col-lg-3">
<label for="ene" class="control-label">Even Numbers To</label>
<input class="form-control" id="ene" name="ene" value="None" pattern="^\d*[02468]$|^(None)$" title="Even Numbers only please with no spaces, or None">
<span class="help-block">e.g. '32' or '216'</span>
</div>
</div>
<div class="form-group">
<div class="col-lg-4">
<label for="rdclass" class="control-label">Road Class</label>
<select class="form-control" id="rdclass" name="rdclass">
<option>Unclassified</option>
<option>A Road</option>
<option>B Road</option>
<option>C Road</option>
</select>
<span class="help-block">Leave as Unclassified if in any doubt.</span>
</div>
<div class="col-lg-4">
<label for="length" class="control-label">Length of this Street Section (whole no. metres)</label>
<input class="form-control" id="length" name="length" value= 0 pattern="^[1-9][0-9]*$" title="Whole number of metres please, no spaces!" required>
</div>
<div class="col-lg-4">
<!-- JS here to put in A B C / disable depending on what selected in rdclass box -->
<label for="rdnum" class="control-label">Road Number</label>
<input class="form-control" id="rdnum" name="rdnum" pattern="^[ABC][1-9][0-9]*$|^(None)$" title="Must be None, or A, B or C followed by a whole number for the road class, no spaces!" value="None" required>
<span class="help-block">Only for A/B/C roads e.g. 'A232', 'C3241'</span>
</div>
</div>
<div class="form-group">
<div class="col-lg-3">
<label class="control-label left">Does one end of this street adjoin a TfL maintained street?</label>
<select class="form-control" id="TfL">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div class="col-lg-4">
<!-- JS not working yet to disable only if no selected in rdclass box -->
<label class="control-label"><br/> Road Number of Adjoining TfL Road?</label>
<input class="form-control" pattern="^[ABC][1-9][0-9]*$|^(None)$"
title="Must be None, or A, B or C followed by a whole number, no spaces!" value="None" id="TfLroad" required>
<span class="help-block">E.g. 'A232', 'B2441'</span>
</div>
</div>
<div class="form-group">
<div class="centre">
<button type="reset" class="btn btn-default">Reset Form</button>
<button type="submit" class="btn btn-primary">Create Street</button>
</div>
</div>
</fieldset>
</form>
{% endblock %}
Instead of setting disabled through javascript you could add the disabled to the HTML input element:
<input class="form-control" disabled="disabled" .... />
Then in your javascript:
document.getElementById('TfL').onchange = function ()
{
if (this.value == '0')
{
document.getElementById("TfLroad").disabled = true;
}
else
{
document.getElementById("TfLroad").disabled = false;
}
}
There are several problems in the HTML/script you provided.
The <script> content is executing before the form fields exist (onload code isn't implemented the way you've done it.)
You haven't picked a default value for TfL
You haven't disabled TfLroad by default
You've got a typo in a comparison.
Fixing in order:
move the <script> to the bottom of the page and remove the onload function.
assuming you want No selected by default:
<select class="form-control" id="TfL">
<option value="0" selected>No</option>
<option value="1">Yes</option>
</select>
Add disabled attribute
<input class="form-control" pattern="^[ABC][1-9][0-9]*$|^(None)$" disabled
title="Must be None, or A, B or C followed by a whole number, no spaces!" value="None" id="TfLroad" required>
usie = instead of == (or ===):
if(this.value = '0') {
Should be
if(this.value === '0') {
(You could also rewrite the onchange handler):
document.getElementById('TfL').onchange = function () {
document.getElementById("TfLroad").disabled = (this.value === '0');
}
disabled is a Boolean attribute. You don't disable an element by setting its attribute to disabled=false. The browser checks if your element HAS a disabled property and doesn't care if its disabled=true, disabled=false, disabled=elephant. In order to "enable" your element you must completely remove the disabled attribute.
This should work:
document.getElementById('TfL').onchange = function () {
if(this.value == '0') {
document.getElementById("TfLroad").disabled = "elephant";
}
else {
document.getElementById("TfLroad").removeAttr("disabled");
}
}
Also when comparing two values use == and not =.
So the problem is load event does not work on all elements, it only supports the below HTML tags.
<body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">,
<link>, <script> and <style>
Refer here to know more.
Also I have changed the logic for applying the initial disabled condition, please check it!
As an alternative you can watch for document.ready instead and then apply this change. Refer the below snippet.
var select = document.getElementById('TfL'), input = document.getElementById("TfLroad");
document.addEventListener("DOMContentLoaded", function(event) {
if (select.value === '0') {
input.disabled = true;
} else {
input.disabled = false;
}
});
select.onchange = function() {
if (this.value === '0') {
input.disabled = true;
} else {
input.disabled = false;
}
}
<h2 style="text-align:center">Add A 'Dummy' Street</h2>
<p>You can create a Dummy street here, which you will be able to search for in this application. This is to demonstrate how a real Create & Update Process could work for this application, without corrupting the original data. Dummy streets are indicated
in search results.</p>
<form class="form-horizontal" action="" method="post">
<fieldset>
<div class="form-group">
<div class="col-lg-6">
<label for="stname" class="control-label">Street Name</label>
<input class="form-control" id="stname" name="stname" pattern="^\S.{3,98}\S$" title="Sorry, you must type from 5 to 100 characters, and no space at beginning or end." placeholder="Full Street Name" required>
<!-- required attribute needed because empty string bypasses the pattern regex. -->
<span class="help-block">NB: No naughty word streets please, these will be deleted by admin!</span>
</div>
<!-- CR, CL, PR, 25, 16, 19, BE, KN, SC, TH, WA, WH -->
<div class="col-lg-3">
<label for="distr" class="control-label">Postal District</label>
<select class="form-control" id="distr" name="distr">
<option>Croydon (CR0, CR2, CR7 or CR9)</option>
<option>Coulsdon CR5</option>
<option>Purley CR8</option>
<option>London SE25</option>
<option>London SW16</option>
<option>Kenley CR8</option>
<option>South Croydon CR2</option>
<option>Thornton Heath CR7</option>
<option>Warlingham CR6</option>
<option>Whyteleafe CR3</option>
<option>Beckenham BR3</option>
</select>
<span class="help-block">NB: Original data uses postal district only, hence problem with several postcodes for Croydon.</span>
</div>
<div class="col-lg-3">
<label for="maint" class="control-label">Who looks after this street?</label>
<select class="form-control" id="maint" name="maint">
<option>Croydon Borough</option>
<option>Transport for London</option>
<option>Private Road</option>
</select>
</div>
</div>
<div class="form-group">
<h4 class="centre">Street Number Limits for this Street Section<br/><small>Please leave as None if all properties in this section have names</small></h4>
</div>
<div class="form-group">
<div class="col-lg-3">
<label for="onb" class="control-label">Odd Numbers From</label>
<input class="form-control" id="onb" name="onb" value="None" pattern="^\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None">
<span class="help-block">e.g. '1' or '111'</span>
</div>
<div class="col-lg-3">
<label for="one" class="control-label">Odd Numbers To</label>
<input class="form-control" id="one" name="one" value="None" pattern="^\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None">
<span class="help-block">e.g. '31' or '217'</span>
</div>
<div class="col-lg-3">
<label for="enb" class="control-label">Even Numbers From</label>
<input class="form-control" id="enb" name="enb" value="None" pattern="^\d*[02468]$|(None)" title="Even Numbers only please with no spaces, or None">
<span class="help-block">e.g. '2' or '110'</span>
</div>
<div class="col-lg-3">
<label for="ene" class="control-label">Even Numbers To</label>
<input class="form-control" id="ene" name="ene" value="None" pattern="^\d*[02468]$|^(None)$" title="Even Numbers only please with no spaces, or None">
<span class="help-block">e.g. '32' or '216'</span>
</div>
</div>
<div class="form-group">
<div class="col-lg-4">
<label for="rdclass" class="control-label">Road Class</label>
<select class="form-control" id="rdclass" name="rdclass">
<option>Unclassified</option>
<option>A Road</option>
<option>B Road</option>
<option>C Road</option>
</select>
<span class="help-block">Leave as Unclassified if in any doubt.</span>
</div>
<div class="col-lg-4">
<label for="length" class="control-label">Length of this Street Section (whole no. metres)</label>
<input class="form-control" id="length" name="length" value=0 pattern="^[1-9][0-9]*$" title="Whole number of metres please, no spaces!" required>
</div>
<div class="col-lg-4">
<!-- JS here to put in A B C / disable depending on what selected in rdclass box -->
<label for="rdnum" class="control-label">Road Number</label>
<input class="form-control" id="rdnum" name="rdnum" pattern="^[ABC][1-9][0-9]*$|^(None)$" title="Must be None, or A, B or C followed by a whole number for the road class, no spaces!" value="None" required>
<span class="help-block">Only for A/B/C roads e.g. 'A232', 'C3241'</span>
</div>
</div>
<div class="form-group">
<div class="col-lg-3">
<label class="control-label left">Does one end of this street adjoin a TfL maintained street?</label>
<select class="form-control" id="TfL">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div class="col-lg-4">
<!-- JS not working yet to disable only if no selected in rdclass box -->
<label class="control-label"><br/> Road Number of Adjoining TfL Road?</label>
<input class="form-control" pattern="^[ABC][1-9][0-9]*$|^(None)$" title="Must be None, or A, B or C followed by a whole number, no spaces!" value="None" id="TfLroad" required>
<span class="help-block">E.g. 'A232', 'B2441'</span>
</div>
</div>
<div class="form-group">
<div class="centre">
<button type="reset" class="btn btn-default">Reset Form</button>
<button type="submit" class="btn btn-primary">Create Street</button>
</div>
</div>
</fieldset>
</form>

Categories

Resources