This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
display dropdown values based on previous dropdown
I know html pretty well and about forms a little bit, but would like to know, for example:
when clicking on a certain drop down list item, a certain second drop down list appears based on the previous field choice. how would you go about incorporating this, is there a specific website I can go to?
an example of code would be appreciated. I am assuming that you could use javascript for this?
do you retrieve specific values or just use different drop down lists for specific choices
Thanks
of the top of my head.
You would handle your javascript on the page, before you submit your form.
step 1. reference jquery in your header
step 2. on load, hide the second select, put this script beneath you reference jquery
<script type="text/javascript">
$(function () {
$("#secondselect").hide()
$("#firstselect").change(function () {
if($(this).val() != 0){
$("#secondselect").show()
}
else
{
$("#secondselect").hide()
}
});
});
</script>
<select id="firstselect" name="firstselect" >
<option value="0">first</option>
<option value="1">second</option>
<option value="2">third</option>
<option value="3"></option>
</select>
<select id="secondselect" name="secondselect">
<option value="0">first</option>
<option value="1">second</option>
<option value="2">third</option>
<option value="3"></option>
</select>
Of the top of my head... but i'd do it something like that.
Good luck.
Oh... just a quick update.
You could use a switch instead of an if like so, might be a bit tidier...
FROM
if($(this).val() != 0){
$("#secondselect").show()
}
else
{
$("#secondselect").hide()
}
TO
switch($(this).val())
{
case '1':
$("#secondselect").show();
break;
case '1':
//do something else... show a third dropdown instead
//for instance...
// $("#thirdselect").show();
alert('got to case 1');
//or if you use firebug or chrome, right click and inspect an element then click on Console and this log report should show
console.log('got here, showing the log');
break;
default:
$("#secondselect").hide();
}
I assume from your question that you want to dynamically populate the second dropdown based on the selected value of the first one.
To do that you can use jQuery to get the value of the first selected value pass it to a PHP file to get a response of the options that the second drop down needs to have and populate them.
You can use .show() and .hide() also to hide or show the dropdown when is needed.
$('#first').change(function(){
var selected= $('#first').val();
$.getJSON('data.php',{name: selected},function(data){
var results='';
$.each(data, function(i, item) {
results += '<option value="'+item.Description+'">'+item.Description+'</option>"' ;
});
$("select#Second").html(results);
})
});
If the options do not need to dynamically change and you just need to hide and show then you can use the simpsons88 answer!
Related
I have a form that contains a select with several options. One option can be selected by default based on a value in the DB.
If an option is selected by default, we want to apply some styling to it.
Once the form is rendered, I can simply do something like this...
$('#mySelect option:selected').addClass('customClass');
Lets say customClass just makes background-color:green.
What happens is that once the form is loaded, the option is still default white in the select. It only turns green once you click on the select.
I think this is because only the option is being changed to green.
If I do, just $('#mySelect').addClass('customClass'); then all options are green.
I thought about applying the class to the whole select and then looping through all options and removing the class except for the selected one, but that doesn't seem efficient.
Any ideas of a concise way to do this?
Thanks!
Here's a simple example
almost working example
Working Demo: https://jsfiddle.net/o81hyseg/
$("#mySelect").on("change", function(e){
if(!e.isTrigger)
$(this).find("option").removeAttr("selected");
if($("#mySelect").val() == "green"){
$('#mySelect').addClass('foo');
$('#mySelect').attr('title', 'foo');
$(this.options[this.options.selectedIndex]).attr("selected","");
}
else{
$('#mySelect').removeClass('foo');
$('#mySelect').removeAttr('title', 'foo');
}
});
$("#mySelect").trigger("change");
.foo {
background-color: green;
}
.foo option:not([selected]) {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect">
<option value="">Select...</option>
<option>white</option>
<option>white</option>
<option>white</option>
<option selected>green</option>
<option>white</option>
</select>
Screenshot of autocomplete lumping all results together in one line as opposed to as a vertical list.
I have the below:
$(document).ready(function() {
$.widget("app.autocomplete", $.ui.autocomplete, {
_create: function() {
if(this.element.is("select")) {
var self = this;
this.original = this.element.hide();
this.element = $("<input/>").insertAfter(this.original);
this.options.source = function(request, response) {
var filter = $.ui.autocomplete.filter,
$options = self.original.find("option"),
result = $options.map(function() {
return $(this).val();
});
response(filter(result, request.term));
};
}
this._super("_create");
},
_destroy: function() {
this._super("_destroy");
this.element.remove();
this.original.show();
}
});
$(function() {
$("#autocomplete").autocomplete();
});
});
In accordance with my mark up, which looks like:
<select id="autocomplete">
<option value="">Select State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
It is showing the auto complete options on one line currently; ie. Type in A, the results are 'ALAKAR...' etc all on one horizontal line -- I would like this to appear as.
ie. Alabama
Alaska
Etc
Etc
I don't want to alter the HTML mark-up. I have tried styling the option tag as follows.
ie.
option {
float:left;
width: 120px;
}
In your code you are using <option> tags as a source of data for jquery autocomplete, but this is not the same element that you are seeing in your filtered results. The actual element being generated/displayed is likely a list item or li (at least it is in all the demo examples).
[Edited] Originally I thought the OP needed to style the <option> tags directly
I'm using a selectbox on a Bootstrap platform to list multiple country flags that can be selected. On select the URL should be changed to the page of the country.
However, since I am not using <option> values, I don't know how to accomplish this. When I do work with <option> the flags won't display as shown below. Does anyone know how to add on select for this function?
<div class="bfh-selectbox bfh-countries pull-left" data-flags="true" data-country="NL" data-flags="true" data-blank="false" data-available="NL,BE">
</div>
Got it.
$(document).ready(function(){
$('.bfh-selectbox').on('change.bfhselectbox', function () {
if($(this).val()=="something"){
window.location.href="http://www.somelink.com";
}
else if($(this).val()=="somethingelse"){
window.location.href="http://www.someotherlink.com";
}
else {
}
});
});
I am generating the drop down dynamically by script (Smarty).
If the drop down has just one option value, is it possible to display it as a label.
This will display a drop down with 3 values.
<select>
<option> 1 </option>
<option> 2 </option>
<option> 3 </option>
</select>
If it shows just one value then display it as label, is it possible with pure HTML or Jquery or combination of both? I could use smarty to check for the values and throw different different html, but that would make my code long as I have many drop downs.
<select>
<option> 1 </option>
</select>
Any simple logic, which I might be missing?
UPDATE (RESOLVED)
Thank for all the stackoverflow'ers who helped.
I used the code given by #ahren which worked as required.
However I have expanded the code to copy the attributes of one tag to another, in case if someone is looking for
// To replace a <select>, with <label> tag if it has just one value
$('select').each(function(){
if($(this).find('option').length === 1){
// Copy all attributes from a given tag and save it in a variable.
var attributes_from = $(this).prop("attributes");
var attributes_to = '';
$.each(attributes_from, function() {
attributes_to += ' '+this.name+'="'+this.value+'"';
});
// If select then copy its value from option.
attributes_to += ' value="'+$(this).find('option').attr('value')+'"';
// Replace the <tag>
$(this).replaceWith(function(){
return $('<label '+attributes_to+' />').html($(this).text());
});
}
});
$('select').each(function(){
if($(this).find('option').length === 1){
$(this).replaceWith(function(){
return $('<label />').html($(this).text());
});
}
});
After you've generated your dropdowns, you can just run this snippet to check each of the select elements.
DEMO: http://jsfiddle.net/kqunE/
I'd iterate over each of the <select> elements, checking the number of options they have, and make the required DOM changes accordingly:
$('select').each(function(index, select) {
var numOptions = $('option', this).length;
if(numOptions === 1) {
// replace the select element here - something like the below
var label = $('<label>').html(this.value);
$(this).after(label).hide();
}
});
I opted to hide, rather than replace, the <select> element so you still get the value sent back as part of the form. If that's not required then you can remove the element entirely using .remove() in place of .hide().
I don't know if this is possible but I would like to have an input field where I would have a value that is not editable by the user.
However, I don't want the input field to be "readonly" because I still want the user to be able to add text after the value.
If you have any idea on how to do this, let me know please that would help me a lot.
EDIT: I use html forms.
You can position the text on top of the input field to make it look as if it is inside it. Something like this:
<input type="text" name="year" style="width:3.5em;padding-left:1.5em;font:inherit"><span style="margin-left:-3em;margin-right:10em;">19</span>
This way your input field will start with "19" which can not be edited, and the user can add information behind this.
Basically what you do is set the input field to a fixed width, so that you know how much negative margin-left to give the span with your text in it in order for it to be positioned exactly at the start of the input field.
You might need to fiddle with the margin-left of the span depending on the rest of your css.
Then also adding pedding-left to the input field, to make sure the user starts typing after your text and not under it.
font:inherit should make sure both your text and the text typed by the user are in the same font.
And if you want to put anything to the right of this input field, do add margin-right to the span with your text, as otherwise other content might start running over your input field as well.
seems a little weird to me ..why not just use a text output and afterwards the input field?
like sometimes used for the birthdate (although, maybe not anymore..)
birthyear: 19[input field]
edit:
with some javascript stuff you could realise something like that you asked for, though
an input field with text and catching keystrokes within that field while only allowing some after what you want to be always there - but, well, you would need to use js ..and if its just for that, Id rather say its not necessary
edit:
if you want to use a trick just for the viewer you could use a background-image/border-style that surrounds a text and the input field, thus making it look like text and input are the same input-box.
Sounds like you want placeholder text. In HTML5 you can set the placeholder attribute on any input element. This will work in modern browsers.
<input type="email" placeholder="jappleseed#appletree.com" name="reg_email" />
Now, for older browsers this won't work. You'll need a JavaScript alternative to provide the same UI value.
This can work for all browsers:
<input type="text" value="Search" onfocus="if (this.value == 'Search') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search';}">
but it's not recommended because there is a better way (really, it's a combination of the first two approaches): Use HTML5 markup for new browsers; jQuery and modernizr for old browsers. This way you can have only one set of code that will support all user cases.
Taken directly from webdesignerwall.com:
<script src="jquery.js"></script>
<script src="modernizr.js"></script>
<script>
$(document).ready(function(){
if(!Modernizr.input.placeholder){
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
</script>
[You'll need both jquery.js and modernizr.js installed in the same folder as your webpage.]
Note: I have a feeling that a little more research might reveal that modernizr isn't needed for this at all, though I could be wrong about that particular point.
Perhaps, then, you want a select menu?
<select name="mySelectMenu">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
Sorry if this isn't what you want either. I'm grasping at straws because what you are asking for is very vague. Maybe you should give an example of what one of these 'editable but not editable' inputs would be used for.
Also, you could use a select and a text input.
The main problem is to determine the position of the cursor. This can be done e.g. using the following function:
function getCaret(el) {
var pos = -1;
if (el.selectionStart) {
pos = el.selectionStart;
}
else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r != null) {
var re = el.createTextRange();
var rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
pos = rc.text.length;
}
}
return pos;
}
Now you can install an event handler for the key press and check whether the pressed key was inside the immutable part of the value of the textarea. If it was there the event handler returns false, otherwise true. This behavior can be wrapped into a simple object:
function Input(id, immutableText) {
this.el = document.getElementById(id);
this.el.value = immutableText;
this.immutableText = immutableText;
this.el.onkeypress = keyPress(this);
}
function keyPress(el) {
return function() {
var self = el;
return getCaret(self.el) >= self.immutableText.length;
}
}
Input.prototype.getUserText = function() {
return this.el.value.substring(this.immutableText.length);
};
var input = new Input("ta", "Enter your name: ");
var userText = input.getUserText();
You can check it on jsFiddle (use Firefox or Chrome).
I came up with this:
```
if (e.target.value == '' || e.target.value.length <= 3) {
e.target.value = '+91-';
}
```