set id on select option to disabled javascript - javascript

I want to disabled option on select without click any button. How can I do that?
I tried this. use id on option in JS
html code:
<select name="select01" id="select01" onchange="handleSelect()">
<option value="01" id="01">01</option>
<option value="02" id="02">02</option>
<option value="03" id="03">03</option>
</select>
JS code:
<script>
function handleSelect() {
if (this.value == '02') {
document.getElementById('02').disabled=true;
}
}
</script>
From what I know from the code JS, option with id 02 will be disabled but it it does not work. I have tried search inside stack over flow but do not find one.

In your eventhandler you need to pass in the element onchange="handleSelect(this)". Then use it:
function handleSelect(ele) {
if (ele.value == '02') {
document.getElementById('02').disabled=true;
}
}
Also note that id isn't supposed to be strictly numerical, while it's supported in HTML 5 it isn't below HTML 4.01 where it needs to start with a letter.
Also if you attach the event handler purely in JavaScript you can just do:
document.getElementById("select01").onchange = function() {
if (this.value == '02') {
document.getElementById('02').disabled=true;
}
}

Related

Is it possible hide a specific field after user selection of another field?

I need to create an IF that allow me to define a specific rule.
I have a customer portal page where customers can open tickets.
The form is developed in order to insert some information like: “software product” and “environment” both are defined as dropdown list. In addition we have other fields like “Suite version”.
The IF I need is:
If (software product = ‘TEST’) then HIDE the field “Suite Version”
It is needed because the value “TEST” will open a new level of the “Software Product” field.
I can use Jquery JavaScript.
Many thanks.
is this what you want ?? check below code
$( document ).ready(function() {
$('#SoftProd').change(function(){
$('#pp').html($(this).val());
if($(this).val() == "Test")
{
$('#SuiteVersion').hide();
}
else
{
$('#SuiteVersion').show();
}
});
});
<Select id="SoftProd"> Software Product
<option selected value="">Select option...</option>
<option value="Test">Test</option>
<option value="other">other</option>
</Select>
<input type="text" Placeholder="Suite Version" id="SuiteVersion" name="SuiteVersion">
<!--Jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
you can try js
css
#Suite_Version {
display: none;
}
JS
var software_product = $('#software_product').val();
if (software_product === "test") {
$("#Suite_Version").hide();
} else {
$("#Suite_Version").show();
}
I tried to use this code but unfortunately doesn’t work.
Consider that I am new in this programming language.
jQuery(document).ready(function()
var software_product = $('#helpdesk_ticket_custom_field_cf_product_1815896').val();
{
if (software_product === "AMHS"){
Jquery("#helpdesk_ticket_custom_field_cf_suite_version_1815896").parent().parent().hide();
}
else {
Jquery("#helpdesk_ticket_custom_field_cf_suite_version_1815896").parent().parent().show();
}
});

How do you populate an option value using jQuery?

I am trying to populate a form option value if it's attribute quantity equals zero.
My goal is to add the a message to the current option value
My html is:
<select class="valid">
<option disabled="disabled" selected="selected" value="">Select Bar</option>
<option value="1" quantity="99">value 1 </option>
<option value="2" quantity="0">value 2 </option>
</select>
So far I've tried the following in jQuery but it's not working:
if($(this).attr('quantity') == '0') {
$(this).append('<span>message</span>');
}
If you don't care about preserving the original message, than you can simply say $(this).text("message"). Leave out the <span> since it cannot be rendered inside of an <option> element anyway.
if($(this).attr('quantity') == '0') {
$(this).text('message');
}
If you want to preserve the original message, you have a couple options. One would simply be to append the new message to the original, however, it may get tricky to remove it later, so I would suggest having some sort of delimiter so you can easily identify the original vs the appended message, like so:
var $option = $(this);
if($option.attr('quantity') == '0') {
$option.text($option.text().trim() + ' (message)');
}
Then, to remove the message, you can do something like this:
$option.text($option.text().slice(0, $option.text().indexOf('(')).trim());
You can populate the option with like this,
$(document).ready(function () {
$('.valid').on('change', function () {
if ($(this.options[this.selectedIndex]).attr('quantity') == 0) {
$(this.options[this.selectedIndex]).find('span').remove();
$(this.options[this.selectedIndex]).append('<span>Message</span>')
}
});
});
JSFIDDLE
I'm not entirely sure of what you're trying to achieve from your question, but you cannot add html elements to an option element. You can however change the text as follows:
$(document).on('change', '.valid', function(){
var selected = $('.valid > option:selected');
if(selected.attr('quantity') == '0'){
selected.text('something else');
}
});
if you wanted to append an error you could do so by using jQuery append() or concatenating with the original value. Alternatively if you wanted it as validation outside of the select box, you could simply assign to the value of a div by replacing the line inside of the if statement.
<select class="valid" onchange="quality(this.options[this.selectedIndex].getAttribute('quantity'));">
<option disabled="disabled" selected="selected" value="">Select Bar</option>
<option value="1" quantity="99">value 1 </option>
<option value="2" quantity="0">value 2 </option>
</select>
<span id="msg"></span>
<script type="text/javascript">
function quality(val) {
if(parseInt(val) == 0){
document.getElementById("msg").innerHTML = "Message";
}
}

Add click event on an option in html select tag [duplicate]

This question already has answers here:
The onclick event does not work for options
(5 answers)
Closed 8 years ago.
I have a html dropdown defined as
<select name="evidence_selected"id="evidence_selected">
<option id="a">A</option>
<option id="b">B</option>
<option id="c">C</option>
<option id="new">New</option>
</select>
I want to fire an on click event on "new" so that when a user clicks on it, a free form appears where they enter some other value that is not on dropdown.
The id of the form is "new_value".
I tried
$("#new").click(function(){
$("new_value").show();
});
It seems the click event wont fire.
Any help(with code snippet) will be highly appreciated.
Regards
Selects use the change event
$('select').change(function () {
if ($(this).val() === 'New') {
// Handle new option
}
});
This will trigger any time any of the options are selected.
I advice doing something like this instead:
$('#evidence_selected').change(function(){
if($(this).val() == "New"){
$("#new_value").show();
} else {
$("#new_value").hide();
}
});
JSFiddle Demo
This way, the function will be triggered when the value of the select changes, but it'll only show #new_value if the option <option id="new">New</option> was selected...
Also if the ID of your form is new_value, you should reference it as $("#new_value").show(); instead of $("new_value").show(); (you're lacking the #)
Try this:
html
<select name="evidence_selected" id="evidence_selected">
<option id="a">A</option>
<option id="b">B</option>
<option id="c">C</option>
<option id="new">New</option>
</select>
js
$("#evidence_selected").change(function(){
if($(this).val()=="new"){
$("new_value").show();
}
});
fiddle
$("#evidence_selected").on('change', function() {
var optionId = $('option:selected', this).attr('id');
if(optionId === 'new') {
// your action here
}
});

Disabling other dropboxes on selection of value in one

I am trying to write a function that will:
Disable the submit button when no option in a dropbox is selected (ie empty string is selected). Enable all dropboxes.
On user selection of an option in a dropbox (that is not the empty
string), disable all other drop boxes and enable the submit button.
However, as a beginner at JavaScript I have no idea how I would begin this. How would I write such code?
So my simplified HTML would be as follows :
<form id="form" name="form" method="post" action="confirmation.cshtml">
<select name="start_to_end_time" class="start_to_end_time">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="start_to_end_time" class="start_to_end_time">
<option value="3">3</option>
<option value="4">4</option>
</select>
<button type="submit">Submit</button>
How can I write code that fulfills this function?
I think it's not a good idea to give two HTML element the same name attribute unless you use brackets [] within it. The last one may overwrite the value of the first one.
JavaScript using MooTools:
$$('.start_to_end_time').each(function(element) {
element.addEvent('click', function(ev) {
$$('.start_to_end_time').each(function(selectbox) {
if (element.getProperty('value') != '') {
$('button').setProperty('disabled', '');
$$('.start_to_end_time').each(function(b) {
if (b != element) {
b.setProperty('disabled', 'disabled');
} else {
b.setProperty('disabled', '');
}
}
} else {
$('button').setProperty('disabled', 'disabled');
$$('.start_to_end_time').each(function(b) {
b.setProperty('disabled', '');
}
}
});
});
});
I didn't test the code. You may define some methods to make it more readable.
start by loading the button as disabled:
<button id="myButton" type="submit" disabled='disabled'>Submit</button>
also, add a onchange listener to your options:
<select onchange="myJSFunction()" name="start_to_end_time" class="start_to_end_time">
<option value="3">3</option>
<option value="4">4</option>
then, write the javascript function:
function myJSFunction(){
var myButton = document.getElementById('myButton');
myButton.removeAttribute("disabled");
}
To check the selected value and disable accordingly (this must be executed in the function called by the onchange method):
var mySelect =document.getElementById('mySelect');
var mySelectedIndex = mySelect.selectedIndex;
if (mySelectedIndex==0){
mySelect.setAttribute("disabled","disabled);
}

Javascript IE innerHTML of <select>

I'm trying to change the innerHTML of a element based on the value of the previous element.
I have the javascript correctly grabbing the current value and everything works correctly in Firefox, Safari, Chrome and Opera. IE is a pain.
sample code:
<form action="soap.php" method="post">
<select name="circuitproduct" id="circuitproduct" onchange="bandwidthfunction();">
<option>Dedicated Voice</option>
<option>Frame Relay</option>
<option>ATM</option>
<option>Dedicated Internet</option>
<option>IP Solutions Private Port</option>
<option>IP Solutions Enhanced Port</option>
<option>Private Line – Domestic</option>
<option>Int’l Private Line</option>
<option>Qwest Metro Private Line (QMPL)</option>
<option>Qwest Metro Ethernet Private Line (QMEPL)</option>
</select><br />
<select name="term" id="term">
<option value="1-Year">1-Year</option>
<option value="2-Year">2-Year</option>
<option value="3-Year">3-Year</option>
</select>
<select id="bandwidth">
</select>
<select id="sublooptype">
</select>
</form>
sample javascript:
function bandwidthfunction() {
var product = document.getElementById('circuitproduct').value;
if (product == 'Dedicated Voice') {
document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');
document.getElementById('sublooptype').innerHTML = ('<option value="Special Access">Special Access</option><option>CO MtPt - Special Access</option><option>CPA Special Access</option>');
}
else if (product == 'Frame Relay') {
document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');
document.getElementById('sublooptype').innerHTML = ('<option value="Special Access">Special Access</option><option>CO MtPt - Special Access</option><option>CPA Special Access</option>');
}
Well, first of all you have a closing tag for the select that you try to put inside the select element, which makes the code invalid.
Then there might be a problem with how the select element treats it's content. When the HTML code is parsed, the select element doesn't have any child elements, like a regular element does. Instead the options are items in it's options collection.
If you want to change the items in the select element, change the content of it's option collection. I.e. to add items, create option objects using the document.createElement method and add to the collection. Example:
var opt = document.createElement('OPTION');
opt.text = 'Choose me';
opt.value = 42;
document.getElementById('bandwidth').options.add(opt);
You have to remove the "select"-Element and the end of setting the innerHTML-Property. This is not a part of innerHTML. Its the end-tag of the element 'bandwith' itself.
document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');
Here's a handy hack I came across that works in both FF and IE as a workaround to the inability to change innerHTML on select elements.
document.getElementById('bandwidth').outerHTML = document.getElementById('bandwidth').outerHTML.replace( document.getElementById('bandwidth').innerHTML + '</select>' , '<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>' + '</select>' );
or as a function for readability:
function swapInnerHTML(objID,newHTML) {
var el=document.getElementById(objID);
el.outerHTML=el.outerHTML.replace(el.innerHTML+'</select>',newHTML+'</select>');
}
I recently came across this problem with IE. I came up with a turnkey solution that works with the following things in mind:
You don't want to use jQuery
Need it to work in IE < 9
You want to append ( not replace the existing options ) string options into an existing select element
The select must be a type of "select-one"
Must wrap selects in their own parent element
We have many landing pages requesting the same information (age, products, country, state etc... ) but with different select options. The implementation I use appends new select options. This was done to allow a custom default option per lading page. One page may have the first option as "select item" another may have "choose one" and so forth.
Select format:
<div> <!-- you MUST wrap the select in a tag without any siblings -->
<select name="age" id="form-age">
<option value="">Choose Age</option>
</select>
</div> <!-- you MUST wrap the select in a tag without any siblings -->
Here is the function to APPEND/ADD values:
function addOptions(el, options){
// checks to make sure element exists and is a select
if(el && el.type === "select-one"){
el.innerHTML = el.innerHTML + options;
el.parentNode.innerHTML = el.outerHTML; // needed for IE
}
}
Now to execute the function pass in the select object and string values:
addOptions(
document.getElementById("form-age"),
'<option value="1">18-25</option><option value="2">26-35</option><option value="3">36-45</option><option value="4">46-55</option><option value="5">56-65</option><option value="6">66-75</option><option value="7">76-85</option><option value="8">86+</option>'
);
This will generate a select with the options passed, even in IE!
<div> <!-- you MUST wrap the select in a tag without any siblings -->
<select name="age" id="form-age">
<option value="">Choose Age</option>
<option value="1">18-25</option><option value="2">26-35</option><option value="3">36-45</option><option value="4">46-55</option><option value="5">56-65</option><option value="6">66-75</option><option value="7">76-85</option><option value="8">86+</option>
</select>
</div> <!-- you MUST wrap the select in a tag without any siblings -->
If you needed the script to REPLACE the values use the following:
function replaceOptions(el, options){
if(el && el.type === "select-one"){
el.innerHTML = options;
el.parentNode.innerHTML = el.outerHTML; // needed for IE
}
}
I hope this helps someone else!
A quick search shows this has been a known bug in IE since at least IE5. You could try to use createElement and make options and append to the select object, or use a library like jQuery and append the html to the node (which must take care of the magic necessary to work in IE).
The real cause of the problem is that due to a DOM parsing/updating problem, IE will not insert child option elements into a select element. Even IE9 still has this problem (later versions not checked).
You have to put the select in a div or span and replace the whole select. Below you will find an example that shows that then IE will play ball as well. Because this innerHTML problem generally occurs when dynamically generating selects, I made an AJAX & PHP example.
The html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chain(ed) select with AJAX and PHP</title>
<style>
select {
min-width: 170px;
}
option.toSelect {
background: yellow;
}
</style>
</head>
<body>
<form action="whatever.php">
<span>
<select id="cities" onchange="getOptions(this.value,'airlinesContainer')">
<option value="">Select a city:</option>
<option value="boston_airlines">Boston</option>
<option value="chicago_airlines" class="toSelect">Chicago</option>
<option value="newyork_airlines">New York</option>
</select>
</span>
<span id="airlinesContainer">
<select>
</select>
</span>
<span id="classesContainer">
<select>
</select>
</span>
</form>
<script>
function getOptions(qValue,containerId) {
var ajaxRequest = new XMLHttpRequest();
if ((qValue == "") || (containerId == "")) {
alert('Invalid selection.');
return;
}
ajaxRequest.onreadystatechange = function() {
if ((ajaxRequest.readyState == 4) && (ajaxRequest.status == 200)) {
document.getElementById(containerId).innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET","getoptions.php?q="+qValue,true);
ajaxRequest.send();
}
</script>
</body>
</html>
.
And the php file, which should be named 'getoptions.php' and should be put in the same folder:
<?php
$q = $_GET['q'];
$chicago_airlines ='
<select id="airlines" onchange="getOptions(this.value,\'classesContainer\')">
<option value="">Select an airline:</option>
<option value="delta_classes">Delta</option>
<option value="klm_classes" class="toSelect">KLM</option>
<option value="united_classes">United Airlines</option>
</select>';
$klm_classes ='
<select id="classes">
<option value="business">World Business Class</option>
<option value="comfort">Economy Comfort</option>
<option value="economy">Economy</option>
</select>';
if ($q == 'chicago_airlines') {
echo $chicago_airlines;
}
elseif ($q == 'klm_classes') {
echo $klm_classes;
}
else {
echo '<select>
<option>Invalid selection</option>
</select>';
}
?>
.
Be sure to select only the options with a yellow background, in this demo.
use Jquery
$('#bandwidth').html('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');

Categories