Materialize Forms Accepting links - javascript

I use materialize often and ran into a little issue within one of my apps. To make it simple I want to basically include a link within a form input (materialize) that will send into a chat feature I made. When generating the tag, the form cannot read the text (because it is rejecting the html generated link format presumably). Does anyone knowledgable of forms with materialize know if forms can accept links and if so what kind of format or special script I would need to include to make the form accept text in the form of a link. It could be another issue as well. Any input would be appreciated!
Code in question:
// function for pre-filling the information in the modal on the chat button press
function handleChatForm() {
$.get("/api/user_data", {}, function(data) {
$('#sender-name').val(data.firstName);
$('.sender-name-label').addClass('active');
});
var currentChatNote = $(this).closest('.addedNoteRow').data("note");
console.log(currentChatNote);
console.log(currentChatNote.title);
var noteObjectForChat = {
title: currentChatNote.title,
body: currentChatNote.body
};
var noteLink = $('<a>');
noteLink.data('noteObject', noteObjectForChat);
noteLink.attr("href", "/cms");
noteLink.append(currentChatNote.title);
$('#new-message-body').val(noteLink)
$('.new-message-label').addClass('active');
}
/** Listener for send button to push data into firebase **/
sendButton.on('click', function() {
var msgName = nameInput.val().trim();
var msgText = textInput.val().trim();
myFirebase.push({ Name: msgName, Text: msgText });
textInput.val("");
});

Related

ArcGIS JS API - Conditional logic within popup

I have created a custom popup with the popupTemplate function with ArcGIS JS API 4.x
It would be great to introduce some conditional logic into my popups. For example, I am currently displaying a hyperlink to a website driven by an attribute within my layer. Not all features have associated websites, so ideally the conditional logic would only display text if the URL attribute was populated. The code below shows i) my existing popup and ii) how I am guessing I would insert a conditional value.
var template = {
content: [
{
type: "text", // TextContentElement
text: "<h1><font color='#c94600'>Click <a href={URL} target='_blank'><b>here</b></a> for video </font></h1>"
},
{
type: "text", // TextContentElement
text: conditionalFunction
},
]};
where conditionalFunction = something to the effect of...
if URL.attribute not null:
> return URL
else:
> return null
Can this be done easily with simple/basic Javascript?? (i'm very much a beginner)? If I can get this working, the next step would be to show a conditional table :)
Any help much appreciated.
You have a couple of ways to do this, you can use functions or promises. Basically instead of defining the content in a "static" manner, you do it "dynamic". In this way each time the popup display the content will be generated using the feature data.
Take a look at this example of ArcGIS. It uses function to set the content of the template, and it dinamically define the arrow style to display (up or down and color).
You can do something similar, like this,
var template = {
content: function(feature) {
var div = document.createElement("div");
if (feature.graphic.attributes.URL) {
div.innerHTML =
"<h1><font color='#c94600'>Click <a href=" +
feature.graphic.attributes.URL +
" target='_blank'><b>here</b></a> for video </font></h1>";
}
return div;
},
outFields: ["URL"]
};
I am assuming that URL is the attribute that contains the url.

How to hide the table until a string is searched? [duplicate]

This question already has answers here:
Rendering partial view on button click in ASP.NET MVC
(2 answers)
Closed 4 years ago.
I'm currently interning as part of my school course at a small tech company and one of the projects I'm working on right now is making a web application with MVC.
The manager gave me a SQL database to work with and I've been following this tutorial by Microsoft here to help me build the web app.
Now, the specific thing the manager wants me to do is hiding the table when someone loads the page and when a string is submitted into the search bar, the relevant information in the table matching the string shows up.
I've been looking everywhere, including SO how to do this for a few days now, no matter what code I try it doesn't seem to work! I've been trying different things using HTML and JS, following some examples posted here, I just can't figure out how to do it, the table flashes for a second when I click the search button, I think it's the page refreshing but why?
Here's my controller with the searchBar
public ActionResult Index(string searchString)
{
ViewBag.NameSortParm = String.IsNullOrEmpty (searchString) ? "name_prmrnm" : "";
var person = from p in db.persons
select p;
if (!String.IsNullOrEmpty(searchString))
{
person = person.Where(s => s.name.Contains(searchString));
}
return View(person.ToList());
}
Here's my javascript in the View:
<script type="text/javascript">
function escondeTable(){
var hideTab = document.getElementById("table-class");
if (hideTab.style.display == 'none') {
hideTab.style.display = '';
}
else {
hideTab.style.display == 'none'
}
}
</script>
And here's my form:
<form action="/people/Index" method="post" onsubmit="escondeTable()">
<p class="barraProc">
#Html.TextBox("searchString", "", new { placeholder = "Insira um nome..." })
<input type="button" value="Procurar">
</p>
</form>
Can anyone tell me what I could be using or doing?
You have to use Ajax call. And one option then is this
$( document ).ajaxStart(function() {
var hideTab = document.getElementById("table-class");
hideTab.hide();
});
$( document ).ajaxStop(function() {
var hideTab = document.getElementById("table-class");
hideTab.show();
});
May I suggest a proper approach?
I'd stay away from forms, because they cause a lot of headaches. Just use regular inputs and event listeners.
Also, I'd use a RESTful API, i.e. avoiding a POST method, and using a GET method to get the table data from the backend.
The API should serve the data on this URL localhost/search/critieria, where the user supplies the criteria.
You can render the table in the following way:
fetch("http://localhost/search/" + criteria)
.then((res) => res.json())
.then((data) => {
generateTable(data);
})
.catch((err) => err);
Here is a quick demo I made: https://jsfiddle.net/hwtgeo36/7/
You insert a number, and it returns a Star Wars character from a server (ex. 1 = Luke Skywalker). You can use the same logic with your own server.
Also, you would render your table here, instead of my example that replaces some html.
If you have troubles with this, please write back.

HOW to update and display JSON file dynamically on click of a button?

I am creating an addon in which, on click of a toolbar button, a panel is displayed which contains checkboxes and a save button. On clicking the save button, the selected checkbox`s data should be saved/updated in a JSON file which should be displayed after clicking save.
Moreover, the data dynamically updated in JSON file should be available even after browser restart.
Also the JSON file should be saved in file system or local storage?
Is this possible.. plz help... And plz ask if u need more info. Below is the addonScript which I used:-
var self = require('sdk/self');
var data = require("sdk/self").data;
var text_entry = require("sdk/panel").Panel({
contentURL: data.url("CheckboxAddon.html"),
//contentScriptFile: data.url("my-script.js")
});
// button creation
require("sdk/ui/button/action").ActionButton({
id: "show-panel",
label: "Show Panel",
icon: {
"16": "./star-icon.png",
},
onClick: handleClick
});
// Show the panel when the user clicks the button.
function handleClick(state) {
text_entry.show();
}
text_entry.on("show", function() {
text_entry.port.emit("show");
});
text_entry.port.on("text-entered", function (text) {
console.log(text);
text_entry.hide();
});
One of the things to keep in mind is that JSON is a subset of javascript, so you just write a javascript object which is also valid JSON. In your case I doubt this is going to be something you'll have to be worrying about. to achieve the effect you're looking for you can simply throw whatever data into dataString = JSON.stringify(data) or dataString = JSON.stringify(data, null, "\t") to give it that json format look. Conversely you would use JSON.parse(dataString) to turn a string into a javascript object.
Definitely use the json.org documentation a guide for writing JSON objects yourself.
the documentation on MDN has good examples, look at the JSON.stringify and JSON.parse in the methods section

google script - entire form delete

I want to send a form in Email to a group of 15 users. The form would contain just two questions one radial button with a pre-set long code and another one is yes and no. So creating form and emailing the form by doing it within Google Script is NOT the question here.
However, once users submit I want this form to be deleted. I know I can just do isAcceptingResponses() to false and let these old forms dust in my Google Drive. However, if I do that I will keep collecting irrelevant forms in my Google Drive. Is there anyway to destroy a form? or what would you suggest?
Here is an example of creating form as per Google developers manual
https://developers.google.com/apps-script/reference/forms/:
function myCreateForm() {
var form = FormApp.create('Form Autocreaticus');
var item = form.addCheckboxItem();
item.setTitle('What condiments would you like on your hot dog?');
item.setChoices([
item.createChoice('Ketchup'),
item.createChoice('Mustard'),
item.createChoice('Relish')
]);
form.addMultipleChoiceItem()
.setTitle('Do you prefer cats or dogs?')
.setChoiceValues(['Cats','Dogs'])
.showOtherOption(true);
form.addGridItem()
.setTitle('Rate your interests')
.setRows(['Cars', 'Computers', 'Celebrities'])
.setColumns(['Boring', 'So-so', 'Interesting']);
Logger.log('Editor URL: ' + form.getId());
return form.getId() //so I can later use for my myDeleteForm().
}
function myDeleteForm() { //myDeleteForm(formID) {
var formID = '1utQdu9EsuQFgMKNbP5Hjm68fxpP-_vKrBNNXL8jsOZo';
DriveApp.getFileById(formID).setTrashed(true);
}
*This code was changed to accommodate the functionality. Thank you!
To delete the file itself you may need to use the DriveApp. The methods you found only seem to remove/change settings or reponses.
This deletes:
function myDeleteForm() {
var formID = '1utQdu9EsuQFgMKNbP5Hjm68fxpP-_vKrBNNXL8jsOZo';
DriveApp.getFileById(formID).setTrashed(true);
}

How should I handle Asp.net MVC URLs in javascript calls?

I am attempting to write a javascript heavy portion of my Asp.net MVC Web App (this portion of the website is a RIA using Extjs). However, I have come up to a standstill at the correct way to handle URLs in the javascript.
For example, right now I have an Ajax call to the List action in the ObjectsController, which resides in the Reading area. The List action takes a parameter of documentId (int). As of right now, this maps to /Reading/Objects/List since I have no changed routing yet (the site is too young at the moment to finalize routes). Normally in a view, to put this URL in a string I would do #Html.Action("List", "Objects", new { area = "Reading", documentId = 3).
However, this doesn't work when dealing with javascript, since javascript isn't parsed by a viewengine.
To get around this, I have a very small view that returns javascript constants, such as URLs, that is loaded prior to my main application's js files. The issue is that I can't call Html.Action for this action because at constant creation time I (obviously) do not know what documentId the ajax calls are going to be, and if you exclude documentId from the Html.Action call an exception occurs. The documentId could change during the normal workflow of the application.
How do I handle this? I don't want to hardcode the URL to /Reading/Objects/List because if I change my routing for this (for a more user friendly json API), or this web app isn't hosted on the root of the domain, the URL will no longer be valid.
How does everyone else handle MVC URLs in their javascript calls?
Here's a safe technique that I've been using. Even if your route changes, your JavaScript will automatically conform to the new route:
<script>
var url = '#Url.Action("List", "Objects", new { area = "Reading", documentId = "_documentId_")';
var id = 100;
var finalUrl = url.replace('_documentId_', id);
</script>
"_documentId_" is essentially a dummy placeholder. Then inside my JavaScript, I replace "_documentId_" with the proper id value once I know what it is. This way, regardless of how your route is configured, your URL will conform.
Update: Dec 20
I just saw this interesting blog post. The author built a library that allows you to build routes inside of your JavaScript file with intellisense support in VisualStudio.
http://weblogs.asp.net/zowens/archive/2010/12/20/asp-net-mvc-javascript-routing.aspx
Personally I use unobtrusive javascript and avoid mixing markup with javascript. AJAX calls are normally triggered by clicking on some buttons or links:
#Html.ActionLink("click me", "List", "Objects",
new { area = "Reading", documentId = 3 }, new { id = "foo" })
and then in a separate js file I would attach and handle the onclick event (example with jquery):
$(function() {
$('#foo').click(function() {
$('#resultDiv').load(this.href);
return false;
});
});
As you can I didn't need to use any hardcoded URL in my javascript file. URLs should always be handled by the routing engine and generated with html helpers.
If it was a <form> instead of a link I would simply handle the onsubmit event (the same way) and use the form's action attribute to get the URL.
UPDATE:
After pointing out in the comments section that the documentId is known only at client-side you could do this:
#Html.ActionLink("click me", "List", "Objects",
new { area = "Reading" }, new { id = "foo" })
And then:
$(function() {
$('#foo').click(function() {
$('#resultDiv').load(this.href, { documentId: '123' });
return false;
});
});
Turns out, this was all solved by using Url.Action() instead of Html.Action(). Url.Action() is (so far) allowing me to generate URLS without all of the parameters. I am assuming that this only works when the route does not specify the parameters in the target URL itself.

Categories

Resources