How to toggle readonly to select2 - javascript

I tried to set readonly attribute to second select2 based on value of first select2 option.
I have my script as below:
<select name="Name" id="Name" style='width:45%'>
<option value="1">disable</option>
<option value="2">enable</option>
</select>
<select name="Name2" id="Name2" style='width:45%'>
<option value="d">David</option>
<option value="b">Bob</option>
</select>
My JS script is to set it is like below:
$(document).ready(function(){
$('#Name,#Name2').select2();
$('#Name').change(function(){
var val = $(this).val();
if(val==1)
{
$('#Name2').attr('readonly','readonly');
}else
{
$('#Name2').removeAttr('readonly');
}
})
})
However, the script above won't be working for select2 option but for textbox is fine. (Fiddlejs)
I tried to search some sources here but it did not help.
Thanks.

The above answers are not going to work with the updated versions of select2,
follow the link for the hack
https://stackoverflow.com/a/55001516/9945426

use .prop() to set disabled or not based on the value
$(document).ready(function() {
$('#Name').change(function() {
var val = $(this).val();
$('#Name2').prop('disabled', val == 1);//prop disabled
}).change();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="Name" id="Name" style='width:45%'>
<option value="1">disable</option>
<option value="2">enable</option>
</select>
<select name="Name2" id="Name2" style='width:45%'>
<option value="d">David</option>
<option value="b">Bob</option>
</select>

Use jQuery .prop() method like this
$('#Name2').prop("disabled", true) for disable and
$('#Name2').prop("disabled", false) for enabling select2.
Here is the (Fiddlejs)

Related

Change ReadOnly Input Value on <select> option change

I want to display the value in a "select > option" in an based on the location selected from my tag.
Here is the html:
<select name="stateCoord" id="stateCoord" autocomplete="off">
<option selected="selected">SELECT STATE</option>
<option value="lg">Lagos</option>
<option value="abj">Abuja</option>
</select>
<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo" readonly>
And here is the javascript:
$(document).ready(function() {
$("#stateCoord option").filter(function() {
return $(this).val() == $("#stateCoordInfo").val();
}).attr('selected', true);
$("#stateCoord").live("change", function() {
$("#stateCoordInfo").val($(this).find("option:selected").attr("value"));
});
});
I'm still getting the hang on javascript so a detailed explanation won't hurt. Thanks in advance.
If I assume correctly, you want this:
1) initialization of the select option at document ready, that strange thing the code with filter() was trying to do.
2) Capture the change event on the select and show the value of the current selected option on the input. This is what the live() (deprecated) part was trying to do.
$(document).ready(function()
{
$("#stateCoord").val("").change();
$("#stateCoord").change(function()
{
$("#stateCoordInfo").val($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="stateCoord" id="stateCoord">
<option value="" selected>SELECT STATE</option>
<option value="lg">Lagos</option>
<option value="abj">Abuja</option>
</select>
<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo">
$(document).ready(function() {
$("body").on("change","#stateCoord",function() {
$("#stateCoordInfo").val($(this).find("option:selected").val());
});
$("#stateCoord").trigger("change");
});
From what I understand, you want to update the text shown in the readonly text box with the value attribute of the selected option from the dropdown.
To do this, you just need to update the val of your read-only text box to the val of the drop-down whenever change event is fired.
$(document).ready(function() {
$('#stateCoord').change(function(e) {
$('#stateCoordInfo').val($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="stateCoord" id="stateCoord" autocomplete="off">
<option selected="selected">SELECT STATE</option>
<option value="lg">Lagos</option>
<option value="abj">Abuja</option>
</select>
<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo" readonly>
I am not sure, if this is what you need, but I think it should be: JSfiddle
Here is the JS code:
$(document).ready(function() {
$("#stateCoord").change(function() {
var value = $("#stateCoord option:selected").text();
$("#stateCoordInfo").val(value);
});
});

Html select onchange get custom attribute value set to other input value

onchange I want to get the select option custom attribute and set to the other input's value. Somehow I cannot get the course_price in the input onchange of the select. It only shows the first option value in the input only.
function selectFunction(e) {
var value1 = $("#test").data('typeid'); //to get value
document.getElementById("money").value = value1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" onchange="selectFunction(event)">
<option id="test" data-typeid="<?php echo $row1['course_price']?>"
value="<?php echo $row1['course_id']?>"><?php echo $row1['course_name']?>
</option>
</select>
<input type="number" value="" id="money" class="form-control">
The issue is because the data-typeid attribute is on the selected option, not the select, so your jQuery code is looking at the wrong element. You can fix this by using find() and :selected to get the chosen option before reading the data attribute from it.
Also note that on* attributes are very outdated. You should be using unobtrusive event handlers, something like this:
$(function() {
$('select.form-control').change(function() {
var typeId = $(this).find('option:selected').data('typeid');
$("#money").val(typeId);
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option data-typeid="1111" value="courseId1">courseName1</option>
<option data-typeid="2222" value="courseId2">courseName2</option>
</select>
<input type="number" value="" id="money" class="form-control">
In your question you are using #test which is id for all options and so it will always consider first occurance of id test. So do not use same id multiple times on the same DOM, change it to class="test" if you need it, otherwise, you need to target the selected option, and it will not need any id or class. Check here:
var type_id = $('select option:selected').attr('data-typeid');
and assign the variable to input box:
document.getElementById("money").value =type_id;
So the entire updated function will be like this:
function selectFunction(e) {
var type_id = $('select option:selected').attr('data-typeid'); //to get value
document.getElementById("money").value =type_id;
}
Another way to make it:
$(document).on('change', 'select.form-control', function() {
var r = $('select.form-control option[value="'+$(this).val()+'"]').attr("data-typeid")
$("#money").val(r)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option selected disabled>-- Select one --</option>
<option data-typeid="1111" value="courseId1">courseName1</option>
<option data-typeid="2222" value="courseId2">courseName2</option>
</select>
<input type="number" value="" id="money" class="form-control">

PHP dropdown if value is selected

I currently have a block of jQuery that I have included this seems to work fine on the comps I have tested OSX, XP however on mobile devices and another computers I have had people to test its still going to the old URL however I do suspect it could be a cache issue but is there a way to develop a PHP fall back?
What I would like to do if the prop2 value is selected I would like to change the form action url almost onclick like the jQuery does.
HTML:
<form action='bookingurl' method='get'>
<label for='channel_code' class="caption">Select property </label>
<select id='channel_code' name='id'>
<option value='prop1'>Prop 1</option>
<option value='prop2'>Prop 2</option>
</select>
</form>
jQuery:
jQuery(document).ready(function(){
jQuery('#channel_code').change(function(){
if(jQuery('#channel_code').val() == 'prop2'){
window.location.href = 'https://hotels.cloudbeds.com/reservation/url';
}
});
});
$(document).ready(function() {
$('#channel_code').change(function() {
if ($('#channel_code option:selected').val() == 'prop2') {
alert("go to")
//window.location.href = 'https://hotels.cloudbeds.com/reservation/url';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='bookingurl' method='get'>
<label for='channel_code' class="caption">Select property</label>
<select id='channel_code' name='id'>
<option value='prop1'>Prop 1</option>
<option value='prop2'>Prop 2</option>
</select>
</form>
Specify the selector as:
$('#channel_code option:selected').val()//meaning option selected value

Select first option that is not empty

Does anyone know how to autoselect in a selectbox? I want to do is even though there is a blank option the selectbox will still show the option that has a value on it.
Does anyone know how to do it in jquery?
html code:
<select name="name">
<option></option>
<option>Mark</option>
</select>
<select name="age">
<option></option>
<option>16</option>
</select>
May this help you :
HTML:
<select name="name">
<option></option>
<option>Mark</option>
</select>
<select name="age" id='some'>
<option></option>
<option>16</option>
</select>
Jquery:
$($('#some').children()[1]).attr('selected',true)
If you have more than one empty option, and there is no order, this is the best solution I think: jsFiddle Live Demo
What we've done here is, checking every selectbox by a each loop:
$('select').each(function()
{
});
And then inside the loop we find the first option which is not empty:
$(this).find('option:not(:empty)').first()
And make it selected by prop:
$(this).find('option:not(:empty)').first().prop('selected',true);
So the whole jQuery and Html will be:
jQuery
$('select').each(function()
{
$(this).find('option:not(:empty)').first().prop('selected',true);
});
HTML
<select name="name">
<option></option>
<option>Mark</option>
</select>
<select name="age">
<option></option>
<option>16</option>
<option>20</option>
<option></option>
<option>55</option>
<option></option>
</select>
If you want to do this to all select boxes on the page, use this:
$(function () {
$('select').each(function () {
$(this).find('option').not(':empty()').first().attr('selected', true);
})
});
It grabs each select, finds the first option that is not empty (read: has text inside it) and sets the selected attribute.
See the fiddle.
No need for javascript to do this, if you want to select (Mark) for example, do it like this
<select name="name">
<option></option>
<option selected>Mark</option>
</select>
and in XHTML:
<select name="name">
<option></option>
<option selected="selected">Mark</option>
</select>

How to pass parameters on onChange of html select

I am a novice at JavaScript and jQuery. I want to show one combobox-A, which is an HTML <select> with its selected id and contents at the other place on onChange().
How can I pass the complete combobox with its select id, and how can I pass other parameters on fire of the onChange event?
function getComboA(selectObject) {
var value = selectObject.value;
console.log(value);
}
<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
The above example gets you the selected value of combo box on OnChange event.
Another approach wich can be handy in some situations, is passing the value of the selected <option /> directly to the function like this:
function myFunction(chosen) {
console.log(chosen);
}
<select onChange="myFunction(this.options[this.selectedIndex].value)">
<option value="1">Text 1</option>
<option value="2">Text 2</option>
</select>
For how to do it in jQuery:
<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>
<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>
You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.
JavaScript Solution
<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
document.getElementById("comboA").onchange = function(){
var value = document.getElementById("comboA").value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = function(evt){
var value = evt.target.value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = handleChange;
function handleChange(evt){
var value = evt.target.value;
};
</script>
I found #Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:
var changeitem = function (sel) {
console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';
The normal behavior may be to say
newSelect.onchange = changeitem;
But this does not really allow you to specify that argument passed in, so instead you may do this:
newSelect.setAttribute('onchange', 'changeitem(this)');
And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange function will be browser dependent. The second way seems to work cross-browser just fine.
jQuery solution
How do I get the text value of a selected option
Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:
$( "#myselect" ).val();
// => 1
The second is the text value of the select.
For example, using the following select box:
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:
$( "#myselect option:selected" ).text();
// => "Mr"
See also
.val() jQuery API Documentation
This is helped for me.
For select:
$('select_tags').on('change', function() {
alert( $(this).find(":selected").val() );
});
For radio/checkbox:
$('radio_tags').on('change', function() {
alert( $(this).find(":checked").val() );
});
You can try bellow code
<select onchange="myfunction($(this).val())" id="myId">
</select>
Html template:
<select class="staff-select">
<option value="">All</option>
<option value="196">Ivan</option>
<option value="195">Jon</option>
</select>
Js code:
const $staffSelect = document.querySelector('.staff-select')
$staffSelect.onchange = function () {
console.log(this.value)
}
Just in case someone is looking for a React solution without having to download addition dependancies you could write:
<select onChange={this.changed(this)}>
<option value="Apple">Apple</option>
<option value="Android">Android</option>
</select>
changed(){
return e => {
console.log(e.target.value)
}
}
Make sure to bind the changed() function in the constructor like:
this.changed = this.changed.bind(this);
this code once i write for just explain onChange event of select you can save this code as html and see output it works.and easy to understand for you.
<html>
<head>
<title>Register</title>
</head>
<body>
<script>
function show(){
var option = document.getElementById("category").value;
if(option == "Student")
{
document.getElementById("enroll1").style.display="block";
}
if(option == "Parents")
{
document.getElementById("enroll1").style.display="none";
}
if(option == "Guardians")
{
document.getElementById("enroll1").style.display="none";
}
}
</script>
<form action="#" method="post">
<table>
<tr>
<td><label>Name </label></td>
<td><input type="text" id="name" size=20 maxlength=20 value=""></td>
</tr>
<tr style="display:block;" id="enroll1">
<td><label>Enrollment No. </label></td>
<td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
</tr>
<tr>
<td><label>Email </label></td>
<td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
</tr>
<tr>
<td><label>Mobile No. </label></td>
<td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
</tr>
<tr>
<td><label>Address</label></td>
<td><textarea rows="2" cols="20"></textarea></td>
</tr>
<tr >
<td><label>Category</label></td>
<td><select id="category" onchange="show()"> <!--onchange show methos is call-->
<option value="Student">Student</option>
<option value="Parents">Parents</option>
<option value="Guardians">Guardians</option>
</select>
</td>
</tr>
</table><br/>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
function setMyValue(v) {
console.log(v);
}
<select onchange="setMyValue(this.value)">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
This worked for me onchange = setLocation($(this).val())
Here.
#Html.DropDownList("Demo",
new SelectList(ViewBag.locs, "Value", "Text"),
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });
Simply:
function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
function retrieve_other() {
alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}
function retrieve() { alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
<HTML>
<BODY>
<p>RETRIEVING TEXT IN OPTION OF SELECT </p>
<form name="myForm" action="">
<P>Select:
<select id="SMS_recipient">
<options value='+15121234567'>Andrew</option>
<options value='+15121234568'>Klaus</option>
</select>
</p>
<p>
<!-- Note: Despite the script engine complaining about it the code works!-->
<input type="button" onclick="retrieve()" value="Try it" />
<input type="button" onclick="retrieve_other()" value="Try Form" />
</p>
</form>
</HTML>
</BODY>
Output:
Klaus or Andrew depending on what the selectedIndex is. If you are after the value just replace .text with value. However if it is just the value you are after (not the text in the option) then use document.getElementById('SMS_recipient').value
//html code
<select onchange="get(this)">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
//javscript code
function get(select) {
let value = select.value;
console.log(value);
}

Categories