Changing the placeholder text based on the users choice - javascript

jQuery is permitted, but an HTML-only solution is preferred.
I have a select box with a couple of options. When the user selects 'Name', I want the placeholder text 'Enter your name' to appear in the adjacent text-box.
Likewise for 'ID' -> 'Enter your ID'.
See http://jsfiddle.net/Uy9Y3/
<select>
<option value="-1">Select One</option>
<option value="0">Name</option>
<option value="1">ID</option>
</select>
<input type="text">
This is a requirement by a client that I haven't been able to figure out.
If it helps, the website is using the Spring framework.

Since you need to update the placeholder when the select updates, you'll need to use javascript to do it.
You could set the placeholder you would like to display as an attribute on each option element using the HTML5 data- style attributes. Then use jQuery to attach a change event listener which will update the placeholder attribute of the input box.
Note that the placeholder attribute doesn't have any effect in older versions of IE, so if you need to support old IE you'll need to polyfill that functionality with another library.
Working Demo
HTML
<select id="mySelect">
<option data-placeholder="" value="-1">Select One</option>
<option data-placeholder="Enter your name" value="0">Name</option>
<option data-placeholder="Enter your ID" value="1">ID</option>
</select>
<input id="myInput" type="text">
jQuery
$('#mySelect').on('change', function() {
var placeholder = $(this).find(':selected').data('placeholder');
$('#myInput').attr('placeholder', placeholder);
});

It requires JavaScript. You can do it inline -- if that's what you mean by HTML-only.
<select onchange="document.querySelector('input').setAttribute('placeholder', 'Enter your ' + this.options[this.selectedIndex].text);"></select>

See the following jsfiddle for an example of how to do this:
http://jsfiddle.net/sW6QP/
Note that this is using jQuery ONLY because jsfiddle seems to be unable to find the function placed into the onChange event.
If you want to do it without jQuery, change the select line to this:
<select id="selectionType" onChange="setPlaceholder();">
And instead of $("#selectionType").on("change",function() {, do this instead:
function setPlaceholder() {
(make sure to change the }); to } as well)

Related

Reset text field on Mouse press / Input - jQuery UI Autocomplete

Simple JS fiddle containing my code in working state
I have a jQuery UI Autocomplete field, with a Dropdown button attached. It works floorlessly, however - its kinda annoying you have to manually delete the words inside the field for a search.
I am unsure if jQuery UI has a feature for it, unless i'd love to know.
I've tried to use onClick functions with JS, however since my field is not exactly an "form field" I've got kinda lost here.
My goal is to: reset the text field when a user presses it.It has prewritten text in it "Please select (Or Type)"
my cshtml file looks as following
cshtml
And it looks like this on the browser browser
Code for Image 1:
<select asp-for="Dinosaur" class="combobox" id="dinoType" asp-items="Html.GetEnumSelectList<Dinosaurs>()">
<option selected="selected" type="text" onclick="resetText()" value="0">Please select (Or Type)</option>
</select>
<span asp-validation-for="Dinosaur" class="text-dark" />
As you can see it has the text in, which i have to CTRL + A, DELETE before i can search in my field.
A function to clear this text when a user presses it will easen the pressure.
I might just be stupid to see the simple solution, i just feel like I've tried some of the things that I'd believe would work. (As the onclick="ResetText()" with a JS code attached to it)
When I click on drop down this is what showing.
Best Regards,
You don't want to wire an onclick listener on your option element, you want an onchange event listener on your select element. onclick is not supported on option elements.
use onchange instead of using onclick and this action should be on the select tag. not on the options. Try this example.
$('select').on('change', function() {
if (this.value === 'disabled') {
this.value = '';
}
console.log(this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select asp-for="Dinosaur" class="combobox" id="dinoType" asp-items="Html.GetEnumSelectList<Dinosaurs>()">
<option selected="selected" type="text" value="disabled">Please select (Or Type)</option>
<option type="text" value="One">One</option>
<option type="text" value="two">two</option>
</select>
<span asp-validation-for="Dinosaur" class="text-dark" />

Why does a jQuery disabled element look touchable in jQuery mobile?

I want to disable/enable a html select element programatically. My project is using jQuery mobile 1.4.5 and jQuery 2.1.4.
To disable the element in jQuery I do:
$('#filter_refn').prop('disabled', true);
Results after rendering in:
<select name="ref_id" id="filter_refn" data-mini="true" disabled="">
<option value="" selected="">Referenznummer auswählen</option>
</select>
This "somehow works. As the user can not select anything, however the box is still active and not disabled as it would be by doing it directly in html.
I noticed that the disabled property by jQuery does not contain "true"
example in jQuery mobile:
native html:
How can I disable the element in a similar way then in HTML?
You need use the functions provided by the jquery mobile API to change the state of their components.
Selectmenu Widget: disable():
$( ".selector" ).selectmenu( "disable" );
The styling of those elements is done by css rules and those utilize the [disabled] selector.
But if you do $('#filter_refn').prop('disabled', true); on a none user input element, then only the property disabled changes, but not the attribute. For elements like select, button, input, ... the $('#filter_refn').prop('disabled', true); will change both property and attribute.
Writing $('#filter_refn').prop('disabled', true).attr('disabled', true); would most certainly also change the visual appearance, but you still should use the functionality provided by the API.
How is your HTML doctype declared? In XHTML the "disabled" attribute must have a value, while in HTML it doesn't need to have a value. Also it may have something to do with your browser, so it'd be more helpful if you can provide more info on the DOCTYPE declaration and the browser you are using to test the page.
For my latest version desktop Chrome browser
<select name="ref_id" id="filter_refn" data-mini="true" disabled>
<select name="ref_id" id="filter_refn" data-mini="true" disabled="">
<select name="ref_id" id="filter_refn" data-mini="true" disabled="disabled">
all produce the same result when the doctype is html5, which should be the correct case.
However if your browser or doctype require the "disabled" attribute to have a value, you may use the jQuery "attr" function, that somehow
$('#filter_refn').prop('disabled', true);
produces
<select name="ref_id" id="filter_refn" data-mini="true" disabled>
while
$('#filter_refn').attr('disabled', true);
produces
<select name="ref_id" id="filter_refn" data-mini="true" disabled="disabled">
and see if that does what you want?

HTML make <option> invalid

I have the following piece of code in a contact form for a site I am designing:
<select id="Category" name="Category">
<option value="0" selected="selected" disabled>Category</option>
<option value="1">General Info</option>
<option value="2">Booking</option>
<option value="3">Auditions</option>
</select>
I would like set the menu such that the user cannot leave category as the selected option. Is there any way to do this with HTML? If not, how would I do it with JavaScript?
Thank you
According to the HTML5 spec,
Constraint validation: If the element has its required attribute specified, and either none of the option elements in
the select element's list of options have their
selectedness set to true, or the only option element in
the select element's list of options with its
selectedness set to true is the placeholder label option,
then the element is suffering from being missing.
If a select element has a required attribute
specified, does not have a multiple attribute specified, and
has a display size of 1; and if the value of the first
option element in the select element's list of
options (if any) is the empty string, and that option
element's parent node is the select element (and not an
optgroup element), then that option is the select
element's placeholder label option.
Therefore, you can use
<select id="Category" name="Category" required>
<option value="" selected disabled>Category</option>
<option value="1">General Info</option>
<option value="2">Booking</option>
<option value="3">Auditions</option>
</select>
When the user click on any option, he can´t return the first one back. But he can submit form without change, then you need to validate via JS.
It's quite simple,
function validate() {
var select = document.getElementById('Category');
return !select.value == 0;
}
And the form in HTML:
<form onsubmit="return validate()">...</form>
Will disabling select work for you?
<select id="Category" name="Category" disabled>
<option value="0" selected="selected">Category</option>
...
</select>
Or maybe disabling all but selected option will work for you (as shown here: https://stackoverflow.com/a/23428851/882073)
Ideally, you would simply remove the selected attribute from disabled options on the server side when generating the HTML document to begin with.
Otherwise, if you are using JQuery, this can be done fairly easily with:
$('#Category').find('option:not([disabled])').first().prop('selected', true);
Add this to your ondomready event handler. This will force the first non-disabled option to be selected for this select element regardless of its options' selected attributes. The disadvantage of this method is that it will prevent the selected attribute from being able to be used at all with this select element.
On the other hand, if you are trying to create category headers within a select element, you should consider using an optgroup element instead, since that is the correct semantic markup for this:
<select id="Category" name="Category">
<optgroup label="Category">
<option value="1">General Info</option>
<option value="2">Booking</option>
<option value="3">Auditions</option>
</optgroup>
</select>

Modification to jQuery script to let me choose which is the default value of the select list on page entrance

I make use of Mobiscroll jQuery script for a prettier input by the users. On page load, the first option of the select list is shown as selected. What should I add to the existing code that on page entrance, the (for example) 3rd value is shown as the default?
I tried selecte="selected" but it does not work.
this is the jQuery script
$(function(){
$('#city').scroller({
preset: 'select',
theme: 'android-ics',
display: 'inline',
mode: 'scroller',
});
});
and here is the options of the select box
<select id="city" class="cities" data-role="none" name="City">
<option value="">All</option>
<option value="1">Atlanta</option>
<option value="2">Berlin</option>
<option value="3">Boston</option>
</select>
You can easily set the value from jQuery by doing this:
var defaultValue = 3;
$("#city").val(defaultValue);​
"3" here represents Boston from your drop down list, here's a fiddle for proof:
http://jsfiddle.net/6mj8n/5/
Using $('#city').val('3'); will put The third option 'Boston' as selected for example
In this case, I think the vanilla DOM method is what I'd go with:
$('#city')[0].options.selectedIndex = 3;
It should be mentioned that this and other solutions should be placed before you initialize mobiscroll. Working demo with mobiscroll: http://jsfiddle.net/DCaHK/1/
...On further thought, your first suggestion of adding selected to the option should have worked. Updated my demo to do exactly that. Autocomplete could prevent this from working properly in some browsers, so it's possible your issue is simply that you need to turn autocomplete off:
<form autocomplete="off">
<select id="city" class="cities" data-role="none" name="City">
<option value="">All</option>
<option value="1">Atlanta</option>
<option value="2" selected>Berlin</option>
<option value="3">Boston</option>
</select>
</form>

How to ensure a <select> form field is submitted when it is disabled?

I have a select form field that I want to mark as "readonly", as in the user cannot modify the value, but the value is still submitted with the form. Using the disabled attribute prevents the user from changing the value, but does not submit the value with the form.
The readonly attribute is only available for input and textarea fields, but that's basically what I want. Is there any way to get that working?
Two possibilities I'm considering include:
Instead of disabling the select, disable all of the options and use CSS to gray out the select so it looks like its disabled.
Add a click event handler to the submit button so that it enables all of the disabled dropdown menus before submitting the form.
Disable the fields and then enable them before the form is submitted:
jQuery code:
jQuery(function ($) {
$('form').bind('submit', function () {
$(this).find(':input').prop('disabled', false);
});
});
<select disabled="disabled">
....
</select>
<input type="hidden" name="select_name" value="selected value" />
Where select_name is the name that you would normally give the <select>.
Another option.
<select name="myselect" disabled="disabled">
<option value="myselectedvalue" selected="selected">My Value</option>
....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />
Now with this one, I have noticed that depending on what webserver you are using, you may have to put the hidden input either before, or after the <select>.
If my memory serves me correctly, with IIS, you put it before, with Apache you put it after. As always, testing is key.
I`ve been looking for a solution for this, and since i didnt find a solution in this thread i did my own.
// With jQuery
$('#selectbox').focus(function(e) {
$(this).blur();
});
Simple, you just blur the field when you focus on it, something like disabling it, but you actually send its data.
I faced a slightly different scenario, in which I only wanted to not allow the user to change the selected value based on an earlier selectbox. What I ended up doing was just disabling all the other non-selected options in the selectbox using
$('#toSelect').find(':not(:selected)').prop('disabled',true);
it dows not work with the :input selector for select fields, use this:
jQuery(function() {
jQuery('form').bind('submit', function() {
jQuery(this).find(':disabled').removeAttr('disabled');
});
});
Same solution suggested by Tres without using jQuery
<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">
<select id="mysel" disabled="disabled">....</select>
<input name="submit" id="submit" type="submit" value="SEND FORM">
</form>
This might help someone understand more, but obviously is less flexible than the jQuery one.
The easiest way i found was to create a tiny javascript function tied to your form :
function enablePath() {
document.getElementById('select_name').disabled= "";
}
and you call it in your form here :
<form action="act.php" method="POST" name="form_name" onSubmit="enablePath();">
Or you can call it in the function you use to check your form :)
I use next code for disable options in selections
<select class="sel big" id="form_code" name="code" readonly="readonly">
<option value="user_played_game" selected="true">1 Game</option>
<option value="coins" disabled="">2 Object</option>
<option value="event" disabled="">3 Object</option>
<option value="level" disabled="">4 Object</option>
<option value="game" disabled="">5 Object</option>
</select>
// Disable selection for options
$('select option:not(:selected)').each(function(){
$(this).attr('disabled', 'disabled');
});
Just add a line before submit.
$("#XYZ").removeAttr("disabled");
Or use some JavaScript to change the name of the select and set it to disabled. This way the select is still submitted, but using a name you aren't checking.
I whipped up a quick (Jquery only) plugin, that saves the value in a data field while an input is disabled.
This just means as long as the field is being disabled programmaticly through jquery using .prop() or .attr()... then accessing the value by .val(), .serialize() or .serializeArra() will always return the value even if disabled :)
Shameless plug: https://github.com/Jezternz/jq-disabled-inputs
Based on the solution of the Jordan, I created a function that automatically creates a hidden input with the same name and same value of the select you want to become invalid. The first parameter can be an id or a jquery element; the second is a Boolean optional parameter where "true" disables and "false" enables the input. If omitted, the second parameter switches the select between "enabled" and "disabled".
function changeSelectUserManipulation(obj, disable){
var $obj = ( typeof obj === 'string' )? $('#'+obj) : obj;
disable = disable? !!disable : !$obj.is(':disabled');
if(disable){
$obj.prop('disabled', true)
.after("<input type='hidden' id='select_user_manipulation_hidden_"+$obj.attr('id')+"' name='"+$obj.attr('name')+"' value='"+$obj.val()+"'>");
}else{
$obj.prop('disabled', false)
.next("#select_user_manipulation_hidden_"+$obj.attr('id')).remove();
}
}
changeSelectUserManipulation("select_id");
I found a workable solution: remove all the elements except the selected one. You can then change the style to something that looks disabled as well.
Using jQuery:
jQuery(function($) {
$('form').submit(function(){
$('select option:not(:selected)', this).remove();
});
});
<select id="example">
<option value="">please select</option>
<option value="0" >one</option>
<option value="1">two</option>
</select>
if (condition){
//you can't select
$("#example").find("option").css("display","none");
}else{
//you can select
$("#example").find("option").css("display","block");
}
Another option is to use the readonly attribute.
<select readonly="readonly">
....
</select>
With readonly the value is still submitted, the input field is grayed out and the user cannot edit it.
Edit:
Quoted from http://www.w3.org/TR/html401/interact/forms.html#adef-readonly:
Read-only elements receive focus but cannot be modified by the user.
Read-only elements are included in tabbing navigation.
Read-only elements may be successful.
When it says the element may be succesful, it means it may be submitted, as stated here: http://www.w3.org/TR/html401/interact/forms.html#successful-controls

Categories

Resources