How to put a javascript variable into view in mvc 4? - javascript

I know that is a small problem, but i didn't found any solution, so i have a javascript variable <script>
var coords = []; </script> and i want to put it in my view :
<input type="submit" name="Tracking" value="Tracking" data-coords="//here !!!"/>
so please if someone have any idea i will be very appreciate.

Method 1;
You Can use this code;
$("[name='Tracking']").attr("data-coords",coords);
Method 2;
if dont required use data-coords
you can use jquery .data()..
replace this;
<input type="submit" id="Tracking" name="Tracking" value="Tracking"/>
and
$("#Tracking").data("data-coords", coords);

You can handle it on the client side:
// javascript version
// safe, if you have only one element that has a name "Tracking"
var btn = document.getElementsByName("Tracking")[0].value;
var a = document.createAttribute('data-coords');
a.value = coords;
btn.setAttributeNode(a);
// or do it easier with jquery
$('[name="Tracking"]').attr('data-coords', coords);

If you want to set dynamic values to something in your HTML, you should use JavaScript to do it. The exact way of doing this depends on context - when exactly you want to set those values and what you want to do with them before.
If you want to set value of data-coords on DOM load and you use jQuery, write code that updates data-coords attribute of this input inside $(document).ready function. You can use attr function to do this if you use jQuery.

Related

javascript set variable from .text method

I'm new in javascript development and I want to ask how to set variable from text method.
Example: in this code have a text method
$('.phone').text(theRestaurant.phone);
$('.location').text(theRestaurant.location);
$('.info').text(theRestaurant.info);
in the Html file, when I create any class from these will print the value from JSON file.
Example :
<div class='phone'></div>
Output: (000)000-9999
source code:
<div class='phone'>(000)000-9999</div>
I try to set this in variable but it doesn't work.
My try:
var phone = theRestaurant.phone
I want to set it in variable because I need to put it inside href value like so:
<script>
var phone = 'tel:' + phone
document.getElementById("phone").href = phone;
</script>
I hope everything clear. and If have an other solution please tell about it.
Thanks
Have you wrapped your jQuery code in a document.ready() wrapper?
If not, then the javascript might run before the page has had time to create the elements in the DOM, and nothing will work.
<script>
$(document).ready(function(){
//all javascript/jQuery code goes in here
});
</script>
Also, see my comment above about mixing up "ByClassName" and "ByID"
Answer came from #itsgoingdown
this code in main javascript file:
var phone=document.getElementById('phone').innerHTML; document.getElementsByClassName("phone")[0].href = phone;

Add new AngularJS variables with JavaScript

I'm trying to make a dynamic form with AngularJS and JavaScript. The objective is to add how many inputs the user need and transform all those inputs in AngularJS variables that print it on body. So I got that code:
$(function(){
var number = 1;
$('a.add').click(function(e){
e.preventDefault();
$('#this_div_contains_settings').append('<input type="text" name="example'+number+'" ng-model="example'+number+'" placeholder="Anything">');
number++;
});
$('#this_div_contains_settings').on('click','a.design_button', function(e){
e.preventDefault();
$(this).parent().remove();
});
});
This function add a INPUT on my DIV with the different ng-model every time it run.
The problem is, it just work's if the {{example1}} is already on my BODY, if I add it later with another function, it just doesn't work.
I'm new with AngularJS, so I didn't understand if I need to "refresh" the AngularJS everytime I add new variable or something like that.
Any help will be appreciated :)
Using jQuery is the wrong way to solve this problem. Instead, create an array inside of your controller that will hold the models for all of these inputs.
Depending on how you define/create your controllers, $scope may be replaced with this
$scope.examples = [];
Next, create a function that will add a new example to the array:
$scope.addExample = function () {
$scope.examples.push("");
}
Now, in your template, create the inputs using an ng-repeat:
<div id="this_div_contains_settings">
<input ng-repeat="example in examples" type="text" name="example" ng-model="example" placeholder="Anything">
</div>
and have your "add" button call your addExample function on click:
<a class="add" ng-click="addExample()">Add Example</a>
Finally, remove all of the code that was included in your question.
And for your .design_button that removes all the examples, that's easy too:
<a class="design_button" ng-click="examples = []">remove all examples!</a>
by that same concept, you could even remove the need for the addExample function, however i tend to keep logic in the controller (well, actually in the services, but that's another topic) anyway rather than putting it in the template.

Save data in html tag attribute

How save some data as html tag atribute? For example, given data asd/45.33/blah, I need save this data in html and after using jquery get this data so:
$("#my_tag").attr("special_attribute");
its possible?
Using custom attributes makes your document invalid, you can use HTML5 data-* attributes and for getting/setting values using jQuery, you can use data method, for example if you have a data attribute called data-special you can get the value of it in this way:
var value = $("#my_tag").data("special");
and set/change the value in this way:
$("#my_tag").data("special", "value");
http://api.jquery.com/data/
If you need to use it with jQuery then a better way to do it is to use data- attibutes.
Declaring a html tag will look like:
<div id="myDiv" data-url="asd/45.33/blah"></div>
Using data is as simple as:
var url = $('#myDiv').data('url')
More about jQuery data.
Question about attr vs data.
USE attr() it is used for getting the value as well as for setting the attribute value.
$("#my_tag").attr("special_attribute",'asd/45.33/blah');
Details http://api.jquery.com/attr/
Yes it is possible. However it won't validate.
Yes you can. I think you should use an hidden field for this purpose:
<input type="hidden" id="my_tag" />
and then access it via jquery :
$("#my_tag").attr("value", "myvalue");
$("#my_tag").attr("value");
You can save value in html element as :
$("htmlelement").data("key","value");
in your case it would be :
$("#my_tag").data("special_attribute","asd/45.33/blah");
var html = "<p>HTML</p>";
$("#my_tag").attr("special_attribute", function() {
return html;
});
Now retrieve it with:
var s = $("#my_tag").attr("special_attribute");
alert(s)

Copying INPUT FILE value to INPUT TEXT with click in jQuery

I would like to copy the value of a input:file to input:text. I can do it with plan JavaScript but I will like to know how to do it with jQuery.
----JavaScript
// This what the script would look like with plain JavaScript
// It works fine. I just woulld like to know who to do it with jQuery.
function fakeScript() {
var filepath;
filepath = document.adminForm.tumb.value;
filepath = filepath.substring(filepath.lastIndexOf('\\')+1, filepath.length);
document.adminForm.tumbFake.value = filepath;
}
If you have something that works in "plain Javascript", it'll work with jQuery too : jQUery is just a library, that adds functions -- it doesn't prevent anything from working (or there is some kind of bug in it ^^ )
var fileValue=$("input[type='file']").val();
var inputValue=$("input[type='text']").val(fileValue);
cheers
You probably cannot use the value attribute of a file input with JQuery.
"The value attribute cannot be used with <input type="file">." - http://www.w3schools.com/tags/att_input_value.asp
To get the text value of a file from an <input type="file"/> element, use yourFileInputElement.files[0].getAsText("utf-8").

How to use YUI to locate an Input by Name and insert content after

How can I use YUI to locate a text input by name and insert a div after it?
For example, this doesn't work:
<input name="some_name" type="text">
<script>
var el = new YAHOO.util.Element(document.createElement('div'));
var some_element = document.getElementsByName('some_name');
// doesn't work .... replacing 'some_element' with 'document.body' works
el.appendTo(some_element);
</script>
As mentioned, document.getElementsByName returns an array. You may want to give your input an ID with the same name as the name attribute. (Aside: This is common and good practice for forms. Other js libraries provide helpful extensions when you do this.)
<input name="some_name" id="some_name" type="text">
<script>
(function () {
var el = new YAHOO.util.Element(document.createElement('div'));
// var some_element = document.getElementByName('some_name')[0];
var some_element = document.getElementsById('some_name'); // preferred, faster
// el.appendTo(some_element);
YAHOO.util.Dom.insertAfter(el,some_element);
})();
</script>
Also notice the use of insertAfter rather than appendTo. You do not want el to be a child of your input element. You want it to be the next sibling. Inputs do not have children. Also lastly, you're adding these variables to the global namespace. This may or may not be a problem, but it's generally a good idea to wrap your code in an anonymous function unless you intend for the variables to have global scope and reuse them later, but then you might want to provide a proper namespace for them.
Hope that helps (and not too much info.) ;)
document.getElementsByName('some_name') always return a collection (an Array), if you are sure that the name is unique you can safely write this.
var some_element = document.getElementsByName('some_name')[0];
With YUI 3 you can now do this:
<script src="http://yui.yahooapis.com/3.18.1/build/yui/yui-min.js"></script>
<input id="some_id" type="text">
<script>
YUI().use('node', function(Y) {
var contentNode = Y.Node.create('<p>');
contentNode.setHTML('This is a para created by YUI...');
Y.one('#some_id').insert(contentNode, 'after');
});
</script>
But keep in mind YUI is being discontinued!
You basically put a condition and say name="some_name".
See the code below and observe that is still does insert the aragraph.
<script src="http://yui.yahooapis.com/3.18.1/build/yui/yui-min.js"></script>
<input id="some_id" type="text" name="inpuname" >
<script>
YUI().use('node', function(Y) {
var contentNode = Y.Node.create('<p>');
contentNode.setHTML('Paragraph created by YUI by searching for *INPUNAME*...');
Y.one('input[name="inpuname"]').insert(contentNode, 'after');
});
</script>

Categories

Resources