As you know, autocomplete attribute is used for <input>s by default. Something like this:
Ok, I can totally remove that attribute by setting it off:
<input type="email" name="email" autocomplete="off">
// ^^^^^^^^^^^^^^^^^^
But I don't want disable it completely. I just want to limit it to two rows. Currently it is six rows. Anyway, Is there any solution (even by JS) to limit the number of that box's rows?
You can specify array of autocomplete options using jQuery.
$("#email").autocomplete({
source: function(request, response){
var results = $.ui.autocomplete.filter(yourAutocompleteArray, request.term);
response(results.slice(0, NUMBER_OF_ROWS_YOU_WANT));
}
});
As #SoftwareEngineer171 mentioned, you could using jQuery UI as a solution if you need that kind of control which is not available in HTML5 input control.
Link for example
Related
I am not sure how to phrase what I'm asking (or I would probably be able to find it). What is it called when you have an indefinite number of items to add to a webpage form for submission to a db? For example, if you have a resume web site, and you want to add experience. You may have a slot for one job, and an "Add more experience" to that. What is that called? How do you implement that (js, html, css)?
EDIT:
Thanks for the comments. This is called: dynamically add form elements.
this is a basic idea ,,
http://jsfiddle.net/3mebW/
var noOfFields = 2;
$('#addNew').on('click', function(e) {
e.preventDefault();
var newField = '<br><label for="experience'+noOfFields+'">experience'+noOfFields+'</label>';
newField += '<input type="text" name="experience'+noOfFields+'"class="field"/>';
$('.field:last').after(newField);
//adding a hidden input inside the form to know the number of inserted fields
//make sure that the input is not already here
//then adding it to handle the number of inputs later
if($('#noOfFields').length === 0){
$('#Frm').append('<input type="hidden" value="2" id="noOfFields"/>');
}else{
$('#noOfFields').attr('value',noOfFields);
}
noOfFields++;
});
you can also detect the number of fields using a class or any other method
You can do this using the jQuery function .clone().
Here's the jQuery doc about it : http://api.jquery.com/clone/
You can copy your Experience input field, and set its properties (ID, name, etc) before appending it where you want.
lots of ways to do this, here is is one
http://jsfiddle.net/uuKM8/
$('#myBtn').click(function(){
$( "#myInput" ).clone().appendTo('body');
});
Alternatively, is it possible to validate against another field's value with HTML?
A common example would be selecting a date range where "from" date should be less than or equal to "to" date. The following would described the desired relationship between the values, if only you could use element references in syntax:
<input type="date" name="from" max="to"> //todo: populate with ~to.value
<input type="date" name="to" min="from"> //todo: populate with ~from.value
It's possible to utilize html5 validation mechanism with some javascript to dynamically update min/max attributes:
//in this case a single input restriction is sufficient to validate the form:
$('#from, #to').on('change', function(){
$('#to').attr('min', $('#from').val());
});
Fiddled. Both min and max could be applied to the respective fields for enhanced UX if browser implementation of a datepicker respects range limitations (by disabling dates outside of the desired range)
Here, Web Components are very useful, however they are not full supported in all browsers yet .
The idea is to create a simple html Element, with two children (from and to) as the following:
<div id="fromToDate">
<div></div>
<div></div>
</div>
then create a template, which defines how the date picker should look:
<template id="fromToDateTemplate">
<label for="fromDate">from</label>
<input type="date" class="fromDate" select=":first" required="" />
<label for="toDate">to</label>
<input type="date" class="toDate" select=":last" required="" />
</template>
the select parameter defines, where the value is taken from so the first input field takes the first div from the "#fromToDate".
Last we have to populate the "shadow root" and define the logic:
var shadow = document.querySelector('#fromToDate').webkitCreateShadowRoot(),
template = document.querySelector('#fromToDateTemplate');
shadow.appendChild(template.content);
shadow.querySelector(".fromDate").addEventListener("change", function (e) {
var to = this.value;
shadow.querySelector(".toDate").setAttribute("min", this.value);
});
template.remove();
In the end two input fields are renderd and when selecting a date in the first datepicker, the second datepicker can't pick any lower data.
Fiddler example: http://jsfiddle.net/cMS9A/
Advantages:
Build as widget
Easy to reause
won't break pages
can be styled independently
Disadvantages:
Not supported in all browsers yet
Future reading:
http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/
http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201/
https://dvcs.w3.org/hg/webcomponents/raw-file/tip/explainer/index.html
If you want to avoid issues with someone hacking / crashing yor site - validate input data with:
(optional) javascript before sending a form (protects against malforming data using javascript, inputting incorrect one, reduces traffic)
(mandatory) on server side (protects against more clever guys that might malform input data using fiddler for example)
This is the only (at least second point) approach that protects you and your site.
It's great to see things moving towards a pure HTML solution ... but why not take a look at using moment.js to fill in the gaps for the time being?
http://momentjs.com/
There are plenty of good examples there and a lot of useful utility methods.
I'm worry, that there's no chance how to validate a input value based on other input value. Only good old javascript.
But maybe you can use <input type="range" …> and set some minimal step (1 day / 1 hour / …). Then you can use min and max value by same-named attributes.
I am wanting to try to change or limit a drop down list using JavaScript, or some other solution. Unfortunately, I have no control over the way the HTML comes out that I am trying to change client side. The drop down list is generated server side, but we would like to give the user additional options to further limit the choices in the drop down list.
We can't edit what is generated, but we can insert HTML.
One suggested solution, which may not be possible, is to use JavaScript to limit the dropdown list. For example, the drop down follows the format of:
<SELECT ID="dropdown_1">
<OPTION VALUE="" >None
<OPTION VALUE="1000">AB-ITEM 1 DESCRIPTION
<OPTION VALUE="2001">AB-ITEM 2 DESCRIPTION
<OPTION VALUE="50" >AB-ITEM 8 DESCRIPTION
<OPTION VALUE="70" >BB-ITEM 3 DESCRIPTION
<OPTION VALUE="100" >BB-ITEM 5 DESCRIPTION
<OPTION VALUE="2" >ABB-ITEM 4 DESCRIPTION
</SELECT>
What I want to limit by the beginning of the text, so AB-, BB-, or ABB- in this case. The value has no rhyme or reason, it's just an index number. I don't think this is possible since this is just text, and not associated with an attribute.
One thought would be to be to:
Store the list into a JavaScript array
Keep only entries like 'TYPE-X%'
Delete original HTML list
Replace with new list stored in the Array
However, I'm not sure if this is possible, and if it is, what would be needed to create such code. Any help or references to functions or examples would be greatly appreciated.
Anything is possible (with jQuery):
$(document).ready(function() {
$("#dropdown_1 option").hide();
$("#dropdown_1 option").filter(":contains(TYPE-X)").show();
});
An advantage with this is that all of the options are still there, you just can't see them. So all it would take to return to the default list would be a call to:
$("#dropdown_1 option").show();
Edit for regex:
$(document).ready(function() {
$("#dropdown_1 option").hide();
$("#dropdown_1 option").filter(function() {
return $(this).text().match(/^AB-/);
}).show();
});
You can filter your list using a regex like seen above.
Edit: A note about jQuery, this in the filter function is the DOM element itself. In order to access the jQuery helper method text(), I first need to wrap that DOM element with the jQuery function, as edited above.
Thanks to BinaryTox1n, I was put on a good path to find an all-browser compatible solution to my question. However, it is a slightly different approach pieced together from other solutions on StackOverFlow.
The difference comes is how one deals with the OPTIONs. Though .hide() works on some browsers, it is not compatible with IE8 (and maybe some others). Alternatives and variations to .hide() also failed. Another problem with .hide() is that you also need to use .disable(). The last problem is that if you have several (20 or so) options and only 2 or 3 are visible, Chrome (and perhaps other browsers) do not render the dropdown box properly.
The best approach found is to .remove() unwanted options. No compatibility issues because the OPTION is simply removed. However, I also want to have the flexibility to add back options if needed. So the following is a version of what I'll be using:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var regex_str = "^AAB-";
var dd1 = $("#dropdown1 option");
//Clone the 'None', Current, and All options into respective variables.
//All options are stored in order to allow different selection criteria
var all_Opt = dd1.clone(true);
var none_Opt = dd1.filter(":contains(None)").clone(true);
var cur_Opt = dd1.filter(function(){
return $(this).text().match(regex_str);
}).clone(true);
//Remove all options and replace the 'None' and Current options
dd1.remove();
noneOpt.appendTo($("#dropdown1"));
curOpt.appendTo($("#dropdown1"));
});
</script>
The only thing I'd like to add is the ability for this to change using a different drop down box or some other trigger.
I'm very new to jQuery and have been stumped by particular issue. I am dynamically adding 2 checkbox fields to a screen form using the code below:
var summon_search = "<br><br><br><label for='summon_search'>Search this resource from compatible products*</label><input type='checkbox' id='summon_search' >";
var summon_link = "<br><br><label for='summon_link'>Link direct from content items in compatible products*</label><input type='checkbox' name='summon_link'>";
$(summon_search+summon_link).insertAfter("#jstor_selection");
However I have had limited success when I want to remove these fields AND labels (which is dependant on another value) and replace them with new fields. The code below shows my best attempt so far. It does appear to remove the labels and first field, but for some reason the last field remains. Could someone please advise if they can spot anything I've done wrong, or perhaps supply a better example of handling this ?
if ($("#summon_search").length > 0 ) {
//Removal of Label and Field (Attempted)
$("label[for=summon_search]").remove();
$("label[for=summon_link]").remove();
$("#summon_search").remove();
$("#summon_link").remove();
Any feedback much appreciated.
Change name='summon_link' to id='summon_link', because #summon_link expects an id.
if you see your code the summon_link variable give it a id instead of name like in the summon_search variable
name=summon_link change it to id='summon_link'
if your intention is to add these HTML string after object with Id 'jstor_selection', you can use like this
$("#jstor_selection").append(summon_search+summon_link);
you should give the for= value in quotes.
EDIT: to remove extra <br>, normally it is suggested not to use <br>
$("label[for='summon_search']").prev('br').remove()
$("label[for='summon_link']").prev('br').remove()
$("label[for='summon_search']").remove();
$("label[for='summon_link']").remove();
also in the suman_link input element you have given as name
<input type='checkbox' name='summon_link'>
either change this to
<input type='checkbox' id='summon_link'/>
or
$("#summon_link").remove();
to
$("input[name='summon_link']").remove();
I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}