PHP - How to submit a select menu without a button - javascript

Is it possible to auto submit a select menu when the selection changes without using a button to submit the form. I have four of these on my page and using a button for each uses up too much space. By Select Menu, I mean:
<select name="something" class="something" title="something something">
<option selected="selected">Option One</option>
<option >Option Two</option>
</select>
I would also like to add a confirm popup for the on change event. The following is what I use for buttons but it does not work for the select menu.
onclick="return confirm('do you haz teh codz?');"
Any link to articles tutorials or examples would be greatly appreciated!
Thanks

This is more appropriately tagged 'javascript' since it's javascript that you'll use to do it.
Add an 'onchange' event to the select. In the example below, 'form' should be substituted for your favourite method of targeting the form node.
<select name="something" class="something" title="something something" onchange="form.submit()">
<option selected="selected">Option One</option>
<option >Option Two</option>
</select>

You need a JavaScript solution, not a PHP solution. PHP can only handle form data after it's been sent to the server; i.e., when the form has been submitted.
You can use JavaScript to:
Add an event listener to the <select> to trigger when it changes (onchange).
When the <select> changes, get its current value.
Based on the value, redirect the user (change window.location) to the page you want them to go to.
Edit: I re-read your question and if you are just looking to submit the form when the user changes the <select>, then mwotton's answer is probably the way to go. (Of course, move the JavaScript away from the HTML; it doesn't belong there.)
For your confirmation, you can do something like this:
document.getElementById('my-select').onchange = function(){
return confirm('do you haz teh codz?');
});
(It's always a good idea to keep your JavaScript away from your HTML. So just give your <select> an ID like id="my-select" and you can access it from the JavaScript. You can also use a JavaScript library like jQuery to greatly ease your JavaScript programming.)

Well, you need to know the form name/id or something. Assuming <form id="selectform"> and <select id="selectelement">,
window.onload=function() {
document.getElementById('selectelement').change = function() {
if(confirm('do you haz teh codz?'))
document.getElementById('selectform').submit();
else
return false;
return true;
}
}
The return false/true will determine whether or not to revert the select back to the original option.
Here's a test: http://jsfiddle.net/yrqcj/2/

You can implement the onchange event for select object and inside the function make a reference to the form.submit();

Related

Is it possible to trigger JavaScript when a user selects the current option in an HTML select?

I know that you can use the onchange event on the select to trigger a JavaScript function, but what if they choose the option that is currently selected?
The reason for this is I want to have a drop down list of a bunch of websites. This is used as a sort of jumppage, if you will. When the user selects a site the selected site opens in a new window. Now if they close the new tab/window the select is on the last option they selected. If the user wants to go to the same website again the onchange event does not fire.
I know that you can change the select option back to the default option with a null value like this:
html
<select onChange="jsFunction(this.value)" id="selectOpt">
<option value="">1</option>
<option value="websiteURL2">2</option>
<option value="websiteURL3">3</option>
</select>
javascript
function jsFunction(opt){
window.location = opt;
document.getElementById("selectOpt").options[0].selected = true;
}
http://jsfiddle.net/XqLmY/1/
But I was wondering if it could be done without that.
Can I trigger an event using a HTML select without changing its value?
What about using onClick instead
Look here http://jsfiddle.net/9X4Ks/1/
<select onclick="clickFunction(this)" id="selectOpt">
<option value="websiteURL1">1</option>
<option value="websiteURL2">2</option>
<option value="websiteURL3">3</option>
</select>
function clickFunction(o){
alert(o.value)
}
It fires even when user clicks the selected option second time.
Unfortunately it works only in chrome and opera.
Does not work in firefox
Not really an answer, but I just ended up using this method because it was easy and didn't have other dependencies.
function jsFunction(opt){
window.location = opt;
document.getElementById("selectOpt").options[0].selected = true;
}

populate and disable text field depending on dropdown

Unfortunately i'm not too familiar with javascript/jQuery. I have a form with a dropdown. What i need to do is to populate a text field depending on the selection of the dropdown. First voice of the dropdown is "other" so the text field must be writable, then from the second i want to assign a value automatically and disable the text field.
The value of the dropdown will be saved in the db so it must remains the name of the option.
I found several solutions with google but none of them fits my needs...hope someone could help me.
To create the functionality you're looking for, there are a few basic things you'll need to learn.
jQuery Selectors
First, if you aren't already familiar with jQuery's selector syntax, learn about it here.
The .change() Event
Next, you'll need to know how to bind to the dropdown menu's .change event. One way to do this is $('#dropdownId').change(function() { ... });, which is just a shortcut for $('#dropdownId').on('change', function() { ... }); . Within the callback functions, you can access the dropdown element with this and as a result, the jQuery object with $(this).
We can then grab the dropdown's value with $(this).val() and use some basic logic to enable/disable the textbox and set its value.
Enabling/Disabling the textbox
In order to enable/disable the textbox, you can use: $('#txt').removeAttr('disabled');and$('#txt').attr('disabled', 'true');` respectively.
Example
I've combined all of these for you in an example fiddle to show you how you can put these together in this jsFiddle. Let me know if you have any questions about how it works :)
Here is the fiddle for you...
http://jsfiddle.net/G3V3v
HTML:
<select id="ddl">
<option value="0">[ Other ]</option>
<option value="1">First</option>
<option value="2">Second</option>
</select>
<input id="txt" />
jQuery:
$('#ddl').change(function() {
if ($(this).val() == 0) {
$('#txt').val('').removeAttr("disabled").focus();
} else {
$('#txt').val($(this).children('option:selected').text());
$('#txt').attr("disabled", "disabled");
}
});

how to disable an option with msdropdown plugin

Is it possible to disable an option after creating a msDropdown plugin?
I explain my problem better.
I want to put html into each option with icons, text and some other stuff, so first i create an empty select then I add each option with the add function:
dropdown.add({text:$price.html(), value:'normal', className:'normal'});
The problem is that if a certain condition happen I have to disable one option, but there are no way to set an option disabled by using plugin settings.
There is the possibility to make an option disabled only by setting the related parameter disabled=disabled into the select before to call the msDropdown function, but I can't use this solution since I have to put dinamically html into option text.
Is there another way to do it?
Thank you for your help.
I found a solution.
I create my select empty and I fill each option with add function as before, but when that condition happen just do this:
var dropdown = $('select[name="priceType"]').msDropdown().data("dd");
if(credits_error) { // option must be disabled
dropdown.destroy(); // Make it a simple select
$('select[name="priceType"] option').attr('disabled', 'disabled');
dropdown = $('select[name="priceType"]').msDropdown().data("dd");
}
This way first I make it a simple select by calling destroy function, then I set properly the disabled attribute and I create a new msDropdown select.
It works for me, I tested it on IE, FF and Chrome
Yes, it is possibile. It can be done by using the disabled property of the option tag:
<select id="payments" name="payments" style="width:250px;">
<option value="" data-description="Choos your payment gateway">Payment Gateway</option>
<option value="amex" data-image="http://www.marghoobsuleman.com/mywork/jcomponents/image-dropdown/samples/images/msdropdown/icons/Amex-56.png" data-description="My life. My card...">Amex</option>
<option value="Discover" data-image="http://www.marghoobsuleman.com/mywork/jcomponents/image-dropdown/samples/images/msdropdown/icons/Discover-56.png" data-description="It pays to Discover...">Discover</option>
<option value="Mastercard" data-image="http://www.marghoobsuleman.com/mywork/jcomponents/image-dropdown/samples/images/msdropdown/icons/Mastercard-56.png" data-title="For everything else..." data-description="For everything else...">Mastercard</option>
<option value="cash" data-image="http://www.marghoobsuleman.com/mywork/jcomponents/image-dropdown/samples/images/msdropdown/icons/Cash-56.png" data-description="Sorry not available..." disabled="true">Cash on devlivery</option>
<option value="Visa" data-image="http://www.marghoobsuleman.com/mywork/jcomponents/image-dropdown/samples/images/msdropdown/icons/Visa-56.png" data-description="All you need...">Visa</option>
<option value="Paypal" data-image="http://www.marghoobsuleman.com/mywork/jcomponents/image-dropdown/samples/images/msdropdown/icons/Paypal-56.png" data-description="Pay and get paid...">Paypal</option>
</select>
The option 'cash' will be disabled.
Here is a working fiddle: http://jsfiddle.net/NKQRj/1/
EDIT
In this second example data are loaded from JSON data using:
$("#payments").msDropDown({byJson:{data:jsonData, name:'payments2'}}).data("dd");
to fill the elements.
You can define your options as disabled in your JSON data using disabled: true property:
{image:'http://www.marghoobsuleman.com/mywork/jcomponents/image-dropdown/samples/images/msdropdown/icons/Cash-56.png', description:'Sorry not available...', value:'cash', text:'Cash on devlivery', disabled:true},
here is a working fiddle: http://jsfiddle.net/NKQRj/3/

Change Form Option through a function with JS or jQuery?

I'm working on an form based website.
<select name="foo" id="foo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I need to allow options to be saved by users based on previous choices.
My first attempt was to add the following HTML(with php) to the option of the users choice.
selected="selected"
However the site has some functions which change the rest of the form based on the user's choice.
$('#foo').change(function(event) {
....
}
Is it possible to have the option changed via a function(using jQuery or JS)? Thus triggering the function waiting for #foo to be changed?
You could use the .val() method:
$('#foo').val('2');
which will preselct the element with value="2" and also trigger the change event handler. Or with pure javascript:
document.getElementById('foo').value = '2';
And to trigger the change event manually you could do this:
$('#foo').change();
Setting the value will NOT trigger the change event. You can just programatically trigger it by doing the following.
$('#foo').trigger('change'); // this should run the change code.

HTML form readonly SELECT tag/input

According to HTML specs, the select tag in HTML doesn't have a readonly attribute, only a disabled attribute. So if you want to keep the user from changing the dropdown, you have to use disabled.
The only problem is that disabled HTML form inputs don't get included in the POST / GET data.
What's the best way to emulate the readonly attribute for a select tag, and still get the POST data?
You should keep the select element disabled but also add another hidden input with the same name and value.
If you reenable your SELECT, you should copy its value to the hidden input in an onchange event and disable (or remove) the hidden input.
Here is a demo:
$('#mainform').submit(function() {
$('#formdata_container').show();
$('#formdata').html($(this).serialize());
return false;
});
$('#enableselect').click(function() {
$('#mainform input[name=animal]')
.attr("disabled", true);
$('#animal-select')
.attr('disabled', false)
.attr('name', 'animal');
$('#enableselect').hide();
return false;
});
#formdata_container {
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form id="mainform">
<select id="animal-select" disabled="true">
<option value="cat" selected>Cat</option>
<option value="dog">Dog</option>
<option value="hamster">Hamster</option>
</select>
<input type="hidden" name="animal" value="cat"/>
<button id="enableselect">Enable</button>
<select name="color">
<option value="blue" selected>Blue</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
<input type="submit"/>
</form>
</div>
<div id="formdata_container" style="display:none">
<div>Submitted data:</div>
<div id="formdata">
</div>
</div>
We could also disable all except the selected option.
This way the dropdown still works (and submits its value) but the user can not select another value.
Demo
<select>
<option disabled>1</option>
<option selected>2</option>
<option disabled>3</option>
</select>
You can re-enable the select object on submit.
EDIT: i.e., normally disabling the select tag (with the disabled attribute) and then re-enabling it automatically just before submiting the form:
Example with jQuery:
To disable it:
$('#yourSelect').prop('disabled', true);
To re-enable it before submission so that GET / POST data is included:
$('#yourForm').on('submit', function() {
$('#yourSelect').prop('disabled', false);
});
In addition, you could re-enable every disabled input or select:
$('#yourForm').on('submit', function() {
$('input, select').prop('disabled', false);
});
another way of doing a readOnly attribute to a select element is by using css
you could do like :
$('#selection').css('pointer-events','none');
DEMO
Simple jQuery solution
Use this if your selects have the readonly class
jQuery('select.readonly option:not(:selected)').attr('disabled',true);
Or this if your selects have the readonly="readonly" attribute
$('select[readonly="readonly"] option:not(:selected)').attr('disabled',true);
<select id="countries" onfocus="this.defaultIndex=this.selectedIndex;" onchange="this.selectedIndex=this.defaultIndex;">
<option value="1">Country1</option>
<option value="2">Country2</option>
<option value="3">Country3</option>
<option value="4">Country4</option>
<option value="5">Country5</option>
<option value="6">Country6</option>
<option value="7" selected="selected">Country7</option>
<option value="8">Country8</option>
<option value="9">Country9</option>
</select>
Tested and working in IE 6, 7 & 8b2, Firefox 2 & 3, Opera 9.62, Safari 3.2.1 for Windows and Google Chrome.
I know that it is far too late, but it can be done with simple CSS:
select[readonly] option, select[readonly] optgroup {
display: none;
}
The style hides all the options and the groups when the select is in readonly state, so the user can not change his selection.
No JavaScript hacks are needed.
Simple CSS solution:
select[readonly]{
background: #eee;
cursor:no-drop;
}
select[readonly] option{
display:none;
}
This results in Select to be gray with nice "disable" cursor on hover
and on select the list of options is "empty" so you can not change its value.
Easier still:
add the style attribute to your select tag:
style="pointer-events: none;"
Yet another more contemporary option (no pun intended) is to disable all the options of the select element other then the selected one.
note however that this is an HTML 4.0 feature
and ie 6,7,8 beta 1 seem to not respect this.
http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/OptionDisabledSupport.html
This is the best solution I have found:
$("#YourSELECTIdHere option:not(:selected)").prop("disabled", true);
The code above disables all other options not selected while keeping the selected option enabled. Doing so the selected option will make it into the post-back data.
A bit late to the party. But this seems to work flawlessly for me
select[readonly] {
pointer-events:none;
}
[SIMPLEST SOLUTION]
Since the OP specifically asked that he does not want to disable the select element, here is what i use to make a select readonly
In html
<select style="pointer-events: none;" onclick="return false;" onkeydown="return false;" ></select>
THAT's IT
Explanation
setting pointer-events to none disables the editing of the "select-element" with mouse/cursor events
setting the onclick & onkeydown functions to return false disables the editing of the "select-element" with keyboard
This way you don't have to create any extra element, or disable/re-enable the element with javascript or messing with form-submission logic, or use any third party library.
Plus you can easily add css-styling like setting backgrouns-color to grey or text color to grey to imply that element is readonly. I haven't added that to code, since that is pretty specific to your site-theme
Or if you want to do it via javascript
let isReadOnly = true ;
selectElement.onclick = function () {
return !isReadOnly ;
};
selectElement.onkeydown =function(){
return !isReadOnly ;
} ;
selectElement.style.pointerEvents = isReadOnly ? "none" : "all" ;
Set the select disabled when you plan for it to be read-only and then remove the disabled attribute just before submitting the form.
// global variable to store original event/handler for save button
var form_save_button_func = null;
// function to get jQuery object for save button
function get_form_button_by_id(button_id) {
return jQuery("input[type=button]#"+button_id);
}
// alter value of disabled element
function set_disabled_elem_value(elem_id, value) {
jQuery("#"+elem_id).removeAttr("disabled");
jQuery("#"+elem_id).val(value);
jQuery("#"+elem_id).attr('disabled','disabled');
}
function set_form_bottom_button_save_custom_code_generic(msg) {
// save original event/handler that was either declared
// through javascript or html onclick attribute
// in a global variable
form_save_button_func = get_form_button_by_id('BtnSave').prop('onclick'); // jQuery 1.6
//form_save_button_func = get_form_button_by_id('BtnSave').prop('onclick'); // jQuery 1.7
// unbind original event/handler (can use any of following statements below)
get_form_button_by_value('BtnSave').unbind('click');
get_form_button_by_value('BtnSave').removeAttr('onclick');
// alternate save code which also calls original event/handler stored in global variable
get_form_button_by_value('BtnSave').click(function(event){
event.preventDefault();
var confirm_result = confirm(msg);
if (confirm_result) {
if (jQuery("form.anyForm").find('input[type=text], textarea, select').filter(".disabled-form-elem").length > 0) {
jQuery("form.anyForm").find('input[type=text], textarea, select').filter(".disabled-form-elem").removeAttr("disabled");
}
// disallow further editing of fields once save operation is underway
// by making them readonly
// you can also disallow form editing by showing a large transparent
// div over form such as loading animation with "Saving" message text
jQuery("form.anyForm").find('input[type=text], textarea, select').attr('ReadOnly','True');
// now execute original event/handler
form_save_button_func();
}
});
}
$(document).ready(function() {
// if you want to define save button code in javascript then define it now
// code below for record update
set_form_bottom_button_save_custom_code_generic("Do you really want to update this record?");
// code below for new record
//set_form_bottom_button_save_custom_code_generic("Do you really want to create this new record?");
// start disabling elements on form load by also adding a class to identify disabled elements
jQuery("input[type=text]#phone").addClass('disabled-form-elem').attr('disabled','disabled');
jQuery("input[type=text]#fax").addClass('disabled-form-elem').attr('disabled','disabled');
jQuery("select#country").addClass('disabled-form-elem').attr('disabled','disabled');
jQuery("textarea#address").addClass('disabled-form-elem').attr('disabled','disabled');
set_disabled_elem_value('phone', '123121231');
set_disabled_elem_value('fax', '123123123');
set_disabled_elem_value('country', 'Pakistan');
set_disabled_elem_value('address', 'address');
}); // end of $(document).ready function
In addition to disabling the options that should not be selectable i wanted to actually make them dissapear from the list, but still be able to enable them should i need to later:
$("select[readonly]").find("option:not(:selected)").hide().attr("disabled",true);
This finds all select elements with a readonly attribute, then finds all options inside those selects that are not selected, then it hides them and disables them.
It is important to separate the jquery query in 2 for performance reasons, because jquery reads them from right to left, the code:
$("select[readonly] option:not(:selected)")
will first find all unselected options in the document and then filter those that are inside selects with a readonly attribute.
This is the simplest and best solution.
You will set a readolny attr on your select, or anyother attr like data-readonly, and do the following
$("select[readonly]").live("focus mousedown mouseup click",function(e){
e.preventDefault();
e.stopPropagation();
});
Solution with tabindex. Works with select but also text inputs.
Simply use a .disabled class.
CSS:
.disabled {
pointer-events:none; /* No cursor */
background-color: #eee; /* Gray background */
}
JS:
$(".disabled").attr("tabindex", "-1");
HTML:
<select class="disabled">
<option value="0">0</option>
</select>
<input type="text" class="disabled" />
Edit: With Internet Explorer, you also need this JS:
$(document).on("mousedown", ".disabled", function (e) {
e.preventDefault();
});
If you disable a form field, this won't be sent when form is submitted.
So if you need a readonly that works like disabled but sending values do this :
After any change in readonly properties of an element.
$('select.readonly option:not(:selected)').attr('disabled',true);
$('select:not([readonly]) option').removeAttr('disabled');
One simple server-side approach is to remove all the options except the one that you want to be selected. Thus, in Zend Framework 1.12, if $element is a Zend_Form_Element_Select:
$value = $element->getValue();
$options = $element->getAttrib('options');
$sole_option = array($value => $options[$value]);
$element->setAttrib('options', $sole_option);
Following on from Grant Wagners suggestion; here is a jQuery snippet that does it with handler functions instead of direct onXXX attributes:
var readonlySelect = function(selector, makeReadonly) {
$(selector).filter("select").each(function(i){
var select = $(this);
//remove any existing readonly handler
if(this.readonlyFn) select.unbind("change", this.readonlyFn);
if(this.readonlyIndex) this.readonlyIndex = null;
if(makeReadonly) {
this.readonlyIndex = this.selectedIndex;
this.readonlyFn = function(){
this.selectedIndex = this.readonlyIndex;
};
select.bind("change", this.readonlyFn);
}
});
};
What I found works great, with plain javascript (ie: no JQuery library required), is to change the innerHTML of the <select> tag to the desired single remaining value.
Before:
<select name='day' id='day'>
<option>SUN</option>
<option>MON</option>
<option>TUE</option>
<option>WED</option>
<option>THU</option>
<option>FRI</option>
<option>SAT</option>
</select>
Sample Javascript:
document.getElementById('day').innerHTML = '<option>FRI</option>';
After:
<select name='day' id='day'>
<option>FRI</option>
</select>
This way, no visiual effect change, and this will POST/GET within the <FORM>.
input being your <select> element:
input.querySelectorAll(':not([selected])').forEach(option => {
option.disabled = true
})
This will keep the select in the data (as it's not disabled) and only the option that are not selected are disabled, therefore not selectable.
The result is a readable select that cannot be changed (=> read only).
Rather than the select itself, you could disable all of the options except for the currently selected option. This gives the appearance of a working drop-down, but only the option you want passed in is a valid selection.
If the select dropdown is read-only since birth and does not need to change at all, perhaps you should use another control instead? Like a simple <div> (plus hidden form field) or an <input type="text">?
Added: If the dropdown is not read-only all the time and JavaScript is used to enable/disable it, then this is still a solution - just modify the DOM on-the-fly.
I resolved it with jquery:
$("select.myselect").bind("focus", function(){
if($(this).hasClass('readonly'))
{
$(this).blur();
return;
}
});
html solution:
<select onfocus="this.blur();">
javascript ones:
selectElement.addEventListener("focus", selectElement.blur, true);
selectElement.attachEvent("focus", selectElement.blur); //thanks, IE
to remove:
selectElement.removeEventListener("focus", selectElement.blur, true);
selectElement.detachEvent("focus", selectElement.blur); //thanks, IE
edit: added remove methods
In IE I was able to defeat the onfocus=>onblur approach by double-clicking.
But remembering the value and then restoring it in the onchange event seems to handle that issue.
<select onfocus="this.oldvalue=this.value;this.blur();" onchange="this.value=this.oldvalue;">
....
</select>
You can do similar without expando properties by using a javascript variable.
If you are using jquery validate, you can do the following below, I used the disabled attribute without a problem:
$(function(){
$('#myform').validate({
submitHandler:function(form){
$('select').removeAttr('disabled');
form.submit();
}
});
});
<select id="case_reason" name="case_reason" disabled="disabled">
disabled="disabled" ->will get your value from database dan show it in the form.
readonly="readonly" ->you can change your value in selectbox, but your value couldn't save in your database.
What's the best way to emulate the readonly attribute for a select
tag, and still get the POST data?
Just make it an input/text field and add the 'readonly' attribute to it. If the select is effectively 'disabled', then you can't change the value anyway, so you don't need the select tag, and you can simply display the "selected" value as a readonly text input. For most UI purposes I think this should suffice.

Categories