HTML, display label if drop down has just one value - html

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().

Related

style option tag for jquery-ui autocomplete solution - appear as vertical list

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

Dropdown select extended options

Im trying to make a dropdown. U have to search on the package number and you will get the detailed information so you can immediately see the correct price or sizes for that package.
<div class="choosePackage">
<label>
<span>Package nr</span>
<span>m3</span>
<span>Size LxWxH</span>
<span>Price</span>
<span>Discount</span>
</label>
<select>
<option value="">
<span class="optPackage"><strong>5528</strong></span>
<span class="optM3">9m3</span>
<span class="optLWH">1.00x2.00x3.40m</span>
<span class="optPrice">€70,00</span>
<span class="optDiscount">€280,00</span>
</option>
</select>
</div>
I made something like this, but you can't split the option.
This is what I want to achieve
I was working on a solution, but have to run into a meeting. This should give you a basic idea however. Basically, you need to use JS to overlay a styled dropdown which will be linked to the actual drop down. Then you can style things to be different with in each option.
Start by creating your drop down select
You will want to make all the text as a single drop down
<select id="selectbox1">
<option value="">Select an option…</option>
<option value="basic">$100 Basic Package 3 Months</option>
<option value="upgraded">$500 Upgraded Package 6 Months</option>
<option value="expert">$1000 Expert Package 12 Months</option>
</select>
Then you theoretically, jump through hoops using Javascript
Here you will need to cache your options, then hide the select to show your styled div.
// Cache the number of options
var $this = $(this),
numberOfOptions = $(this).children('option').length;
// Hides the select element
$this.addClass('s-hidden');
// Wrap the select element in a div
$this.wrap('<div class="select"></div>');
// Insert a styled div to sit over the top of the hidden select element
$this.after('<div class="styledSelect"></div>');
// Cache the styled div
var $styledSelect = $this.next('div.styledSelect');
// Show the first select option in the styled div
$styledSelect.text($this.children('option').eq(0).text());
Now you will want to cache your styled div, and append some child elements into your div
// Cache the styled div
var $styledSelect = $this.next('div.styledSelect');
// Show the first select option in the styled div
$styledSelect.text($this.children('option').eq(0).text());
// Insert an unordered list after the styled div and also cache the list
var $list = $('<ul />', {
'class': 'options'
}).insertAfter($styledSelect);
// Insert a list item into the unordered list for each select option
for (var i = 0; i < numberOfOptions; i++) {
$('<li />', {
html: $this.children('option').eq(i).text()
.split(' ').join(' <span style="color: red; font-weight:100;">'),
rel: $this.children('option').eq(i).val()
}).appendTo($list);
}
// Cache the list items
var $listItems = $list.children('li');
You will want to use your for loop to append styling onto certain parts of your drop down. I have a basic mock up for you to check out as well.

Is it possible from one button to reset a page? HTML

I've created a html page and in that page I have forms, drop down lists and radio tags and tables. from one button I wanted to reset everything on the page when its clicked upon.
you can use the following JavaScript method to clear the HTML input file control's value:
function clearFileInputField(tagId) {
document.getElementById(tagId).innerHTML =
document.getElementById(tagId).innerHTML;
}
Or, if refactored in jQuery, this should work as well:
$("#control").html($("#control").html())
Or, for textbox type
var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
if (elements[ii].type == "text") {
elements[ii].value = "";
}
}
You could use a reset button, please refer to this page for more information -> LINK
But if you have multiple form on the page you can write a javascript function to reset all of them like this:
$('#yourResetButton').click(function(){
$('form').each(function(idx, obj){
obj.reset();
});
});
You could also refresh your page as stated in other answers but in my opinion that could be very disappointing for your users to see that the page is refreshing
A little working fiddle as example
You can reset with reset however you won't be able to reset your inputs that doesn't included into forms, otherwise you can clear inputs within your forms like:
$('form').each(function (index, obj) { obj.reset(); });
Example
<input type="button" onclick="function() {window.location.href = window.location.href;}" name="Reset" value="Reset">

something noob about html forms [duplicate]

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!

Having a permanent value in an input field while still being able to add text to it

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-';
}
```