Textfield not displaying variable from javascript function - javascript

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().

Related

angularjs remove $scope.expression from ng-src

I have a image from a angular scope that is placed over my background image in a from, when i submit the form i clear the data from the form, however the image remains. How would i be able to remove the image from the $scope and just see the background image again.
This is the code (example)
<form ng-submit=submitform()>
<input type="text" ng-model="formdata.gametitle">
<input type="text" ng-model="formdata.image">
<img ng-src="{{formdata.image}}" style="background-image: 'url("select.jpg")'; width: 5vw; height: 7vw;"/>
<input type="submit">
so what this does it that the user adds a suggested image in the input (formdata.image) as an html link, in that case the directly shows the
image on the screen. When the user clicks the submit button i wipe the formdata clean (after adding it to the db first of course) as such
$scope.formdata = [];
this clears all the input fields, however the image stays. I can do this as example:
$scope.formdata.image = "//:0" // broken image link displayed
$scope.formdata.image = "" // does not do anything
$scope.formdata.image = $0; // results in crash
$scope.formdata.image = null; // no result
How would i be able to remove the complete data from the formfield and remove the image display, i don't want to 'ng-hide' the complete image i just want to show the image that is in the background. When one first time loads the form the DevTools elements mentions, you can reference to this expression with ==$0, "use $0 in the console.log to refer to this element" it say's. In this case there is no data.
To be able to clear all the data of a form one could use the $destroy.
$scope.formdata.$destroy

Jquery doesn't update an attribute as expected

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'));

Codeigniter dynamic javascript when using load->view

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')

Javascript Submit With GetElementByID - Open in New Window

I have a page called "review.asp" with a form that produces a list of records from a database. If the user wants to see more information about a particular record, they just click on the "prjName" field, which is a hyperlink. Then, the page will submit and display information about the record. Currently, this opens in the same window. I'd like it to open to a new window.
Additionally, I don't want to just put a target = _blank in the form part of the HTML because this page does several submits and I don't want them ALL to open in a new window - just this one below. So, I'm hoping there is a solution for this within the Javascript?
Thanks in advance!
My HTML:
<form name="frmPrjReview" id="frmPrjReview" method="post">
<p><a href="javascript:selectRecID('<%= RS("recID")%>')";><%=RS("prjName")%></a></p>
My current Javascript:
function selectRecID(recID)
{
//Set the value of the hidden text field = to the record ID in the table.
document.getElementById("txtRecID").value = recID;
var submitSearch = document.getElementById("frmPrjReview");
submitSearch.action = "review.asp";
submitSearch.submit();
}
Set the target programatically when you need it:
var submitSearch = document.getElementById("frmPrjReview");
...
submitSearch.setAttribute("target", "_blank");
submitSearch.submit();
submitSearch.removeAttribute("target")
EDIT: to add removal.

set Tweet button 'data-text' contents dynamically with javascript, or..?

Here is functioning code on a form that displays a Tweet button -- the button's on a form that displays several images -- when the user clicks one of the images, it becomes the 'selected' image and the Tweet button is supposed to tweet the selected image's name and url:
<a id="tweetBtnId" href="https://twitter.com/share" class="twitter-share-button"
data-text="Check me out on OurWebSite!"
data-url=http://$ourSiteURL
data-via=http://$ourSiteURL data-size="medium" data-count="none">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];
if(!d.getElementById(id)){js=d.createElement(s); js.id=id;
js.src="//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js,fjs);}}
(document,"script", "twitter-wjs");</script>
I have an 'onclick()' handler for the div that displays the image. When the user clicks one of the images, its div's onclick() handler is called and sets that image to be the 'currentlySelectedImage' on the page -- and the onclick() handler then needs to update the Tweet button's 'data-text' attribute with the name of the just-selected image:
// This is part of the code of the 'onclick()' handler for
// the image being selected.
<script>
function handleImageOnClick()
{
var myDynamicTweetText = "name of currently-selected image goes here";
var elem = document.getElementById("tweetBtnId");
alert("The elem is: " + elem); // elem IS NULL !! Dagnabbit.
// this fails because 'elem' is null
elem.setAttribute("data-text", myDynamicTweetText);
// other onclick() code not shown for brevity......
}
</script>
I need to dynamically change the 'data-text' attribute's value in the Tweet button to be the name of the selected image. I added the javascript code above which fails-- the 'elem' obtained from the code here:
var elem = document.getElementById("tweetBtnId");
is null (I think) because of this line in the Twitter tweet button code above:
if(!d.getElementById(id)){js=d.createElement(s); js.id=id;
I'm not sure but it looks like the Twitter Tweet button default script overwrites any attempt
to add an 'id' attribute to the Tweet button.
You will see that I added the id="tweetBtnId" to the Tweet button above so I could get access to the Tweet button in my image-selection onclick() handler above, then set the 'data-text' to the name of the just-selected image.
I just doubt that Twitter's design goal for the Tweet button was "we're gonna dumb this sucker WAY down, we'll only let these animals choose ONE data-text value - every Tweet button has to have one hard-coded, "Once-on-the-page" data-text attribute - joke's on them if they try to dynamically change the Tweet button's data-text attribute."
I need to get this to work -- any ideas?
Just put it in a container with a known ID and traverse the document with it:
<div id="someIDiKnow">
<a id="tweetBtnId"...>...</a>
</div>
$("#someIDiKnow a").attr("data-text", "Replacement Text!");
Looks like it's going to be the kludgy hidden form/php variable approach for now -- I'll post back if I find a better work-around.
EDIT: the hidden-form/PHP variable solution has beaten the roadblock put up by Twitter's Tweet button -- I can now successfully, dynamically change the Tweet button text at will, anytime based on the user's client-side input. Per Domenic's astute observation that the question above is too long and has code in it, I'll skip posting the answer here, and I apologize for the length above.
You could use JQuery to update the attribute data-text by adding an onclick action on the image. If you wanted to include the text inside the actual image tag by adding your own attribute to the tag, that could be an easy work around to assembling the tweet text.
For example:
function updateTweetBtn(obj) {
$('#someIDiKnow a').attr('data-text', $(this).attr('tweet'));
}
<img src="/images/myimage.jpg" tweet="This is what I want to tweet" onclick="updateTweetBtn(this);" />
<img src="/images/myimage2.jpg" tweet="This is some other text I want to tweet" onclick="updateTweetBtn(this);" />
using in html
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
Tweet
I managed to change the 'data-text' with javascript
var a = "new text";
document.getElementsByClassName('twitter-share-button')[0].setAttribute("data-text", a);
also worked with document.getElementById('twitter') if you add id='twitter' to <a>

Categories

Resources