I have the following jQuery code for showing/hiding a conditional form field (contained within tr#other-employer). This works fine, once the page is loaded and options are changed.
I would like make it so that the conditinal field shows when the page is loaded and the option selected in the drop-down list with #employer is pre-selected (this is done with PHP).
I have tried removing $('tr#other-employer').hide(); , but then this showed the conditional field on load regardless if the drop-down field is other or not.
A simple sample page is here: http://brenda.upreach.org.uk/beta/form.php
$(document).ready(function () {
$('tr#other-employer').hide();
$('#employer').change(function () {
if ($(this).val() == "Other") {
$('tr#other-employer').fadeIn();
} else {
$('tr#other-employer').hide();
}
});
});
Any help greatly appreciated!
You can add an if condition like below to check the status of the select box and do the needful.
$(document).ready(function () {
$('tr#other-employer').hide();
/*********************************/
if($("select#employer").val() == "Other")
{ $('tr#other-employer').fadeIn(); }
/*********************************/
$('#employer').change(function () {
if ($(this).val() == "Other") {
$('tr#other-employer').fadeIn();
} else {
$('tr#other-employer').hide();
}
});
});
you can also set the select box default option from jquery using
$("select#employer").val("Other");
I'm not sure I totally understand the question, but if you're looking for the same functionality this code provides, but without the action being a requirement, then just remove the .change() function, and swap out the this for the id:
$(document).ready(function () {
$('tr#other-employer').hide();
if ($('#employer').val() == "Other") {
$('#other-employer').fadeIn();
}
});
Edit:
The above should work, given the following HTML (I've removed the table code from both to simplify the explanation):
<form>
<select id="#employer">
<option value="Foo">Foo</option>
<option value="Other" selected="selected">Other</option>
</select>
<select id="#other-employer">
<option value="Foo">Bar</option>
</select>
</form>
Given the above code the #other-employer dropdown will display only if the 'Other' option is preselected on load.
Related
I cannot seem to locate the flaw in my code. I am using select2 for my select list and I have a button to the right that when clicked, performs the following script:
<script type="text/javascript">
function clearBiller() {
$('#bill_to').val('').trigger('change');
}
</script>
But when clicked, I receive the TypeError: $(...).val(...) is null error which references this script:
<script>
$(document).ready(function(){
$('#bill_to').on('change', function() {
if ($(this).val() == '')
{
$("#biller").show();
}
else
{
$("#biller").hide();
}
});
});
</script>
This issue is somewhere in this second function, I'm just not sure how to pin it down. At the moment this is the html in that part of the form:
<select id="bill_to" name="bill_to" class="js-example-basic-single form-control">
#if($shipment->bill_to)
<option value="{{$shipment->bill_to}}" selected>3</option>
#endif
#foreach($cCustomers as $customer)
<option value="{{$customer->id}}">{{$customer->customer_name}}</option>
#endforeach
</select>
<img src="/images/clear.png" height="15px" width="15px" style="margin-left: 5px;" onclick="clearBiller()">
<div id="existing_biller_details" class="hidden" name="existing_biller_details" style="margin-top:10px;">
</div>
Can anyone spot anything?
Update
Based on the suggestion below that worked the best in my case, my script now looks like this:
$(document).ready(function() {
if ($('.js-example-basic-single').val() == "") {
$('#biller').addClass('hidden');
$('#existing_biller_details').removeClass('hidden');
}
var $eventSelect = $("#bill_to");
$eventSelect.select2();
$eventSelect.on("select2:select", function (e) {
if ($eventSelect.select2().val() == '')
{
$('#biller').removeClass('hidden');
$('#existing_biller_details').addClass('hidden');
alert('cleared');
}
else
{
$('#biller').addClass('hidden');
$('#existing_biller_details').removeClass('hidden');
alert('not cleared');
}
});
});
The alerts above are only there to guide me in what isn't working. At the moment, I load up the page I have set the div with the id of "existing_biller_details" to already be hidden, but if a value is selected in the select2, the "hidden" class is removed.
My problem at the moment is that using the above code, only the "else" works completely. If I go through the initial "if" statement, it will only conduct $('#biller').removeClass('hidden') and then it can't go any further. I don't see any errors in the console but no alert comes up and the command $('#existing_biller_details').addClass('hidden') doesn't work either.
May be this help you
var $eventSelect = $("#bill_to");
$eventSelect.select2();
$eventSelect.on("select2:select", function (e) {
if ($eventSelect.select2().val() == '')
{
$("#biller").show();
}
else
{
$("#biller").hide();
}
});
You should trigger the change event directly on #bill_to
$('#bill_to').val('');
$('#bill_to').trigger('change');
But you should check Select2 docs as your main select gets hidden when Select2 is initialized and Select2 has its own set of events for change and such.
I have a combo box of which the HTML looks like this:
<select id="myCombo">
<option value=""></option> <!-- Not shown in jQuery UI Combobox because empty value -->
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
I've attached the jQuery UI Combobox to I as such:
$("#myCombo").combobox({
select: function () {
if ($("#myCombo").val() == "") {
//DO SOMETHING
}
else {
//DO SOMETHING ELSE
}
}
});
When I select an option by either typing and/or selecting an option, the "DO SOMETHING ELSE" part is triggered like it should, so no issue there.
However, when I clear the selection (this selects the first option of my original combo) by deleting the text or clicking the "x", nothing get's triggered, so I can't execute the "DO SOMETHING" part of my function.
How can I trigger this part? Is there maybe another event that is triggered when clearing a selection?
I have searched and found lots of topic on selecting an item, but none on clearing/deselecting something(that were answered at least).
This can be accomplished with select2.
$("#myCombo").select2({
placeholder: "Select report type",
allowClear: true,
});
$("#myCombo")
.on("select2-selecting", function(e) {
log("selecting val=" + e.val + " choice=" + JSON.stringify(e.choice));
})
.on("select2-removed", function(e) {
log("removed");
})
After looking further into it I've found a way to trigger an event when clearing the text.
For this I had to edit the original custom.combobox widget JS, provided by the example on the jQuery UI site
In this js look for the _removeIfInvalid function and edit it like so
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
//**ADD this piece of code**
this._trigger("change", event, {
item: null
});
return;
}
// Remove invalid value
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.data("ui-autocomplete").term = "";
//**ADD this piece of code**
this._trigger("change", event, {
item: null
});
}
The added piece of code (I know it's added 2 times, but the code would otherwise jump out of the function before it was ran), will add a change event to the combobox that can be used in your own script. This change event, I can use to run any code I want when the selection is cleared.
$("#myCombo").combobox({
select: function () {
//DO SOMETHING ON SELECT
//IMPORTANT: The other function can't be triggered before the combobox loses focus!!
$(".custom-combobox-input").blur();
},
change:function () {
//DO SOMETHING ON CLEAR
}
});
The removeIfInvalid function is always called by default when an option can't be found and by adding an event to the control when this function is invoked is invoked, we finally have a place to execute our algorithmns.
Hopefully, more people are helped with this small fix.
Empty value cannot be selected in the browser. Hence select() is never called on empty contents.
If you try this, it becomes a bit more clear:
<select id="myCombo">
<option value=""></option> <!-- Not shown in jQuery UI Combobox because empty value -->
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4"></option>
<option value="5">Option 5</option>
</select>
I have slightly modified the javascript, note that I'm empty is never logged.
$("#myCombo").combobox({
select: function(event, ui) {
var idx = $("#myCombo").val();
var txt = $("#myCombo option:selected").text();
alert(idx);
if (idx === undefined) {
console.log("select: I'm empty");
} else {
console.log("select: " + idx + ": " + txt);
}
}
});
Interestingly, none of the other callbacks (search(), change(), response(), focus()) seems to function from autocomplete, so there is no way to detect a zero-ing out of the select.
I had spent what felt like a lot of time trying proposed solutions for this and those did not work for me, then I solved it myself.
Look for the _createAutocomplete function where you created your combobox instance.
Look for the chain of properties being set to this.input.
Then add
.on("focus",function(){
$(this).val('');
})
Anywhere in the chain.
So there are many examples on here of how to do this, but they are all (my opinion) cumbersome. You can clear the selection much easier by doing the following:
1) your _createAutocomplete: function() needs to have the following:
.attr( "title", "mytitle" )
Use any title that you want, or set another attribute (name, id etc)- I just happened to have a use for the title, so this worked for me.
2) whatever function you are running only needs the following to clear:
$("input[title='mytitle']").val('');
$("#combobox").val('');
(You have to clear both).
My need was a form with one of the fields being an autocomplete with minimum number of characters. There's an add entry button that submits, refreshes the entry list and resets the form line for additional entries. Much cleaner.
EDIT: Will be more specific with requirements see bottom for additions:
I am trying to hide an a link (button formatted as a href), however I am trying to do it based on text found with in an option drop down menu.
So for example
<form id="phonetypeform">
<select name="porting-p1" class="dropdown">
<option value="">Please select an option...</option>
<option value="1">I want to keep my current phone number</option>
<option value="2">I want to choose a new number</option>
</select>
</form>
Next Step
If the 'please select an option' is selected it hides the a link, if anything else is selected then it shows the link
here is the jquery I have which is not working
$(document).ready(function() {
$("a.nextbutton").hide()
$('.dropdown').change(function() {
if($('.dropdown option:contains'Please)') {
$('a.nextbutton',this).hide();
} else {
$("a.nextbutton")show();
}
});
});
EDIT starts here:
thanks to everyone that has given me some answers, but what I now have works, but its not ideal, and ideally would like to use the contains, simple reason is I have about 20 of these scripts I would have to create and target the value, ugly!
to show my exact requirement please see the fiddle, while this is working, as I said I have many of these scripts to put in place, ideally I would like to:
1. target the text 'select...'
2. Have it so that it stays hidden until all options no longer contain 'Select...' (the contains should take care of that right)
Here is a fiddle to make life easier for anyone that can help?
http://jsfiddle.net/p3ewE/
END EDIT
Try this instead:
$("a.nextbutton").hide();
$('.dropdown').change(function () {
if ($('.dropdown').val() == "") {
$('a.nextbutton', this).hide();
} else {
$("a.nextbutton").show();
}
});
jsFiddle example
You had a few syntax issues with missing periods and brackets.
Typo here
if($('.dropdown option:contains(Please)')
^ ^
:contains()
Use this code
DEMO
$('.dropdown').change(function () {
if (this.value == "") {
$('a.nextbutton').hide();
} else {
$("a.nextbutton").show();
}
}).change();
Here is the link http://jsfiddle.net/XXDwr/5/
have a look at it.
$(document).ready(function() {
$(".nextbutton").hide();
$('.dropdown').on('change',function() {
var h= $('.dropdown').val();
if(h=="")
{
$(".nextbutton").hide();
}
else{
$(".nextbutton").show();
}
});
});
I hope you wanted to achieve this.
$(document).ready(function() {
var btnNext = $("a.nextbutton").hide();
$('.dropdown').change(function() {
if(this.value){
btnNext.show();
} else {
btnNext.hide();
}
});
});
You had a typo right before "please".
You could/should save the button in a variable so you don't have to make that query every time.
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?
Try this:
http://jsfiddle.net/qk2Pc/
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");
});
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'));
});
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.
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)
}
}
});
Demo
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.
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>
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 :)
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;
}
});
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/
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>
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;
$('#my_select').bind('mousedown', function (event) {
event.preventDefault();
event.stopImmediatePropagation();
});
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());
});
});
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.
I've got a select box where the user selects which elements they want to see based on option 1, option 2 and option 3.
So what I'm trying to set up is have if option 1 is selected run one set of commands and if option 2 run another and so on.
I guess I just need to know how to set up the jQuery selector.
You didn't specify how the code was triggered, so here are two common ways:
$('#yourSelect').change(function() {
if ($(this).val() == 'something') {
// do this
}
if ($(this).val() == 'somethingelse') {
// do that
}
});
Note that while I used the onchange event for the select, an onclick for another element would look like this instead:
$('#somethingelse').click(function() {
if ($('#yourselect').val() == 'something') {
// do this
}
if ($('#yourselect').val() == 'somethingelse') {
// do that
}
});
<select onchange="if(this.value)window[this.value]();">
<option value="">select one...
<option value="runme1">run me 1
<option value="runme2">run me 2
</select>
<script>
function runme1() {
alert(1);
}
function runme2() {
alert(2);
}