I have an autocomplete box that (for the purposes of this example, since it's a simple example) returns a list including social security numbers. These have dashes in them for readability. I want to modify the autocomplete so that if I put in "123456789" or "123-45-6789", it will find the same entry in the autocomplete, without having to add both styles to the autocomplete source. I've been looking at adding a callback to search, but I'm drawing a blank on exactly how to accomplish this.
If I were using a search that pulled from an AJAX source, I could simply trim the input server-side and return whatever results I wanted. However, for speed's sake, I've pre-loaded all of the data into the Javascript, so that option's out.
Basically, I want to know how to trim dashes off autocomplete input before comparing it to the stored data (and, preferably, comparing it to a copy of the stored data also with dashes trimmed). There's almost zero documentation on how to use the search: option, so I'm hoping someone can help.
One way to do this would be to provide a function to the source option of autocomplete:
var ssn = ['123-45-6789', '333-44-5543', '111-34-9696', '555-99-5323'];
$("#ssn").autocomplete({
source: function(request, response) {
/* Remove the dashes from the search term: */
var term = request.term.replace(/-/g, '');
var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
response($.map(ssn, function(el) {
/* Remove dashes from the source and compare with the term: */
if (matcher.test(el.replace(/-/g, ''))) {
return el;
}
}));
}
});
Here's what's going on:
The source option takes a request and response parameter. Basically, you manipulate request.term (replace the dashes with an empty string) before comparing it with the list of valid values.
Then, call the response function with the correct results. This example uses $.map to return a list of matches, comparing the term to each item in the list (without the "-").
Here's a working example: http://jsfiddle.net/andrewwhitaker/r4SzC/
Related
If I turn off enableFilter and roll my own input fields to search through the grid, how do I search only by one column?
See my plunker
$scope.searchGrid = function(searchTerm){
console.log("Term: " + searchTerm);
$scope.gridOptions.data = $filter('filter')(myData, searchTerm, undefined);
}
I want to have multiple input fields and send in the filter to each column as needed.
You would typically bind to a specific gridApi.grid.columns[x].filters[0].term, that's basically what the grid implementation of the filters does.
You'd end up with something like this:
http://plnkr.co/edit/2u56wGFUOCxPLp4ekEkT?p=preview
The other problem is that you now have filter boxes, which presumably you didn't want. You can suppress these by playing with the headerTemplates, but it is a bit of messing around.
I've seen so many posts and examples of people using a DDL placeholder like this...
#Html.DropDownList("lstUsers",(SelectList)ViewBag.UsersList, "--Select User--")
or
#Html.DropDownListFor(u => u.RoleID, Model.RoleList, "Select", new { #id="hi"})
I mean yea these work, but I want the placeholder to disappear after the ddl index changed, and all these do is place dummy text for the 1st index which can then be selected again.
I haven't been able to find an answer for the life of me. I've tried jquery
$("#tb2").attr("placeholder", "--Please Select--"
which works for a textbox, but not a DropDown. I'm using dynamically generated ddl's
Thanks!
That's not how the select element works. That "placeholder" is actually a full-fledged option in the select list. It's value is usually set to an empty string so that if it's still selected on POST, an empty string is posted and will caused an error if the field is expected to have a value. It doesn't just disappear automatically on it's own.
A textbox is entirely different. When placeholder text is placed inside a textbox, it is literally overwritten by user input, hence why it goes away. In HTML5 textboxes now have an actual placeholder attribute, which will show and hide a bit of text based on the focus of the input. The select element has no equivalent, though.
You could potentially do what you want with some additional JavaScript. You would just watch for a change event on the select and if it has a value (not the "placeholder"), then you could remove the first item from the select (which should be the placeholder):
$('#mySelect').on('change', function () {
if ($(this).val() != '') {
var firstChild = $(this).children().eq(0);
if (firstChild.prop('value') == '') firstChild.remove();
}
});
(I'm using jQuery here because doing the same in straight JavaScript would be much more arduous and since you're using ASP.NET MVC, it's a safe bet you're also using jQuery)
This question assumes familiarity with FormStack, a drag-and-drop WYSIWYG online form builder.
Background
A client is using FormStack to manage forms. Currently, form submissions are emailed, then manually entered into a database. Predictably, my task is to automate this process. This is easy enough using FormStack's WebHooks API: I can have form submissions sent to a URL, e.g. a PHP script, and happily parse away.
Question
Is it possible to name (or tag) FormStack fields with simple identifiers?
The client needs to be able to customize the form such that multiple fields may feed into the same database column.* FormStack however, as far as I can tell, provides only a way to specify a field label, e.g. Which of these trips interest you?, not a programmer-friendly identifier, e.g. Trip. My script would have to string-compare labels (which, due to their length, are more prone to typos) to determine what to do. What are some sensible workarounds to this problem?
Clarifications*
The reason there can exist multiple fields that feed into the same database column, is that the client uses conditional fields. For example, one field might ask, Where are you studying abroad? If the user selects "Europe", a conditional field might appear, asking Which of these trips interest you?, with choices pertaining to Europe. If the user selects "Africa" however, a similar field might appear, e.g. Which of these trips interest you?, but with choices pertaining to Africa. In FormStack, these are actually two distinct fields. However, as you can imagine, the values belong in the same database column, Trip.
I have settled on a hack for now. FormStack allows HTML markup in labels, e.g. Which of these trips interest you? <!--Trip-->. The client is willing to "tag" fields in this way.
Here's a snippet of the code that parses such tags, in case it might help someone else:
require_once 'Formstack.php';
$formstack = new Formstack($apiKey);
$form = $formstack->form($_POST['FormID']);
$taggedFields = array();
foreach ($form['fields'] as $field)
{
if (preg_match('/<!--\s*([0-9A-Za-z]+)\s*-->/',
$field['label'],
$matches))
{
$taggedFields[$matches[1]] = $_POST[$field['id']];
}
}
In fact, I've had to make it a little bit more sophisticated. Some FormStack field-types serialize input (in a horrific way). For example, FormStack's Name field-type takes multiple fields (prefix, first, middle, last, initial, suffix), and concatenates the results into a string:
'first = Andrew
initial = W
last = Cheong'
To handle this, I've written my code to handle such syntax in labels as Tell us your name! <!--FirstName=first--> <!--LastName=last--> <!--MiddleInitial=initial-->
The code follows.
require_once 'Formstack.php';
$formstack = new Formstack($apiKey);
$form = $formstack->form($_POST['FormID']);
$taggedFields = array();
foreach ($form['fields'] as $field)
{
if (preg_match_all('/<!--\s*([0-9A-Za-z]+)\s*(?:=\s*(\w+))?-->/',
$field['label'],
$matches,
PREG_SET_ORDER))
{
foreach ($matches as $captures)
{
if (count($captures) == 3 &&
preg_match('/(?:^|\n|\r)'.$captures[2].' = ([^\n\r]+)/',
$_POST[$field['id']],
$subcaptures))
{
$taggedFields[$captures[1]] = $subcaptures[1];
}
else
{
$taggedFields[$captures[1]] = $_POST[$field['id']];
}
}
}
}
Hopefully, FormStack will soon add a native way to name or tag fields!
i am working on a project and using Struts2 for it with JSP. In one JSP page, i have two drop down list say dd1 and dd2. The dd2 is dependable on dd1. The values in dd2 should be populated based on the dd1 value. Now i have a java class which gives me all the options for the drop down lists from the database and i am displying them in my JSP using the SELECT tag. How to make the dd2 dependable on dd1? I dont have any knowledge of Ajax. Please help.
Not a very big fan of any Ajax plugin.If you do not want to use any big fancy Ajax tags and are ready to learn a bit of JQuery or any other java-script framework, i suggest you to use simple ajax call.
Play around with the events when the value in your parent drop-down change call a function and make an Ajax call to your action which can return the values in JSON format (use struts2 JSON plugin), parse the JSON data and fill the other drop-down.
benefits of this approach are
More flexible.
Much light and faster.
No need to add any UN-necessary dependencies. Other approach (IMO not the good one) use Struts2-Jquery plugin to get it done but get ready for any undesirable behavior or any other issue and you have to reply on the Plugin community.
Here is an example as suggested
<s:select list="states" label="State" name="state" onchange="ajaxCallForDistrict();"
id="stateList"></s:select>
<s:select list="districts" label="District" name="district" id="district" />
what i am doing here is that District are dependent upon state so once user select a State from first select i am calling a java-script function on onchange event and here is my ajaxCallForDistrict() function
function ajaxCallForDistrict()
{
var selectedState = document.getElementById("stateList");
var statedata = selectedState.options[selectedState.selectedIndex].value;
var formInput='state='+statedata;
$.getJSON('search/getDistricts',formInput,function(data) {
$('.result').html('' + data.districts + '');
$.each(data.districts,function(index, value){
var districtid = document.getElementById("district");
var option=new Option(value,value);
try{
districtid.add(option);
}
catch(e){
districtid.appendChild(option);
}
});
});
}
what i am doing in above function is that i am fetching the value of selected state and giving the Ajax call to getDistricts Action which is simply creating a list of district for the provided state and returning back the result as JSON data.
for filling the District select i am looping through the result (JSON) and appending the element in the select box
JSP are servlets inside so there no way how to make interaction after response is send to client
i would recommend struts2-jquery-plugin - you will be able to solve this problem using ajax and this framework is good place to start if you are not interested in learning javascript (jQuery), showcase
I am not sure but may be this can help you...
jsp page
<s:select name= "" lable = "" onchange="javaScriptFunction(element that you have selected);"></s:select>
JavaScript---
<script>
function javaScriptFunction(element)
{
document.LoginForm.action=element+".action";
document.LoginForm.submit();
}
</script>
Now map these action in struts.xml
My suggestion is use one action but several different methods.
After that populate the other dropdown Box by using s:iterator.
I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid() can check for "undefined" or other things you don't want to handle.
Also, make sure you use $(document).ready() appropriately, of course.
[RFC 2396][1] section 4.1:
When a URI reference is used to perform a retrieval action on the
identified resource, the optional fragment identifier, separated from
the URI by a crosshatch ("#") character, consists of additional
reference information to be interpreted by the user agent after the
retrieval action has been successfully completed. As such, it is not
part of a URI, but is often used in conjunction with a URI.
(emphasis added)
[1]: https://www.rfc-editor.org/rfc/rfc2396#section-4
That's because the browser doesn't transmit that part to the server, sorry.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX).
Regards
Artur
You may see also how to play with back button and browser history
at Malcan
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Possible solution for GET requests:
New Link format: http://example.com/yourDirectory?hash=video01
Call this function toward top of controller or http://example.com/yourDirectory/index.php:
function redirect()
{
if (!empty($_GET['hash'])) {
/** Sanitize & Validate $_GET['hash']
If valid return string
If invalid: return empty or false
******************************************************/
$validHash = sanitizeAndValidateHashFunction($_GET['hash']);
if (!empty($validHash)) {
$url = './#' . $validHash;
} else {
$url = '/your404page.php';
}
header("Location: $url");
}
}