I have an MVC App and on one of my pages as part of the display I will render one of two partials based on a user selection of a radio button. This bit all works ok, but I have a button on the main form where I need to set/reset values that will be passed to my controller based on the user selection. The button is declared on my main form as:
#Html.GlobalModalAuthorizeButton("Upload Document", "Upload", "Documents", new { serviceUserId = Model.ServiceUser.Id, folderId = Model.CurrentFolderId, viewType = Model.ViewTypes.ToString() }, new { #class = "icon upload btn-primary" })
when this page is initially rendered the viewtype is set to the default view that the user is initially presented with. when the user changes the view the viewtype doesn't seem to get updated. So from the partial that has been loaded I try to set the value to the correct value. Using the Chrome browsers Developer tools if I do the following:
$(this).parent().parent().parent().parent().find($('.upload')).attr('data-url').replace('FileView', 'TreeView');
it returns in the console window the value I want (idea is that i set the value on the button before the user presses it). The trouble is the above doesn't really seem to have changed the data-url attribute on the button so consequently when the controller is hit, 'FileView' is still passed through.
For full attribute:
var new_attr = "/ServiceUser/Documents/Upload?serviceUserId=21&viewType=FileView";
$(this).parent().parent().parent().parent().find($('.upload')).attr('data-url', new_attr);
Or, as #Rup already suggested, you should first get the original attribute value, modify that using replace method and then reassign the new_attr.
jQuery got a special method to read and write data attributes:
var uploadButton = $(this).parent().parent().parent().parent().find('.upload');
var currentUrl = uploadButton.data('url');
uploadButton.data('url', currentUrl.replace('FileView', 'TreeView'));
Related
I have a customer who is a member of a web site. He has to fill a form every time which is really very often. That's why he wants me to develop an application for him to make this process automatic. When I use the webBrowser control to manipulate it, I am able to login but after that there are fields that contains data-binding. These fields are the ones I need to manipulate. When I push the data to necessary fields, it's not working, because in the html tag, there is no value attribute, instead it has data-binding. So my question is how can I manipulate and push data to these fields?
Thank you so much for your all help in advance.
Knockout uses data-binds to listen to changes in an input and update an underlying model. For example, the value binding listens to change events and writes the new value to a data-bound observable.
If you update a value attribute through code, the change event isn't triggered. You'll see the new value in the UI, but the javascript model won't be updated.
You can combat this by explicitly triggering a change. Here's an example:
Type in the input: you'll see a console.log that shows knockout gets updated
Press the button to inject a new value: you won't see a log: knockout isn't updated
Press the last button to trigger a change event. You'll notice knockout now updates the model.
Of course, you can combine the two click listeners into one function. I've separated them to get the point across.
// Hidden knockout code:
(function() {
var label = ko.observable("test");
label.subscribe(console.log.bind(console));
ko.applyBindings({ label: label });
}());
// Your code
var buttons = document.querySelectorAll("button");
var input = document.querySelector("input");
buttons[0].addEventListener("click", function() {
input.value = "generated value";
});
buttons[1].addEventListener("click", function() {
// http://stackoverflow.com/a/2856602/3297291
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
input.dispatchEvent(evt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="value: label">
<button>inject value from outside</button>
<button>let knockout know something changed</button>
I am attempting to get the data displayed from a database (it displays it on a dynamic page within a table) and have it as the value for a textfield on a different html page (map.html).
The value will be some sort of postcode/address and I want that to go into my google map page within the destination textfield. So when users check the location of the event they press the 'View on Map' button which will open up the page of the map and the data from the event should already be populated within the textfield.
However nothing appears and instead it remains blank, even when I just put in some dummy text it still doesn't populate. I know that the location value is being fetched as the alert correctly displays the location, but the problem is having it populate in the textfield.
I am using JQuery Mobile/Cordova/JavaScript/JQuery/HTML. The app is a one-page structure, with the exception of map.html which has it's own page.
Any ideas?
Fetching the location value:
$(document).on("click", ".btnMap", function(e){
var location = $(this).data("rowlocation");
viewMap(location);
});
Snippet of Button:
<a data-rowlocation='" + response.rows.item(i).Location + "' href='map.html' onclick='viewMap(location)' data-role='button' rel='external' data-mini='true' class='btnMap'>View on Map</a></td></tr>"
viewMap Function:
function viewMap(location) {
alert(location);
$("#target-dest").val(location);
}
HTML:
<input type="text" name="target-dest" id="target-dest" />
the simplest way of passing the location to a new page - using your existing code would be to append the location as a query string to the href in the link.
<a ...href='map.html?loc='" + response.rows.item(i).Location + "'...
and then on the destination page - use JS to grab the querystring from the URL, split it from the rest of the UURL and pass it to the textbox.
//js on destination page
var locn=location.href;
var locationPortions = locn.split("?loc=");
$('#target-dest").val(locationPortions[1]);
Because the trigger for this is clicking an <a>, the link is causing a loading of the map.html page which negates the updating of the contents of the textbox:
<a ...href='map.html'...
This is taking precedence over the onclick event. You need to either change the link into a button and trigger the function as an onclick event or prevent the link from performing its normal function as other posters have noted with e.preventDefault().
I have a web application using Umbraco (MVC .NET) that has (for now) only two roots. They are named "English" and "Swedish". English is the default webpage and Swedish should be optional for the user. In order for the user to be able to change language I display them in a dropdown menu using Razor:
#{
List<SelectListItem> languages= new List<SelectListItem>();
foreach (var language in Model.Content.Siblings())
{
languages.Add(new SelectListItem
{
Text = language.Name,
Value = language.Url
});
}
#Html.DropDownList("LanguageSelect",new SelectList(languages,"Value","Text"), htmlAttributes: new { id = "LanguageSelect" });
}
This properly outputs the names of the roots at root level. Now using javascript i reroute using onchange:
document.getElementById("LanguageSelect").onchange = function() {
window.location.href = this.value;
};
This works for going from one language to another. Now the hard part starts: because this dropdown exists in my master template inherited by all views, when a new view is loaded, everything from the template is reloaded. Therefor the dropdown is reloaded and the selected language is lost in the dropdown. Instead of looking at the URL for which value should be set in the dropdown I wanted to use local storage. So I tried setting this in the onchange function for the dropdown:
localStorage.setItem("LanguageSelectStoredUrl", this.value);
But this saves the URL. I would like to save the text aswell, i.e. "Swedish" and just set the current value of the dropdown to the stored value. This should work, right? If so how do I do that? Any reasons not to?
Another reason why I wanted to do it this way is because I want the user in a later session not having to choose language again by using:
$(document).onload(function(){
if(localStorage.getItem("LanguageSelectStoredValue") != null){
// Check if the dropdown value is equal to the stored value
// If so do nothing
// Else reroute to locally stored URL
But as I don't know how to store the text value of the dropdown I cant do this and maybe there is a more fitting event to hook on to than onload?
Here is a summary of my questions that I need help with in order to fulfill the task at hand:
How do I get the text of the selected dropdown item?
How do I programmaticly select one of the values in the dropdown?
Is there a better event to hook on to than onload?
Anything else that I might have overlooked?
Thanks!
To get the selected text of a drop down list:
JavaScript:
var languageSelect = document.getElementById("LanguageSelect");
var selectedText = languageSelect.options[languageSelect.selectedIndex].text;
jQuery:
$('#LanguageSelect option:selected').text();
Using $("#LanguageSelect").val('ValFromDdl'); will allow you to select an item in a drop down list.
You can use $(document).ready to read your storage object and initialize the drop down list.
I have a form with a « newInput » button, which add dynamically in javascript a new input when I click to it.
When I have an error in my form, I re-load the view with the form. It’s normal, but .. Because I use dynamic javascript for adding new input, all the input added are removed when I reload..
There is something I can do ?
This is an exemple of my view.tpl :
<input type="text" placeholder="ex: cerise"
onfocus="javascript:autoComplet('jigd1', '{site_url('recettes/getIngredient')}')" value="{set_value('igd[]')}" id="jigd1" name="igd[]"/>
{form_error('igd[]')}
I add a partiel code of my js file
var cpt=1;
function addField(uriIngredient, uriLabel) {
try
{
cpt=cpt+1;
var inputIgd = document.createElement('input'),
button = document.createElement('input'),
div = document.createElement('div'),
inputIgd.setAttribute('type','text');
inputIgd.setAttribute('name','igd[]');
inputIgd.setAttribute('id','jigd'+cpt);
button.setAttribute('type','button');
button.setAttribute('onclick','javascript:supField("igd'+cpt+'")');
button.setAttribute('value','Supprimer');
div.setAttribute('id','igd'+cpt);
div.appendChild(inputIgd);
div.appendChild(button);
document.getElementById("listIgd").appendChild(div);
...
Since you are appending new input/button to dom dynamically and not saving its state by making ajax call/submitting form you cannot retain the input/button after reloading the page.
Using localStorage, to keep the information of previously added input/buttom would be preferable.
PS : since you havent added any code which you tried, its really hard to explain localStorage with specific code.
as soon as you append, add the state of the form into localStorage,
When you loading the page, look for the localStorage to check the previously added inputs
you can set the item into localStorage :
window.localStorage.setItem('key','value')
You can retrieve them like this :
window.localStorage.getItem('key')
I am currently using bootstrap editable for the front end of my application.
See plugin: http://vitalets.github.io/x-editable/index.html
What I am doing is loading data onto a page via Ajax and allowing each item on the page to be editable. For example; I load a user onto a page and allows for his first name, last name and date of birth to be editable.
Because I am loading via Ajax, when a second user is loaded for example or third and i try to edit the first name etc, I keep getting the values of the first user loaded initially.
I am presuming it may be cache. I have tried setting display on the function and even auto-text.
Is there anyway I can reset or clear the editable form?
see sample code below:
function editable(obj) {
$('#title, #lastName, #firstName).editable('option', {
pk: obj.lId,
placement: 'bottom',
emptytext: 'Empty',
display: function(value) {
$(this).text(value);
},
validate: function(value) {
if ($.trim(value) === '') {
return 'This field is required';
}
}
});
}
Assuming that obj is your new user, and it contains the title, last name, and first name of the new user, all you have to do is set the values of the x-editable objects:
$('#title').editable('setValue', obj.title);
$('#lastName').editable('setValue', obj.lastName);
$('#firstName').editable('setValue', obj.firstName);
The reason why your example is not working is because x-editable separates the display from the actual value. Your display function is called whenever the user changes an x-editable value. By default, x-editable displays whatever the value is set to. But perhaps the internal value is different from a displayed value, that is what the display function is used for - it has no impact on the actual value, just the display of the value.
X-Editable has a lot of different methods you can take advantage of, you can find them on the 'Methods' tab here: http://vitalets.github.io/x-editable/docs.html#editable