Submit javascript dynamically added elements to controller method like Stackoverflow - javascript

Put it simply: I'd like to let the user to select some tags in JS and submit it to my controller. Here are my suggestions:
Create a hidden input for every inserted tag with naming convention like: Tag123 (123 = this tag's unique identifier) and iterate through FormCollection in my action method to find out which tags have been selected. Cons are obvious: using FormCollection instead of ViewModel and iterating through the FormCollection to get my desired data seems bad to me.
Create one hidden input and append every selected tag to it. This can become messy on tags deletion since I should find the right id from the input's current value and delete it. But the Pro is that I only have one element and can put it in a viewmodel to access it in controller action.
Curious to see if anyone knows how SO does it. They're kind of defning the standards now. Would love to know how they do it.
Thanks.

I have a website running with the option of adding tags, much like SO.
My approach to the problem, however, led to me create one input field for each added tag, and increment a javascript index variable every time a new input is added, then making use of a ViewModel to bind a IList<TagDTO> tags { get; set; } (forms tend to get complex over time anyway, so a viewmodel is almost always a good way to go). Here is an example of the html hidden inputs created in the page:
name=tags.Index, value=0
name=tags[0].tagid, value=201
name=tags.Index, value=2
name=tags[2].tagid, value=307
This has one great advantage to me: Internationalized tags and possibly disallowing nonexistent tags.
What I mean is that every tag has an ID, and in my "Tags" table in the database there is one column for the name of this tag in each language I support. Such as:
tagid | name_ptBR | name_en
201 | animais | animals
307 | educacional | educational
This is only my approach to the problem, but it has worked out ok so far.

Stack Overflow just has one text input field, which is enhanced with autocompletion by JavaScript. When it's sent to the server, the field is split by spaces, and the corresponding tags are looked up by name. I recommend you do that, as it's the most accessible of all the options.

Related

Input Submit Button - Html.buttonfor

I am a bit new to mvc razor and building websites (front and backend). The break down is, I need a button that has a value stored in it be sent to the controller/model. Something similar to html boxtextfor. I have tried giving boxtextfor attributes similar to an input submit button, but it doesn't like that. I have tested the button using javascript and it does have the value within each individual button (# of buttons are dynamic based on previous submit).
I have seen posts like this but I am unsure how to add these to my controller or model so my index page can call it. My model is linked to my index page so I guess I could link these methods in my model.
There's no #Html.Button !
(tried this, but it needs to be linked to my model. A simple button doesn't work.)
Looking for a Html.SubmitButton helper that would accept class attributes in MVC3
I currently don't have access to my code in question. The button needs to be an input submit to go to [HTTPPOST]. However, if you need any more information please let me know.
Thank you for your time,
HtmlNooby
I solved it by wrapping a button with the following. This creates binds each individual button with the given item from an array. Kind of acts like a buttonfor if you will.
Foreach item in array{
#using(Html.BeginForm(…)
{
<button class=input value=item>item</button>
}
}

Is there any way to edit a URL to embed a form entry?

I know it is possible to embed form values into the URL as parameters if the form has an ID assigned to it. But what if it does not have an ID?
For example the "Search" field in this page:
http://au.autodesk.com/speaker-resource-center/call-for-proposals/voting
<input type="text" placeholder="Search " class="form-control ng-valid ng-dirty search-box" ng-model="search.$" ng-change="updateButtons()">
I know it is possible to embed form values into the URL as parameters if the form has an ID assigned to it.
That is not true.
Server-side (and occasionally client-side) code on a page may read the query string as a means to set default values for form controls (typically so that a form can be corrected and resubmitted if there were errors in the previous attempt).
In these cases, the name attributes will usually map onto the query string (because the form will generate the query string from the name attributes). Often an input will be given an id that is the same as its name.
It is entirely under the control of the site's authors.
There is no way to set values of inputs on another site without the other side providing a mechanism to allow you to do that.
There's a few different ways to do that. Looking at that HTML, it's the first text-type input inside the div, so the first method that comes to mind is this:
You could pull out the div (using the class "search-area") and then target the first text input box within that div. I don't know whether you're using jQuery or native JS or exactly what language/library/framework you're using.
JQuery would be something like:
var inputElement = $(".search-area")[0].first()
This SO answer may help:
jQuery: how to find first visible input/select/textarea excluding buttons?
Edited to add: Answer is targetting the input element. As the answer from someone else mentions.. You can't actually do what you're wanting to do with the URL.
Edited again. Misread the question. I'll leave this here in case someone else needs to know how to target an input field that doesn't have an ID. Alternatively, I have no problems if someone wants to delete this answer.

Get Input Field value using DTM on Submitting a form

I have two input fields that had the user access card and password. and the user click on submit button to authenticate.
I'm using DTM in my app to capture the user navigation but I want also to get the values of those field to my DTM so I would know who the user is.
And here is what I tried but with no luck.
Created Data element as below:
And created Event based rule. But not sure how to get the values to be shown in my report:
Thanks for your help.
Example Form
Since you did not post what your form code looks like, here is a simple form based on what I see in the screenshots you posted, that I will use in my examples below.
<form id='someForm'>
User Name <input type='text' name='userName'><br>
Password <input type='password' name='userPass'><br>
<input type='submit' value='submit' />
</form>
Data Elements
Okay first, let's go over what you did wrong.
1) You said you want to capture two form fields, but you only have one data element...maybe? You didn't really convey this in your question. I just assumed as much because of what you did throughout the rest of the screenshots. But to be clear: you should have two separate data elements, one for each field.
2) The CSS Selector Chain value you used is just input, so it will select the first input field on the page, which may or may not coincide with one of the input fields you are looking to capture. So, you need to use a CSS selector that is unique to the input field you want to capture. Something as simple as input[name="userName"] will probably be good enough (but I cannot confirm this without seeing your site). You will need to do the same for the 2nd Data Element you create for the other input field (e.g. input[name="userPass"])
3) In the Get the value of dropdown, you chose "name". This means that if you have for example <input type='text' name='foo'>, it will return "foo". Since you want to capture the value the user inputs, you should select "value" from the dropdown.
Solution
Putting all the above together, you should have two Data Elements that look something like this (one for the user name field and one for the password field; only one shown below):
Event Base Rule
Okay first, let's go over what you did wrong.
1) The value you specified in Element Tag or Selector is input. You aren't submitting an input field; you are submitting a form. Input fields don't even have a submit event handler! Your Event Type is "submit", so at a minimum, Element Tag or Selector should be form. But really..
2) Ideally, you should use a CSS Selector that more directly and uniquely targets the form you want to trigger the rule for. For example, maybe the form has an id attribute you can target in your CSS Selector. Or maybe the form is on a specific page, so you can add additional conditions based on the URL. What combination of CSS Selector or other conditions you use to uniquely identify your form depends on how your site is setup. In my example form above, I added an id attribute, so I can use form#someForm as the CSS Selector.
3) You checked the Manually assign properties & attributes checkbox, and then added two Property = Value items. This tells DTM to only trigger the rule if the input has a name attribute with value of "userName" AND if it has a name attribute value of "userPass". Well name can't have two values at the same time, now can it!
<input name='foo' name='bar'> <!-- bad! -->
All of this needs to be removed, because again (from #1), you should be targeting a form, not an input field.
4) For good measure, looks like you added a Rule Condition of type Data > Custom, but the code box is empty. The rule will only trigger if the box returns a truthy value. Since there is no code in the box, it will return undefined (default value returned by a javascript function if nothing is returned), which is a falsey value. This also needs to be removed.
Solution
Putting all the above together, the Conditions section of the Event Based Rule should look something like this:
But again, ideally your conditions should be more complex, to more uniquely target your form.
Referencing the Data Elements
Lastly, you can reference the input fields to populate whatever fields in the various Tool sections with the %data_element% syntax. For example, you can populate a couple of Adobe Analytics eVars like this (data element names reflect the examples I created above):
Or, you can reference them with javascript syntax in a custom code box as e.g. _satellite.getVar('form_userName');
Additional Notes
1) I Strongly recommend you do not capture / track this type of info. Firstly, based on context clues in your post, it looks like this may count as Personally Identifiable Information (PII), which is protected under a number of laws, varying from country to country. Secondly, in general, it is a big security risk to capture this information and send it to Adobe (or anywhere else, really). Overall, capturing this sort of data is practically begging for fines, lawsuits, etc.
2) Note that (assuming all conditions met), the "submit" Event Type will track when the user clicks the submit button, which is not necessarily the same thing as the user successfully completing the form (filling out all the form fields with valid input, etc.). I don't know the full context/motive of your requirements, but in general, most people aim to only capture an event / data on successful form completion (and sometimes separately track form errors).

Transfer possibly unsafe user input from hidden input field to DOM

The following is a simplified example of a page a user has created at a site (they created it by filling out a form and then they get a URL for the page; the below is the HTML for the page they created).
In the example, I'm taking the value of a hidden input field and then putting it into the DOM as is. That results in an alert, simulating an XSS attack.
What's the best way to prevent things like this? The value of #sourceinput was previously input by the same or a different user who's viewing the page below, and the user's input wasn't filtered to remove tags. (The actual case involves the jquery.tooltip.js plugin and it's bodyHandler callback; on mouseover a bodyHandler callback would get the hidden input and display it to the user.)
One way to deal with this would be to strip tags on input; I control what goes in the hidden textfield so that would seem to solve it.
Another way would be to strip tags in Javascript, but some of these don't seem to be 100% effective:
Strip HTML from Text JavaScript
Is there some sort of best practice that I'm missing, or are those two the best ways?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>
<title></title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>google.load("jquery", "1.7.1");</script>
<script>
$(document).ready(function() {
var badHTML = $('#sourceinput').val();
$('#destinationdiv').html( badHTML );
//$('#destinationdiv').text( badHTML );
});
</script>
</head>
<body>
<input type="hidden" id="sourceinput" value="<script>alert('hi');</script>" />
<div id="destinationdiv" style="width:10px;height:10px;background-color:red;"></div>
</body>
</html>
UPDATE: The solution I'm going with for now has three parts:
When the page the user has created is saved, I run PHP's strip_tags() on their input. These are just short text strings like titles and blurbs, so few users will expect they can enter HTML. That might not be appropriate for other situations.
When the page the user created is displayed, instead of putting what the user had entered in an input value attribute, I put their input inside a div.
I take the value out of that div using .text() (not .html() ). I then run that through the underscore function (see below).
Testing this out - including simulating skipping the first step - seems to work. At least I'm hoping there isn't something I missed.
Here's the escape function used by Underscore.js, if you don't want to use the entire Underscore library of functions:
var escape = function(string) {
return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
};
Used like
var safe_html = escape("<b>Potentially unsafe text</b>"); // "<b>hello</b>"
$("#destination").html(safe_html);
It's written well and is known to work, so I'd advise against rolling your own.
I would say what you commented out (using text() from jquery is the better option). That will make sure the text stays text which is what you want. Filtering or stripping may have unwanted side effects like removing a mathematical expression in the input (" x is < 5").
Do Nothing.
You are trying to protect the user from himself. There is no way the user A can harm user B. And for all you care, user A might as well type javascript:alert('hi') on the address bar and xss himself. And no matter what javascript escape function you create, a savvy user can always bypass it. All in all, its a pointless pursuit.
Now, if you start saving what the user entered on the server side, then you should definitely filter things. Don't build anything on your own. Depending on your server side language, there are several options. OWASP's AntiSammy is one such solution.
If you do choose to save user entered html on the server side, make sure to run it by antisammy or a similar library before saving it to the database. On the way out, you should simply dump the HTML without escaping, because you know whatever is in the database is sanitized.

Getting HTML with the data using jQuery

I have a form which has many elements (e.g. textarea, input, select), after users have entered some data the states of these elements should change.
For example, an input[type="radio"] element will have the attribute checked="checked" if a user has checked it. The value attribute of an input[type="text"] element will contain the text entered by user.
The problem is that the html string returned by $('#form1').html() does not contain these data.
Feel free to take a look at this example:
http://jsfiddle.net/cmNmu/
You can see that no matter what your inputs are, the html returned is still the same (having no attribute data).
Is there any easy way to collect the html including their states?
Thanks in advance.
use below code getting the value of input type text via jQuery
alert($("input:text").val())
Maybe you could use the 'onblur' event handler to set the value of the element when you leave it
You should get the value using :
$('#form1').find(':input').val();
$('#form1').find(':radio[name=gender]:checked').val();
if you have multiple input then you can filter them bu their name or class or even id. Then you will need to select input using .find(':input[name=input_field_name]'). My Suggestion is : use name property instead of other property if you want to use form.
People usually use $('#form1').serialize() to get the values. If html() doesn't return both the source and data, I don't think that there is something you can other than manually constructing the full html by looking at the data.
Live demo: http://jsfiddle.net/cmNmu/6/
By using the jQuery formhtml plugin written by gnarf:
jQuery html() in Firefox (uses .innerHTML) ignores DOM changes
The changes in the input elements can be reflected in the html string returned by formhtml().
Thank you very much everyone.

Categories