Reputation: 978
I want to prevent a select box from being changed if a certain condition applies. Doing this doesn't seem to work:
$('#my_select').bind('change', function(ev) {
if(my_condition)
{
ev.preventDefault();
return false;
}
});
I'm guessing this is because by this point the selected option has already changed.
What are other ways of doing this?
Upvotes: 55
Views: 120648
Reputation: 1
Very easy... if my_condition
is true, the select will restore to default option, usually the <option value=''>Please, select an option</option>
after 500ms.
function set_default(id)
{
setTimeout(function () { $('#'+id).val(''); }, 500);
}
$('#my_select').on('change', function()
{
if(my_condition)
{
alert('Wrong option!');
set_default( $(this).attr('id') );
}
});
Upvotes: 0
Reputation: 1
$(document).ready(function () {
$.post("/home/getvisits")
.done(function (res) {
for (var item in res) {
$("#table").append(
"<tr>" +
"<td>" + res[item].pkID + "</td>"+
"<td>" + res[item].Name + " " + res[item].Family + "</td>"+
"<td>" + res[item].Tshamsi + "</td>" +
"<td>" + res[item].Pname + " " + res[item].Pfamily + "</td>" +
"<td>" + res[item].Mobile + "</td>" +
"<td>" + res[item].VisitType + "</td>" +
"<td class='status' align='center' id=status-" + res[item].pkID + " onclick='get(this.id)'>" + "<select class='o1' onchange='getValue(this.value)'>" + "<option>" + res[item].Status + "</option>" +"</select>"+"</td>"
);
}
})
.fail(function () {
})
.always(function () {
})
})
function getValue(data) {
var e = document.getElementById("ch").innerHTML;
var myDiv = e.split("-");
var chdata = data;
var spdata = chdata.split("-");
$.post("/home/setdatastate", { myDiv: myDiv[1], spdata: spdata[0] })
.done(function (res) {
if (res == 1) {
location.reload();
}
})
.fail(function () {
})
.always(function () {
})
}
function get(getdata) {
var i = getdata;
document.getElementById("ch").innerHTML = i;
$.post("/home/setstatus")
.done(function (res) {
$(".o1").empty();
for (var item in res) {
$(".o1").append(
"<option>" + res[item].pkID + "-" + res[item].Status + "</option>"
);
}
})
.fail(function () {
})
.always(function () {
})
}
<p id="ch" style="display: none"></p>
</div>
</div>
<table class="table">
<thead>
<tr class="filters">
<th><input type="text" class="form-control" placeholder="ردیف" disabled></th>
<th><input type="text" class="form-control" placeholder="مشخصات پزشک" disabled></th>
<th><input type="text" class="form-control" placeholder="تاریخ مراجعه" disabled></th>
<th><input type="text" class="form-control" placeholder="مشخصات بیمار" disabled></th>
<th><input type="text" class="form-control" placeholder="شماره همراه بیمار" disabled></th>
<th><input type="text" class="form-control" placeholder="نوع ویزیت" disabled></th>
<th><input type="text" class="form-control" placeholder="وضعیت" disabled></th>
</tr>
</thead>
<tbody id="table">
</tbody>
</table>
***6l.jpg
Upvotes: -1
Reputation: 1
None of the other answers worked for me, here is what eventually did.
I had to track the previous selected value of the select element and store it in the data-* attribute. Then I had to use the val() method for the select box that JQuery provides. Also, I had to make sure I was using the value attribute in my options when I populated the select box.
<body>
<select id="sel">
<option value="Apple">Apple</option> <!-- Must use the value attribute on the options in order for this to work. -->
<option value="Bannana">Bannana</option>
<option value="Cherry">Cherry</option>
</select>
</body>
<script src="https://code.jquery.com/jquery-3.5.1.js" type="text/javascript" language="javascript"></script>
<script>
$(document).ready()
{
//
// Register the necessary events.
$("#sel").on("click", sel_TrackLastChange);
$("#sel").on("keydown", sel_TrackLastChange);
$("#sel").on("change", sel_Change);
$("#sel").data("lastSelected", $("#sel").val());
}
//
// Track the previously selected value when the user either clicks on or uses the keyboard to change
// the option in the select box. Store it in the select box's data-* attribute.
function sel_TrackLastChange()
{
$("#sel").data("lastSelected", $("#sel").val());
}
//
// When the option changes on the select box, ask the user if they want to change it.
function sel_Change()
{
if(!confirm("Are you sure?"))
{
//
// If the user does not want to change the selection then use JQuery's .val() method to change
// the selection back to what it was previously.
$("#sel").val($("#sel").data("lastSelected"));
}
}
</script>
I hope this can help someone else who has the same problem as I did.
Upvotes: 0
Reputation: 1598
I was looking for "javascript prevent select change" on Google and this question comes at first result. At the end my solution was:
const $select = document.querySelector("#your_select_id");
let lastSelectedIndex = $select.selectedIndex;
// We save the last selected index on click
$select.addEventListener("click", function () {
lastSelectedIndex = $select.selectedIndex;
});
// And then, in the change, we select it if the user does not confirm
$select.addEventListener("change", function (e) {
if (!confirm("Some question or action")) {
$select.selectedIndex = lastSelectedIndex;
return;
}
// Here do whatever you want; the user has clicked "Yes" on the confirm
// ...
});
I hope it helps to someone who is looking for this and does not have jQuery :)
Upvotes: 1
Reputation: 1
if anybody still interested, this solved the problem, using jQuery 3.3.1
jQuery('.class').each(function(i,v){
jQuery(v).data('lastSelected', jQuery(v).find('option:selected').val());
jQuery(v).on('change', function(){
if(!confirm('Are you sure?'))
{
var self = jQuery(this);
jQuery(this).find('option').each(function(key, value){
if(parseInt(jQuery(value).val()) === parseInt(self.data('lastSelected')))
{
jQuery(this).prop('selected', 'selected');
}
});
}
jQuery(v).data('lastSelected', jQuery(v).find('option:selected').val());
});
});
Upvotes: 0
Reputation: 638
$('#my_select').bind('mousedown', function (event) {
event.preventDefault();
event.stopImmediatePropagation();
});
Upvotes: 0
Reputation: 13842
This worked for me, no need to keep a lastSelected
if you know the optionIndex
to select.
var optionIndex = ...
$(this)[0].options[optionIndex].selected = true;
Upvotes: 0
Reputation: 23283
Try this:
var my_condition = true;
var lastSel = $("#my_select option:selected");
$("#my_select").change(function(){
if(my_condition)
{
lastSel.prop("selected", true);
}
});
$("#my_select").click(function(){
lastSel = $("#my_select option:selected");
});
Upvotes: 55
Reputation: 1076
This was the ONLY thing that worked for me (on Chrome Version 54.0.2840.27):
$('select').each(function() {
$(this).data('lastSelectedIndex', this.selectedIndex);
});
$('select').click(function() {
$(this).data('lastSelectedIndex', this.selectedIndex);
});
$('select[class*="select-with-confirm"]').change(function() {
if (!confirm("Do you really want to change?")) {
this.selectedIndex = $(this).data('lastSelectedIndex');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruits' class="select-with-confirm">
<option selected value="apples">Apples</option>
<option value="bananas">Bananas</option>
<option value="melons">Melons</option>
</select>
<select id='people'>
<option selected value="john">John</option>
<option value="jack">Jack</option>
<option value="jane">Jane</option>
</select>
Upvotes: 0
Reputation: 1
Implement custom readonly like eventHandler
<select id='country' data-changeable=false>
<option selected value="INDIA">India</option>
<option value="USA">United States</option>
<option value="UK">United Kingdom</option>
</select>
<script>
var lastSelected = $("#country option:selected");
$("#country").on("change", function() {
if(!$(this).data(changeable)) {
lastSelected.attr("selected", true);
}
});
$("#country").on("click", function() {
lastSelected = $("#country option:selected");
});
</script>
Demo : https://jsfiddle.net/0mvajuay/8/
Upvotes: 0
Reputation: 629
You can do this without jquery...
<select onchange="event.target.selectedIndex = 0">
...
</select>
or you can do a function to check your condition
<select onchange="check(event)">
...
</select>
<script>
function check(e){
if (my_condition){
event.target.selectedIndex = 0;
}
}
</script>
Upvotes: 1
Reputation: 27
None of the answers worked well for me. The easy solution in my case was:
$("#selectToNotAllow").focus(function(e) {
$("#someOtherTextfield").focus();
});
This accomplishes clicking or tabbing to the select drop down and simply moves the focus to a different field (a nearby text input that was set to readonly) when attempting to focus on the select. May sound like silly trickery, but very effective.
Upvotes: 1
Reputation: 331
In the event someone needs a generic version of mattsven's answer (as I did), here it is:
$('select').each(function() {
$(this).data('lastSelected', $(this).find('option:selected'));
});
$('select').change(function() {
if(my_condition) {
$(this).data('lastSelected').attr('selected', true);
}
});
$('select').click(function() {
$(this).data('lastSelected', $(this).find('option:selected'));
});
Upvotes: 32
Reputation: 101
If you simply want to prevent interaction with the select altogether when my_condition is true, you could always just capture the mousedown event and do your event prevent there:
var my_condition = true;
$("#my_select").mousedown(function(e){
if(my_condition)
{
e.preventDefault();
alert("Because my_condition is true, you cannot make this change.");
}
});
This will prevent any change event from ever occurring while my_condition is true.
Upvotes: 10
Reputation: 76557
Another option to consider is disabling it when you do not want it to be able to be changed and enabling it:
//When select should be disabled:
{
$('#my_select').attr('disabled', 'disabled');
}
//When select should not be disabled
{
$('#my_select').removeAttr('disabled');
}
Update since your comment (if I understand the functionality you want):
$("#dropdown").change(function()
{
var answer = confirm("Are you sure you want to change your selection?")
{
if(answer)
{
//Update dropdown (Perform update logic)
}
else
{
//Allow Change (Do nothing - allow change)
}
}
});
Upvotes: 2
Reputation: 566
You might need to use the ".live" option in jQuery since the behavior will be evaluated in real-time based on the condition you've set.
$('#my_select').live('change', function(ev) {
if(my_condition)
{
ev.preventDefault();
return false;
}
});
Upvotes: 0