Set attribute to readonly when dropdown value is changed - javascript

I have this dropdown that has 4 options.
What I want to achieve is to change the attribute of input text number to readonly when a user selects option3 or option4 from the dropdown.
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number: <input type="text" name="number">
This is the script that I have for now, what it does is just alert the selected value.
$(document).ready(function () {
$("#s_id").change(function () {
var x = $(this).val();
alert($(this).val());
if (x == opel) {
alert("iff");
$(this).attr("readOnly", "true");
}
});
});
JS Fiddle link
Any idea/s would be really appreciated!

Use prop to make readonly and remove it back
DEMO
$(document).ready(function () {
$("#s_id").change(function () {
if (this.value === 'option3' || this.value === 'option4')
$("input[name='number']").prop('readonly', true);
else
$("input[name='number']").prop('readonly', false);//enable it back again
});
});

You can simply check your .value in your change handler and use jQuery .prop method:
$("#s_id").change(function () {
var isReadonly = (this.value === 'option3' || this.value === 'option4');
$("input[name='number']").prop('readonly', isReadonly);
});
or using an array for making it easier to modify it in future:
$("#s_id").change(function () {
var isReadonly = ['option3', 'option4'].indexOf(this.value) > -1;
$("input[name='number']").prop('readonly', isReadonly);
});
Here is the working JSFiddle demo.

Use prop() to set the readonly property of the text-box.
Create an array of all the values of the drop-down which, when selected, the number text-box should be disabled.
Check if the selected value is in the array in the change event handler
If the selected option value is present in the array, disable the number text-box, else enable it
Demo
$(document).ready(function() {
// Values when selected, the number box should be disabled
var values = ['option2', 'option3'];
// On selection change of the dropdown
$("#s_id").change(function() {
// values.indexOf($(this).val()) > -1
// Checks if the value selected is from the array
// Comparison returns true when the value is in array, false otherwise
$('input[name="number"]').prop('readonly', values.indexOf($(this).val()) > -1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number:
<input type="text" name="number">

Try following code :-
$(this).attr("disabled", true);
I think drop down is always read only . what you can do is make it disabled
if you work with a form , the disabled fields does not submit , so use a hidden field to store disabled dropdown value

Please use this, You can also use it dynamically
Given below the HTML code
<select id="s_id">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
number: <input type="text" id="number" name="number">
Given below the JQuery code
$(document).ready(function () {
$("#s_id").change(function () {
var option_Array = ["option3","option4"]
var x = $(this).val();
$("#number").prop('readonly', false);
for(var i=0; i<option_Array.length; i++){
if (x == option_Array[i]){
$("#number").prop('readonly', true);
}
}
});
});

Related

Using jQuery to check and see if a select box has/or contains selected options

Using jQuery, upon a change/select event, how can I check and see if multiple select boxes contain any selected items? All I am looking for is how to capture and obtain a total count of this?
Based on a validation if not equal to 0, this would set a buttons default disabled attribute to false.
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
</form>
$('#myform select).bind("change select",function() {
});
Assuming your <button> is within the form element, the following should work for you:
// binding the anonymous function of the on() method
// as the event-handler for the 'change' event:
$('#myform').on('change', function() {
// caching the $(this) (the <form>, in this case):
var form = $(this);
// finding the <button> element(s) within the <form>
// (note that a more specific selector would be
// preferable), and updating the 'disabled' property,
// finding all <option> elements that are selected,
// filtering that collection:
form.find('button').prop('disabled', form.find('select option:selected').filter(function() {
// retaining only those whose values have a length
// (in order to not-count the default 'empty'
// <option> elements:
return this.value.length;
// and then checking if that collection is
// equal to 0, to obtain a Boolean true
// disabling the <button>, or a false to
// enable the <button>:
}).length === 0);
// triggering the change event on page-load
// to appropriately enable/disable the <button>:
}).change();
$('#myform').on('change', function() {
var form = $(this);
form.find('button').prop('disabled', form.find('select option:selected').filter(function() {
return this.value.length;
}).length === 0);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<br>Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<button>Submission button</button>
</form>
References:
change().
filter().
find().
on().
prop().
You can use the jQuery :checked selector to capture all elements that are checked. For the count, you can do:
$( "input:checked" ).length;
You can then do your condition to view if there are zero or more elements checked:
var selected = $( "input:checked" ).length;
if(selected > 0)
//do something
$('#myform select').on('change', function() {
var count = 0;
$('#myform').find('select').find('option').each(function(){
if ($(this).is(':selected')){
count++;
}
});
if (count < 0){
$('#mybutton').prop('disabled', false);
} else {
$('#mybutton').prop('disabled', true);
});
Grab all the selects on the page and just loop through them while adding a change event to each one.
Then in that change event, call a method that counts up how many selects have items selected.
https://jsfiddle.net/x833qr20/3/
// put an on change event on all the selects, can be done in onload
var ddl = $('select');
for (i = 0; i < ddl.length; i++) {
ddl[i].onchange = function() {
CountAllSelectedDDL();
}
}
// function that fires when one select gets changed
function CountAllSelectedDDL() {
var ddl = $('select');
var count = 0;
for (i = 0; i < ddl.length; i++) {
if (ddl[i].selectedIndex > 0) {
count++;
}
}
var button = document.getElementById('button');
if (count > 0) {
// set the buttons default disabled attribute to false
button.disabled = false;
} else {
button.disabled = true;
}
}
Hope this helps.
Here's a working example via jQuery
https://jsfiddle.net/wedh87bm/
$('#myform select').bind("change select",function() {
var completed = true;
$('#myform select').each(function(){
if($(this).val() == "")
{
completed = false;
}
});
if(completed)
{
$('#validate').prop("disabled",false);
} else
{
$('#validate').prop("disabled",true);
}
});

Change select option based on attribute

I am trying to change a select option on click but I don't want to use the option value. My code works if I give my button a value='3' but what I want is to select the one with data-price="0" which in my case is the one with value='3'.
JS :
jQuery(document).ready(function () {
jQuery('#sample-addtocart-button').click(function(){
jQuery('.product-custom-option').val(jQuery(this).attr('value'));
});
});
Html :
<button value="0" id="sample-addtocart-button" type="button">Free</button>
<select class="product-custom-option">
<option value="">-- Please Select --</option>
<option data-price="10" value="1">£10.00</option>
<option data-price="20" value="2">£20.00</option>
<option data-price="0" value="3">FREE</option>
</select>
Any help will be appreciated
You can use attribute equals selector to get the option and then select option by setting selected property using prop() method.
jQuery(document).ready(function() {
jQuery('#sample-addtocart-button').click(function() {
jQuery('.product-custom-option option[data-price="' + jQuery(this).attr('value') + '"]').prop('selected', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="0" id="sample-addtocart-button" type="button">Free</button>
<select class="product-custom-option">
<option value="">-- Please Select --</option>
<option data-price="10" value="1">£10.00</option>
<option data-price="20" value="2">£20.00</option>
<option data-price="0" value="3">FREE</option>
</select>
You can select elements by attribute, and then set the selected property on the element.
jQuery(document).ready(function () {
jQuery('#sample-addtocart-button').click(function(){
jQuery('.product-custom-option [data-price=' + this.value + ']').prop("selected", true);
});
});
This selects the element with a data-price attribute equal to the value of this.value, which is a descendant of .product-custom-option, and sets its selected property to true.
Without jQuery, it could look like this:
document.addEventListener("DOMContentLoaded", function () {
document.querySelector('#sample-addtocart-button').addEventListener("click", function(){
document.querySelector('.product-custom-option [data-price=' + this.value + ']').selected = true;
});
});
And a handful of helper methods always helps with the verbosity:
function listen(el, typ, fn, cap) {
el && el.addEventListener(typ, fn, cap)
}
function query(el, sel) {
if (typeof el === "string") {
sel = el;
el = document;
}
return el.querySelector(sel)
}
listen(document, "DOMContentLoaded", function () {
listen(query('#sample-addtocart-button'), "click", function(){
query('.product-custom-option [data-price=' + this.value + ']').selected = true;
});
});
Try this:
jQuery('#sample-addtocart-button').click(function(){
var val= jQuery(this).attr('value');
jQuery('.product-custom-option option[data-price='+val+']').prop('selected', true); // it will find the select option with certain data-price and make it selected
});

How to update a textarea's text relative to a checked radio button?

A textarea's text will be populated with a dropdown lists selected
text.
A simple radio button list will determine which dropdown list's text should be used.
CLICK HERE FOR DEMO
The code below creates the desired effect but does not make the expected changes when an alternate radio button value is selected.
Debugging shows checked is not added to radio inputs when a new selection is made.
JQUERY
var rbl = $('#rbl input:checked').val();
$('#ddlA1,#ddlB1').change(function () {
if (rbl = 1) {
$('#txt').val($('#ddlA1 :selected').text());
} else if (rbl = 2) {
$('#txt').val($('#ddlB1 :selected').text());
}
});
HTML
<span id="rbl">
<input type="radio" id="rbl_0" name="rbl" value="1" /> 1 <br />
<input type="radio" id="rbl_1" name="rbl" value="2" /> 2 <br />
</span>
<select id="ddlA1">
<option value="1">A1 A</option>
<option value="2">A1 B</option>
<option value="3">A1 C</option>
</select>
<select id="ddlB1">
<option value="1">B1 A</option>
<option value="2">B1 B</option>
<option value="3">B1 C</option>
</select>
<textarea id="txt">LOAD TEXT</textarea>
Your code is correct but you need to modify some little things ;)
$('#ddlA1,#ddlB1').change(function () {
var rbl = $('#rbl input:checked').val();
if (rbl == 1) {
$('#txt').val($('#ddlA1 :selected').text());
} else if (rbl == 2) {
$('#txt').val($('#ddlB1 :selected').text());
}
});
Put rbl variable inside the change event
Use == instead of = on your conditionals
http://jsfiddle.net/3kXsX/5/
That's all!
Best Regards,
Something more like this
$('#rbl_0, #rbl_1, #ddlA1, #ddlB1').on('change', function() {
var dropdown = $($('#rbl_0').is(':checked') ? '#ddlA1' : '#ddlB1');
$('#txt').val(dropdown.find('option:selected').text());
});
FIDDLE
The value of rbl is set once, when that line of code runs, and not updated if the selected radio changes. Put the var rbl = ... line inside the event handler so it checks the radios when a change is made to the dropdown, ie
$('#ddlA1,#ddlB1').change(function () {
var rbl = $('#rbl input:checked').val();
if (rbl = 1) {
$('#txt').val($('#ddlA1 :selected').text());
} else if (rbl = 2) {
$('#txt').val($('#ddlB1 :selected').text());
}
});

How to run a piece of javascript when you select a dropdown option?

I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};

Is there a SelectedIndex for an HTML5 DataList?

You can pick the current option of any select element:
mySelect.options[mySelect.selectedIndex]
Can I do the same with a DataList? Something like this:
<input id = "input" list = "datalist" type = "text" />
<datalist id = "datalist">
<option value = "No. 1"></option>
<option value = "No. 2"></option>
<option value = "No. 3"></option>
</datalist>
<script>
var datalist = document.getElementById ("datalist");
var input = document.getElementById ("input");
input.addEventListener ("keyup", function (event) {
if (event.which === 13) {
alert (datalist.options[datalist.selectedIndex]); // Example
}
}, false);
</script>
No, the datalist element is for providing autocomplete to inputs. It is a source of data, is hidden from the user, and multiple inputs may link to it. Therefore it doesn't make sense to have a selectedIndex.
Instead, you should simply check the .value of the input:
var datalist = document.getElementById ("datalist");
var input = document.getElementById ("input");
input.addEventListener ("keyup", function (event) {
if (event.which === 13) {
alert(input.value);
}
}, false);
Judging by specs, datalist object doesn't have selectedIndex property. But you can find it's default option, which have selected. Or compare input's value to each option value and manually find the index.
for (var i=0;i<datalist_id.options.length;i++)
if (datalist_id.options[i].value == input_id.value)
{alert(datalist_id.options[i].innerText);break;}
Lets say you have data attributes in the above example like this,
<input list="browsers" name="browser" value="Internet Explorer">
<datalist id="browsers">
<option value="Internet Explorer" data-company="Microsoft">
<option value="Firefox" data-company="Mozilla">
<option value="Chrome" data-company="Google/Alphabet">
<option value="Opera" data-company="Opera">
<option value="Safari" data-company="Apple">
</datalist>
and you want to obtain the data-company attribute of the selected item,
using the loop above
for (var i=0;i<datalist_id.options.length;i++) {
if (datalist_id.options[i].value == input_id.value) {
// obtains the data-company attrbute
console.log(datalist_id.options[i].getAttribute("data-company");
alert(datalist_id.options[i].innerText);
break;
}
}
You can just add a value to the input element. This will be shown to the user as the "default" value. If the user decides to change it, i.e. delete this value from the input field, then the list in the datalist will show up:
<input list="browsers" name="browser" value="Internet Explorer">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
Here is the script for getting index from SelectedIndex of Datalist. Html from #pingle60
let x = document.getElementById("browsers").options;
let input = document.querySelector('input');
input.onchange = getIndex;
function getIndex(e) {
for (var i=0;i<x.length;i++) {
if (x[i].value == e.target.value) {
return i;
// alert('The index of SellectedIndex is : ' + i + ' and the value is : ' +x[i].value);
break;
}
}
}

Categories